From 84608f2f580adf300dacce46355183fd216e70ec Mon Sep 17 00:00:00 2001 From: Pahansith Date: Thu, 5 Nov 2020 09:49:39 +0530 Subject: [PATCH 01/17] Fix issue in Geo fence get by fence name --- .../impl/GeoLocationBasedServiceImpl.java | 2 +- .../mgt/core/dao/impl/GeofenceDAOImpl.java | 30 ++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java index aa41922d5a6..144b1228b7e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java @@ -659,7 +659,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { @QueryParam("name") String name) { try { GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); - if (offset != 0 && limit != 0) { + if (offset >= 0 && limit != 0) { PaginationRequest request = new PaginationRequest(offset, limit); if (name != null && !name.isEmpty()) { request.setProperty(DeviceManagementConstants.GeoServices.FENCE_NAME, name); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GeofenceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GeofenceDAOImpl.java index 452c2ecc3a8..e02c3811962 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GeofenceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GeofenceDAOImpl.java @@ -166,7 +166,35 @@ public class GeofenceDAOImpl implements GeofenceDAO { @Override public List getGeoFencesOfTenant(String fenceName, int tenantId) throws DeviceManagementDAOException { - return null; + try { + List geofenceData; + Connection conn = this.getConnection(); + String sql = "SELECT " + + "ID, " + + "FENCE_NAME, " + + "DESCRIPTION, " + + "LATITUDE, " + + "LONGITUDE, " + + "RADIUS, " + + "GEO_JSON, " + + "FENCE_SHAPE, " + + "OWNER, " + + "TENANT_ID " + + "FROM DM_GEOFENCE " + + "WHERE FENCE_NAME LIKE ? AND TENANT_ID = ? "; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, fenceName + "%"); + stmt.setInt(2, tenantId); + try (ResultSet rst = stmt.executeQuery()) { + geofenceData = extractGeofenceData(rst); + } + } + return geofenceData; + } catch (SQLException e) { + String msg = "Error occurred while retrieving Geofence of the tenant " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } } @Override From 65266e068599fd45f18c12e1484404e116fb784c Mon Sep 17 00:00:00 2001 From: Saad Sahibjan Date: Mon, 9 Nov 2020 19:48:24 +0530 Subject: [PATCH 02/17] Handle re-applying of failed policies via monitoring through a different operation code --- .../policy/mgt/core/impl/ComplianceDecisionPointImpl.java | 2 +- .../carbon/policy/mgt/core/util/PolicyManagementConstants.java | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java index 5914f223ca6..2c0ba22e8a3 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java @@ -153,7 +153,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint { PolicyOperation policyOperation = new PolicyOperation(); policyOperation.setEnabled(true); policyOperation.setType(Operation.Type.POLICY); - policyOperation.setCode(PolicyOperation.POLICY_OPERATION_CODE); + policyOperation.setCode(PolicyManagementConstants.MONITOR_POLICY_BUNDLE); if (complianceData.isCompletePolicy()) { List effectiveFeatures = policy.getProfile().getProfileFeaturesList(); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java index e945f98127a..3841662c2cb 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java @@ -40,6 +40,7 @@ public final class PolicyManagementConstants { public static final String DEVICE_CONFIG_XML_NAME = "cdm-config.xml"; public static final String ANY = "ANY"; public static final String POLICY_BUNDLE = "POLICY_BUNDLE"; + public static final String MONITOR_POLICY_BUNDLE = "MONITOR_POLICY_BUNDLE"; public static final String TENANT_ID = "TENANT_ID"; From 2789a7122ce6bb8a0ad93c5e43893c43a8a64e05 Mon Sep 17 00:00:00 2001 From: Pahansith Gunathilake Date: Tue, 10 Nov 2020 02:24:20 +0000 Subject: [PATCH 03/17] Remove old geofence policy transformation --- .../core/util/PolicyManagementConstants.java | 1 - .../mgt/core/util/PolicyManagerUtil.java | 66 ------------------- 2 files changed, 67 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java index 4e608040e12..4ef2027297d 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java @@ -68,7 +68,6 @@ public final class PolicyManagementConstants { public static final String POLICY_FEATURE_CODE = "POLICY_ACTION"; public static final String POLICY_ACTIONS = "POLICY_ACTIONS"; public static final String CORRECTIVE_POLICY_FEATURE_CODE = "CORRECTIVE_POLICY"; - public static final String GEOFENCE_POLICY = "GEOFENCE_POLICY"; public static final String EMAIL_CORRECTIVE_ACTION_TYPE = "MAIL"; public static final String EMAIL_FEATURE_CODE = "EMAIL_ACTION"; public static final Integer EMAIL_ACTION_ID = 450; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java index 51ab59b4ebd..fe4cb939be0 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java @@ -48,15 +48,12 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; -import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException; -import org.wso2.carbon.device.mgt.common.geo.service.GeofenceData; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.policy.mgt.CorrectiveAction; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.config.tenant.PlatformConfigurationManagementServiceImpl; -import org.wso2.carbon.device.mgt.core.geo.service.GeoLocationProviderServiceImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; @@ -161,7 +158,6 @@ public class PolicyManagerUtil { } if (payloadVersion >= 2.0f) { setMultipleCorrectiveActions(effectiveFeatures, policyOperation, policy); - transformGeoFencePolicy(effectiveFeatures, policyOperation, policy); } else { setSingleCorrectiveAction(policy, effectiveFeatures); } @@ -170,68 +166,6 @@ public class PolicyManagerUtil { return policyOperation; } - /** - * Transform geofence policy payload - * @param effectiveFeatures feature list of the policy - * @param policyOperation operation object - * @param policy related policy object - * @throws PolicyTransformException if any error occurs while transforming geo fence policy - */ - private static void transformGeoFencePolicy(List effectiveFeatures, - PolicyOperation policyOperation, Policy policy) throws PolicyTransformException { - String payload = null; - int fenceId = -1; - for (ProfileFeature effectiveFeature : effectiveFeatures) { - if (effectiveFeature.getFeatureCode().equals(PolicyManagementConstants.GEOFENCE_POLICY)) { - payload = effectiveFeature.getContent().toString(); - break; - } - } - if (payload != null) { - for (ProfileOperation profileOperation : policyOperation.getProfileOperations()) { - try { - if (profileOperation.getCode().equals(PolicyManagementConstants.GEOFENCE_POLICY)) { - JsonParser jsonParser = new JsonParser(); - JsonElement parsedPayload = jsonParser.parse(payload); - JsonObject jsonPayload = parsedPayload.getAsJsonObject(); - GeoLocationProviderServiceImpl geoLocationProviderService = new GeoLocationProviderServiceImpl(); - if (jsonPayload.get("fenceId") == null) { - String msg = "No valid fence Id found in saved policy payload"; - log.error(msg); - throw new PolicyTransformException(msg); - } - fenceId = jsonPayload.get("fenceId").getAsInt(); - if (log.isDebugEnabled()) { - log.debug("Retrieving geofence with ID " + fenceId); - } - GeofenceData geofence = geoLocationProviderService.getGeoFences(fenceId); - if (geofence != null) { - JsonObject operationPayload = new JsonObject(); - operationPayload.addProperty("fenceId", geofence.getId()); - operationPayload.addProperty("latitude", geofence.getLatitude()); - operationPayload.addProperty("longitude", geofence.getLongitude()); - operationPayload.addProperty("radius", geofence.getRadius()); - operationPayload.addProperty("name", geofence.getFenceName()); - operationPayload.addProperty("fenceShape", geofence.getFenceShape()); - operationPayload.addProperty("geoJson", geofence.getGeoJson()); - profileOperation.setPayLoad(operationPayload.toString()); - } - } - } catch (GeoLocationBasedServiceException e) { - String msg = "Error occurred while retrieving geofence with fence Id " + fenceId - + " for the policy with Id "+policy.getId(); - log.error(msg); - throw new PolicyTransformException(msg); - } - } - } else { - if (log.isDebugEnabled()) { - String msg = "No Geofence feature attached with the policy " + policy.getId(); - log.debug(msg); - } - } - } - /** * This method is used for generate single corrective action set for a single policy which is * bind to the policy payload From 5d34b0671e9d1caed89cdb9e3251c77b1c1f48c1 Mon Sep 17 00:00:00 2001 From: charitha Date: Tue, 10 Nov 2020 08:08:48 +0530 Subject: [PATCH 04/17] Add new Enrollment statuses for IoT devices --- .../java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java index 796110b63e3..924c0aec856 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java @@ -30,7 +30,9 @@ public class EnrolmentInfo implements Serializable { private static final long serialVersionUID = 1998101712L; public enum Status { - CREATED, ACTIVE, INACTIVE, UNREACHABLE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED, DISENROLLMENT_REQUESTED + CREATED, ACTIVE, INACTIVE, UNREACHABLE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED, DISENROLLMENT_REQUESTED, + CONFIGURED, READY_TO_CONNECT, RETURN_PENDING, RETURNED, DEFECTIVE, WARRANTY_PENDING, WARRANTY_SENT, + WARRANTY_REPLACED } public enum OwnerShip { From bbf580d43ad89d82ed556421117f4601d4e0cf04 Mon Sep 17 00:00:00 2001 From: Farheen99 Date: Tue, 10 Nov 2020 22:16:57 +0530 Subject: [PATCH 05/17] Hide package name METADATA for web clip apps only --- .../components/ReleasePage/components/ReleaseView/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/components/ReleasePage/components/ReleaseView/index.js b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/components/ReleasePage/components/ReleaseView/index.js index fa6307d6b0b..3e1b2867484 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/components/ReleasePage/components/ReleaseView/index.js +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/components/ReleasePage/components/ReleaseView/index.js @@ -153,7 +153,7 @@ class ReleaseView extends React.Component { metaData = JSON.parse(release.metaData); // eslint-disable-next-line no-empty } catch (e) {} - if (app.hasOwnProperty('packageName')) { + if (app.type !== 'WEB_CLIP' && app.hasOwnProperty('packageName')) { metaData.push({ key: 'Package Name', value: app.packageName, From d25779774bb017c5be639668e43e6e36aff85e48 Mon Sep 17 00:00:00 2001 From: "tcdlpds@gmail.com" Date: Sat, 7 Nov 2020 00:31:02 +0530 Subject: [PATCH 06/17] Improve MDM policy functionality --- ...ApplicationManagementPublisherAPIImpl.java | 14 +-- .../impl/PolicyManagementServiceImpl.java | 10 +- .../policy/mgt/PolicyMonitoringManager.java | 1 - .../DeviceManagementProviderServiceImpl.java | 1 - .../mgt/DefaultPolicyMonitoringManager.java | 7 +- .../mgt/core/dao/impl/MonitoringDAOImpl.java | 13 +- .../mgt/core/dao/impl/PolicyDAOImpl.java | 115 +++--------------- .../mgt/core/enforcement/DelegationTask.java | 15 +-- .../PolicyEnforcementDelegatorImpl.java | 5 +- .../impl/PolicyAdministratorPointImpl.java | 58 +-------- .../mgt/core/impl/PolicyFilterImpl.java | 2 +- .../mgt/bean/UpdatedPolicyDeviceListBean.java | 2 - .../core/mgt/impl/MonitoringManagerImpl.java | 1 - .../mgt/core/mgt/impl/PolicyManagerImpl.java | 6 +- .../mgt/core/mgt/impl/ProfileManagerImpl.java | 31 ++--- .../core/task/TaskScheduleServiceImpl.java | 2 +- 16 files changed, 66 insertions(+), 217 deletions(-) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java index a7dc95940f4..2b53e65da7f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java @@ -334,7 +334,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (ApplicationManagementException e) { - String msg = "Error occurred while creating a costom application"; + String msg = "Error occurred while creating a custom application"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (RequestValidatingException e) { @@ -716,7 +716,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem .changeLifecycleState(applicationUuid, lifecycleChanger); return Response.status(Response.Status.CREATED).entity(applicationRelease).build(); } catch (BadRequestException e) { - String msg = "Request payload contains invalid data, hence veryfy the request payload."; + String msg = "Request payload contains invalid data, hence verify the request payload."; log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).build(); } catch (ForbiddenException e) { @@ -1005,10 +1005,10 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem } if (attachmentList != null && !attachmentList.isEmpty()) { - Map scrrenshotData = new TreeMap<>(); + Map screenshotData = new TreeMap<>(); for (Attachment sc : attachmentList) { dataHandler = sc.getDataHandler(); - String screenshotrFileName = dataHandler.getName(); + String screenshotFileName = dataHandler.getName(); InputStream screenshotStream = dataHandler.getInputStream(); if (screenshotStream == null) { String msg = @@ -1017,16 +1017,16 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem log.error(msg); throw new BadRequestException(msg); } - if (screenshotrFileName == null) { + if (screenshotFileName == null) { String msg = "Screenshot file name retrieving is failed for one screenshot. Hence can't proceed. " + "Please verify the screenshots."; log.error(msg); throw new BadRequestException(msg); } - scrrenshotData.put(screenshotrFileName, screenshotStream); + screenshotData.put(screenshotFileName, screenshotStream); } - applicationArtifact.setScreenshots(scrrenshotData); + applicationArtifact.setScreenshots(screenshotData); } return applicationArtifact; } catch (IOException e) { 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 b92fa01e1d3..fa93c46c60c 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 @@ -136,6 +136,14 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { } } + /** + * GEt {@link Policy} from {@link PolicyWrapper} + * + * @param policyWrapper {@link PolicyWrapper} + * @return {@link Policy} + * @throws DeviceManagementException if error occurred while creating {@link Policy} object from + * {@link PolicyWrapper} + */ private Policy getPolicyFromWrapper(@Valid PolicyWrapper policyWrapper) throws DeviceManagementException { Policy policy = new Policy(); policy.setPolicyName(policyWrapper.getPolicyName()); @@ -151,7 +159,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { policy.setPolicyPayloadVersion(policyWrapper.getPayloadVersion()); policy.setCorrectiveActions(policyWrapper.getCorrectiveActions()); //TODO iterates the device identifiers to create the object. need to implement a proper DAO layer here. - List devices = new ArrayList(); + List devices = new ArrayList<>(); List deviceIdentifiers = policyWrapper.getDeviceIdentifiers(); if (deviceIdentifiers != null) { for (DeviceIdentifier id : deviceIdentifiers) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/policy/mgt/PolicyMonitoringManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/policy/mgt/PolicyMonitoringManager.java index e4bd294e243..dce81f95caf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/policy/mgt/PolicyMonitoringManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/policy/mgt/PolicyMonitoringManager.java @@ -19,7 +19,6 @@ package org.wso2.carbon.device.mgt.common.policy.mgt; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; 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 8aa03908201..d453f88a5d7 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 @@ -150,7 +150,6 @@ import java.io.IOException; import java.io.StringWriter; import java.sql.SQLException; import java.util.ArrayList; -import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java index 8a0bc9c2929..2b44124c1a5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java @@ -25,7 +25,6 @@ import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData; -import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import java.util.ArrayList; import java.util.List; @@ -35,10 +34,10 @@ import java.util.List; */ public class DefaultPolicyMonitoringManager implements PolicyMonitoringManager { - private static Log log = LogFactory.getLog(DefaultPolicyMonitoringManager.class); + private static final Log log = LogFactory.getLog(DefaultPolicyMonitoringManager.class); + @Override - public NonComplianceData checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy, Object response) - throws PolicyComplianceException { + public NonComplianceData checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy, Object response) { if (log.isDebugEnabled()) { log.debug("Checking policy compliance status of device '" + deviceIdentifier.getId() + "'"); } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/MonitoringDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/MonitoringDAOImpl.java index e9f8abcf774..25531d57578 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/MonitoringDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/MonitoringDAOImpl.java @@ -188,14 +188,6 @@ public class MonitoringDAOImpl implements MonitoringDAO { stmt.setInt(4, tenantId); stmt.setInt(5, enrolmentId); stmt.executeUpdate(); - -// generatedKeys = stmt.getGeneratedKeys(); -// if (generatedKeys.next()) { -// return generatedKeys.getInt(1); -// } else { -// return 0; -// } - } catch (SQLException e) { throw new MonitoringDAOException("Error occurred while deleting the none compliance to the database.", e); } finally { @@ -442,7 +434,7 @@ public class MonitoringDAOImpl implements MonitoringDAO { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; - List complianceFeatures = new ArrayList(); + List complianceFeatures = new ArrayList<>(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { @@ -488,8 +480,7 @@ public class MonitoringDAOImpl implements MonitoringDAO { } - private Connection getConnection() throws MonitoringDAOException { + private Connection getConnection() { return PolicyManagementDAOFactory.getConnection(); } - } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java index bf3635cd953..063b5c47a89 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java @@ -75,41 +75,13 @@ public class PolicyDAOImpl implements PolicyDAO { return persistPolicy(policy); } -// @Override -// public Policy addPolicyToDeviceType(String deviceType, Policy policy) throws PolicyManagerDAOException { -// Connection conn; -// PreparedStatement stmt = null; -// try { -// conn = this.getConnection(); -// String query = "INSERT INTO DM_DEVICE_TYPE_POLICY (DEVICE_TYPE_ID, POLICY_ID) VALUES (?, ?)"; -// stmt = conn.prepareStatement(query); -// stmt.setInt(1, getDeviceTypeId(deviceType)); -// stmt.setInt(2, policy.getId()); -// stmt.executeQuery(); -// } catch (SQLException e) { -// throw new PolicyManagerDAOException("Error occurred while adding the device type policy to database.", e); -// } finally { -// PolicyManagementDAOUtil.cleanupResources(stmt, null); -// } -// return policy; -// -// } - @Override public Policy addPolicyToRole(List rolesToAdd, Policy policy) throws PolicyManagerDAOException { Connection conn; PreparedStatement insertStmt = null; -// PreparedStatement deleteStmt = null; -// final List currentRoles = this.getPolicy(policy.getId()).getRoles(); -// -// SetReferenceTransformer transformer = new SetReferenceTransformer(); -// -// transformer.transform(currentRoles, rolesToAdd); -// rolesToAdd = transformer.getObjectsToAdd(); -// List rolesToDelete = transformer.getObjectsToRemove(); try { conn = this.getConnection(); - if (rolesToAdd.size() > 0) { + if (!rolesToAdd.isEmpty()) { String query = "INSERT INTO DM_ROLE_POLICY (ROLE_NAME, POLICY_ID) VALUES (?, ?)"; insertStmt = conn.prepareStatement(query); for (String role : rolesToAdd) { @@ -119,16 +91,6 @@ public class PolicyDAOImpl implements PolicyDAO { } insertStmt.executeBatch(); } -// if (rolesToDelete.size() > 0){ -// String deleteQuery = "DELETE FROM DM_ROLE_POLICY WHERE ROLE_NAME=? AND POLICY_ID=?"; -// deleteStmt = conn.prepareStatement(deleteQuery); -// for (String role : rolesToDelete) { -// deleteStmt.setString(1, role); -// deleteStmt.setInt(2, policy.getId()); -// deleteStmt.addBatch(); -// } -// deleteStmt.executeBatch(); -// } } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while adding the role name with policy to database", e); } finally { @@ -146,14 +108,14 @@ public class PolicyDAOImpl implements PolicyDAO { final List currentRoles = previousPolicy.getRoles(); - SetReferenceTransformer transformer = new SetReferenceTransformer(); + SetReferenceTransformer transformer = new SetReferenceTransformer<>(); transformer.transform(currentRoles, rolesToAdd); rolesToAdd = transformer.getObjectsToAdd(); List rolesToDelete = transformer.getObjectsToRemove(); try { conn = this.getConnection(); - if (rolesToAdd.size() > 0) { + if (!rolesToAdd.isEmpty()) { String query = "INSERT INTO DM_ROLE_POLICY (ROLE_NAME, POLICY_ID) VALUES (?, ?)"; insertStmt = conn.prepareStatement(query); for (String role : rolesToAdd) { @@ -163,7 +125,7 @@ public class PolicyDAOImpl implements PolicyDAO { } insertStmt.executeBatch(); } - if (rolesToDelete.size() > 0) { + if (!rolesToDelete.isEmpty()) { String deleteQuery = "DELETE FROM DM_ROLE_POLICY WHERE ROLE_NAME=? AND POLICY_ID=?"; deleteStmt = conn.prepareStatement(deleteQuery); for (String role : rolesToDelete) { @@ -186,17 +148,9 @@ public class PolicyDAOImpl implements PolicyDAO { public Policy addPolicyToUser(List usersToAdd, Policy policy) throws PolicyManagerDAOException { Connection conn; PreparedStatement insertStmt = null; -// PreparedStatement deleteStmt = null; -// final List currentUsers = this.getPolicy(policy.getId()).getUsers(); -// -// SetReferenceTransformer transformer = new SetReferenceTransformer(); -// -// transformer.transform(currentUsers, usersToAdd); -// usersToAdd = transformer.getObjectsToAdd(); -// List usersToDelete = transformer.getObjectsToRemove(); try { conn = this.getConnection(); - if (usersToAdd.size() > 0) { + if (!usersToAdd.isEmpty()) { String query = "INSERT INTO DM_USER_POLICY (POLICY_ID, USERNAME) VALUES (?, ?)"; insertStmt = conn.prepareStatement(query); for (String username : usersToAdd) { @@ -206,22 +160,10 @@ public class PolicyDAOImpl implements PolicyDAO { } insertStmt.executeBatch(); } -// if (usersToDelete.size() > 0){ -// String deleteQuery = "DELETE FROM DM_USER_POLICY WHERE USERNAME=? AND POLICY_ID=?"; -// deleteStmt = conn.prepareStatement(deleteQuery); -// for (String username : usersToDelete) { -// deleteStmt.setString(1, username); -// deleteStmt.setInt(2, policy.getId()); -// deleteStmt.addBatch(); -// } -// deleteStmt.executeBatch(); -// } - } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while adding the user name with policy to database", e); } finally { PolicyManagementDAOUtil.cleanupResources(insertStmt, null); -// PolicyManagementDAOUtil.cleanupResources(deleteStmt, null); } return policy; } @@ -234,14 +176,14 @@ public class PolicyDAOImpl implements PolicyDAO { PreparedStatement deleteStmt = null; final List currentUsers = policy.getUsers(); - SetReferenceTransformer transformer = new SetReferenceTransformer(); + SetReferenceTransformer transformer = new SetReferenceTransformer<>(); transformer.transform(currentUsers, usersToAdd); usersToAdd = transformer.getObjectsToAdd(); List usersToDelete = transformer.getObjectsToRemove(); try { conn = this.getConnection(); - if (usersToAdd.size() > 0) { + if (!usersToAdd.isEmpty()) { String query = "INSERT INTO DM_USER_POLICY (POLICY_ID, USERNAME) VALUES (?, ?)"; insertStmt = conn.prepareStatement(query); for (String username : usersToAdd) { @@ -251,7 +193,7 @@ public class PolicyDAOImpl implements PolicyDAO { } insertStmt.executeBatch(); } - if (usersToDelete.size() > 0) { + if (!usersToDelete.isEmpty()) { String deleteQuery = "DELETE FROM DM_USER_POLICY WHERE USERNAME=? AND POLICY_ID=?"; deleteStmt = conn.prepareStatement(deleteQuery); for (String username : usersToDelete) { @@ -328,7 +270,6 @@ public class PolicyDAOImpl implements PolicyDAO { String query = "SELECT ACTION_TYPE, CORRECTIVE_POLICY_ID, FEATURE_ID, POLICY_ID, IS_REACTIVE " + "FROM DM_POLICY_CORRECTIVE_ACTION "; try (PreparedStatement stmt = conn.prepareStatement(query)) { - List correctiveActions = new ArrayList<>(); return extractCorrectivePolicies(stmt); } } catch (SQLException e) { @@ -826,7 +767,7 @@ public class PolicyDAOImpl implements PolicyDAO { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; - List criteria = new ArrayList(); + List criteria = new ArrayList<>(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { conn = this.getConnection(); @@ -912,8 +853,6 @@ public class PolicyDAOImpl implements PolicyDAO { } stmt.executeBatch(); } - // stmt.executeUpdate(); - } catch (SQLException | IOException e) { throw new PolicyManagerDAOException("Error occurred while inserting the criterion properties " + "to database", e); @@ -928,7 +867,7 @@ public class PolicyDAOImpl implements PolicyDAO { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; - List criteria = new ArrayList(); + List criteria = new ArrayList<>(); try { conn = this.getConnection(); String query = "SELECT DPC.ID, DPC.CRITERIA_ID, DPCP.PROP_KEY, DPCP.PROP_VALUE, DPCP.CONTENT FROM " + @@ -1152,7 +1091,6 @@ public class PolicyDAOImpl implements PolicyDAO { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; - List policies = new ArrayList(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { @@ -1180,7 +1118,7 @@ public class PolicyDAOImpl implements PolicyDAO { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; - List deviceIdList = new ArrayList(); + List deviceIdList = new ArrayList<>(); try { conn = this.getConnection(); String query = "SELECT * FROM DM_DEVICE_POLICY WHERE POLICY_ID = ?"; @@ -1204,7 +1142,7 @@ public class PolicyDAOImpl implements PolicyDAO { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; - List roleNames = new ArrayList(); + List roleNames = new ArrayList<>(); try { conn = this.getConnection(); String query = "SELECT * FROM DM_ROLE_POLICY WHERE POLICY_ID = ?"; @@ -1229,7 +1167,7 @@ public class PolicyDAOImpl implements PolicyDAO { PreparedStatement stmt = null; ResultSet resultSet = null; - List users = new ArrayList(); + List users = new ArrayList<>(); try { conn = this.getConnection(); String query = "SELECT * FROM DM_USER_POLICY WHERE POLICY_ID = ?"; @@ -1387,7 +1325,7 @@ public class PolicyDAOImpl implements PolicyDAO { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; - List policyIds = new ArrayList(); + List policyIds = new ArrayList<>(); try { conn = this.getConnection(); String query = "SELECT * FROM DM_DEVICE_POLICY WHERE DEVICE_ID = ? "; @@ -1411,7 +1349,7 @@ public class PolicyDAOImpl implements PolicyDAO { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; - List policyIds = new ArrayList(); + List policyIds = new ArrayList<>(); try { conn = this.getConnection(); String query = "SELECT * FROM DM_ROLE_POLICY WHERE ROLE_NAME = ? "; @@ -1435,7 +1373,7 @@ public class PolicyDAOImpl implements PolicyDAO { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; - List policyIds = new ArrayList(); + List policyIds = new ArrayList<>(); try { conn = this.getConnection(); String query = "SELECT * FROM DM_USER_POLICY WHERE USERNAME = ? "; @@ -1563,16 +1501,6 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); -// String userPolicy = "DELETE FROM DM_USER_POLICY WHERE POLICY_ID = ?"; -// stmt = conn.prepareStatement(userPolicy); -// stmt.setInt(1, policyId); -// stmt.executeUpdate(); -// -// String rolePolicy = "DELETE FROM DM_ROLE_POLICY WHERE POLICY_ID = ?"; -// stmt = conn.prepareStatement(rolePolicy); -// stmt.setInt(1, policyId); -// stmt.executeUpdate(); - String devicePolicy = "DELETE FROM DM_DEVICE_POLICY WHERE POLICY_ID = ?"; stmt = conn.prepareStatement(devicePolicy); stmt.setInt(1, policyId); @@ -1601,7 +1529,7 @@ public class PolicyDAOImpl implements PolicyDAO { } } - private Connection getConnection() throws PolicyManagerDAOException { + private Connection getConnection() { return PolicyManagementDAOFactory.getConnection(); } @@ -1821,15 +1749,6 @@ public class PolicyDAOImpl implements PolicyDAO { } finally { PolicyManagementDAOUtil.cleanupResources(stmt, resultSet); } -// -// if (policy != null && log.isDebugEnabled()) { -// log.debug("Applied policy logging details started ------------------"); -// log.debug("Applied policy name " + policy.getPolicyName() + "for the device id " + deviceId); -// log.debug(policy.getCompliance()); -// log.debug(policy.getId()); -// log.debug(policy.getPriorityId()); -// log.debug("Applied policy logging details finished...."); -// } return policy; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java index 2cb4a295734..3c377b156c1 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java @@ -41,7 +41,8 @@ import java.util.Map; public class DelegationTask implements Task { private static final Log log = LogFactory.getLog(DelegationTask.class); - private PolicyConfiguration policyConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getPolicyConfiguration(); + private PolicyConfiguration policyConfiguration = DeviceConfigurationManager.getInstance() + .getDeviceManagementConfig().getPolicyConfiguration(); @Override public void setProperties(Map map) { @@ -73,21 +74,17 @@ public class DelegationTask implements Task { List toBeNotified; for (String deviceType : deviceTypes) { try { - devices = new ArrayList<>(); toBeNotified = new ArrayList<>(); - devices.addAll(service.getAllDevices(deviceType, false)); - //HashMap deviceIdPolicy = policyManager.getAppliedPolicyIdsDeviceIds(); + devices = new ArrayList<>(service.getAllDevices(deviceType, false)); for (Device device : devices) { - // if (deviceIdPolicy.containsKey(device.getId())) { if (device != null && device.getEnrolmentInfo() != null - && device.getEnrolmentInfo().getStatus() != EnrolmentInfo.Status.REMOVED) { + && device.getEnrolmentInfo().getStatus() != EnrolmentInfo.Status.REMOVED) { toBeNotified.add(device); } - // } } if (!toBeNotified.isEmpty()) { - PolicyEnforcementDelegator enforcementDelegator = new PolicyEnforcementDelegatorImpl - (toBeNotified, updatedPolicyDeviceList.getUpdatedPolicyIds()); + PolicyEnforcementDelegator enforcementDelegator = new PolicyEnforcementDelegatorImpl( + toBeNotified, updatedPolicyDeviceList.getUpdatedPolicyIds()); enforcementDelegator.delegate(); } } catch (DeviceManagementException e) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java index 12ce24e824b..3667f258c61 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java @@ -122,7 +122,6 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato return null; } return policy; - //return PolicyManagementDataHolder.getInstance().getPolicyEvaluationPoint().getEffectivePolicy(identifier); } catch (PolicyEvaluationException | PolicyManagementException e) { String msg = "Error occurred while retrieving the effective policy for devices."; log.error(msg, e); @@ -135,7 +134,7 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato PolicyDelegationException { try { String type = null; - if (deviceIdentifiers.size() > 0) { + if (!deviceIdentifiers.isEmpty()) { type = deviceIdentifiers.get(0).getType(); } PolicyManagementDataHolder.getInstance().getDeviceManagementService().addOperation(type, @@ -161,7 +160,7 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato public void addPolicyRevokeOperation(List deviceIdentifiers) throws PolicyDelegationException { try { String type = null; - if (deviceIdentifiers.size() > 0) { + if (!deviceIdentifiers.isEmpty()) { type = deviceIdentifiers.get(0).getType(); } PolicyManagementDataHolder.getInstance().getDeviceManagementService().addOperation(type, diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java index c555b27b976..9c4be122af1 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java @@ -34,10 +34,8 @@ import org.wso2.carbon.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.core.cache.PolicyCacheManager; import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; -import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; import org.wso2.carbon.policy.mgt.core.mgt.ProfileManager; -import org.wso2.carbon.policy.mgt.core.mgt.impl.FeatureManagerImpl; import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; import org.wso2.carbon.policy.mgt.core.mgt.impl.ProfileManagerImpl; import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants; @@ -53,28 +51,18 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { private PolicyManager policyManager; private ProfileManager profileManager; - private FeatureManager featureManager; - private PolicyCacheManager cacheManager; private PolicyConfiguration policyConfiguration; - // private PolicyEnforcementDelegator delegator; public PolicyAdministratorPointImpl() { this.policyManager = new PolicyManagerImpl(); this.profileManager = new ProfileManagerImpl(); - this.featureManager = new FeatureManagerImpl(); - this.cacheManager = PolicyCacheManagerImpl.getInstance(); - this.policyConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getPolicyConfiguration(); - // this.delegator = new PolicyEnforcementDelegatorImpl(); + this.policyConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig() + .getPolicyConfiguration(); } @Override public Policy addPolicy(Policy policy) throws PolicyManagementException { Policy resultantPolicy = policyManager.addPolicy(policy); -// try { -// delegator.delegate(resultantPolicy, resultantPolicy.getDevices()); -// } catch (PolicyDelegationException e) { -// throw new PolicyManagementException("Error occurred while delegating policy operation to the devices", e); -// } if (policyConfiguration.getCacheEnable()) { PolicyCacheManagerImpl.getInstance().rePopulateCache(); } @@ -84,11 +72,6 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { @Override public Policy updatePolicy(Policy policy) throws PolicyManagementException { Policy resultantPolicy = policyManager.updatePolicy(policy); -// try { -// delegator.delegate(resultantPolicy, resultantPolicy.getDevices()); -// } catch (PolicyDelegationException e) { -// throw new PolicyManagementException("Error occurred while delegating policy operation to the devices", e); -// } if (policyConfiguration.getCacheEnable()) { PolicyCacheManagerImpl.getInstance().rePopulateCache(); } @@ -190,7 +173,6 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { } } } - } catch (TaskException e) { String msg = "Error occurred while creating the policy delegation task for tenant " + PrivilegedCarbonContext. @@ -198,42 +180,6 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { log.error(msg, e); throw new PolicyManagementException(msg, e); } - -// List deviceTypes = policyManager.applyChangesMadeToPolicies(); -// -// if(log.isDebugEnabled()) { -// log.debug("Number of device types which policies are changed .......... : " + deviceTypes.size() ); -// } -// -// if (!deviceTypes.isEmpty()) { -// -// -// DeviceManagementProviderService service = PolicyManagementDataHolder.getInstance() -// .getDeviceManagementService(); -// List devices = new ArrayList<>(); -// for (DeviceType deviceType : deviceTypes) { -// try { -// devices.addAll(service.getAllDevices(deviceType.getName())); -// } catch (DeviceManagementException e) { -// throw new PolicyManagementException("Error occurred while taking the devices", e); -// } -// } -// HashMap deviceIdPolicy = policyManager.getAppliedPolicyIdsDeviceIds(); -// List toBeNotified = new ArrayList<>(); -// -// for (Device device : devices) { -// if (deviceIdPolicy.containsKey(device.getId())) { -// toBeNotified.add(device); -// } -// } -// if (!toBeNotified.isEmpty()) { -// -// // ExecutorService executorService = getExecutor(); -// // PolicyEnforcementDelegator enforcementDelegator = new PolicyEnforcementDelegatorImpl(toBeNotified); -//// Thread thread = new Thread(new PolicyEnforcementDelegatorImpl(toBeNotified)); -//// thread.start(); -// } -// } } @Override diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyFilterImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyFilterImpl.java index acb2c48794c..fbb61465d72 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyFilterImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyFilterImpl.java @@ -63,7 +63,7 @@ public class PolicyFilterImpl implements PolicyFilter { } } - List temp = new ArrayList(); + List temp = new ArrayList<>(); for (Policy policy : policies) { if (policy.isActive()) { temp.add(policy); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/bean/UpdatedPolicyDeviceListBean.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/bean/UpdatedPolicyDeviceListBean.java index 2071d1ff5bd..bd0e925565c 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/bean/UpdatedPolicyDeviceListBean.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/bean/UpdatedPolicyDeviceListBean.java @@ -18,8 +18,6 @@ package org.wso2.carbon.policy.mgt.core.mgt.bean; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; -import org.wso2.carbon.device.mgt.core.dto.DeviceType; - import java.util.List; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java index 351da8495e0..65394c71383 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java @@ -32,7 +32,6 @@ import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceData; -import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; 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 159372e73a5..9187676f008 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 @@ -241,9 +241,9 @@ public class PolicyManagerImpl implements PolicyManager { policy.getProfile().setUpdatedDate(currentTimestamp); policy.setPriorityId(previousPolicy.getPriorityId()); policy.setPolicyPayloadVersion(previousPolicy.getPolicyPayloadVersion()); - Policy updatedPolicy = policyDAO.updatePolicy(policy); - profileDAO.updateProfile(policy.getProfile()); + policyDAO.updatePolicy(policy); + profileDAO.updateProfile(policy.getProfile()); featureDAO.updateProfileFeatures(existingFeaturesList, profileId); if (!newFeaturesList.isEmpty()) { featureDAO.addProfileFeatures(newFeaturesList, profileId); @@ -646,8 +646,8 @@ public class PolicyManagerImpl implements PolicyManager { @Override public void inactivatePolicy(int policyId) throws PolicyManagementException { + Policy policy = this.getPolicy(policyId); try { - Policy policy = this.getPolicy(policyId); PolicyManagementDAOFactory.beginTransaction(); policyDAO.inactivatePolicy(policyId); policyDAO.recordUpdatedPolicy(policy); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java index 160d512ee52..d0a79cb53ea 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java @@ -22,8 +22,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.policy.mgt.Profile; import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; -import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; import org.wso2.carbon.policy.mgt.common.ProfileManagementException; import org.wso2.carbon.policy.mgt.core.dao.FeatureDAO; import org.wso2.carbon.policy.mgt.core.dao.FeatureManagerDAOException; @@ -41,17 +39,13 @@ import java.util.List; public class ProfileManagerImpl implements ProfileManager { - private static Log log = LogFactory.getLog(ProfileManagerImpl.class); + private static final Log log = LogFactory.getLog(ProfileManagerImpl.class); private ProfileDAO profileDAO; private FeatureDAO featureDAO; -// private DeviceDAO deviceDAO; - private DeviceTypeDAO deviceTypeDAO; public ProfileManagerImpl() { profileDAO = PolicyManagementDAOFactory.getProfileDAO(); featureDAO = PolicyManagementDAOFactory.getFeatureDAO(); -// deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); - deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); } @Override @@ -68,19 +62,21 @@ public class ProfileManagerImpl implements ProfileManager { PolicyManagementDAOFactory.commitTransaction(); } catch (ProfileManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); - throw new ProfileManagementException("Error occurred while adding the profile (" + - profile.getProfileName() + ")", e); + String msg = "Error occurred while adding the profile (" + profile.getProfileName() + ")"; + log.error(msg, e); + throw new ProfileManagementException(msg, e); } catch (FeatureManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); - throw new ProfileManagementException("Error occurred while adding the profile features (" + - profile.getProfileName() + ")", e); + String msg = "Error occurred while adding the profile features (" + profile.getProfileName() + ")"; + log.error(msg, e); + throw new ProfileManagementException(msg, e); } catch (PolicyManagerDAOException e) { - throw new ProfileManagementException("Error occurred while adding the profile (" + - profile.getProfileName() + ") to the database", e); + String msg = "Error occurred while adding the profile (" + profile.getProfileName() + ") to the database"; + log.error(msg, e); + throw new ProfileManagementException(msg, e); } finally { PolicyManagementDAOFactory.closeConnection(); } - return profile; } @@ -115,7 +111,7 @@ public class ProfileManagerImpl implements ProfileManager { @Override public boolean deleteProfile(Profile profile) throws ProfileManagementException { - boolean bool = true; + boolean bool; try { PolicyManagementDAOFactory.beginTransaction(); featureDAO.deleteFeaturesOfProfile(profile); @@ -173,7 +169,7 @@ public class ProfileManagerImpl implements ProfileManager { for (Profile profile : profileList) { - List list = new ArrayList(); + List list = new ArrayList<>(); for (ProfileFeature profileFeature : featureList) { if (profile.getProfileId() == profileFeature.getProfileId()) { list.add(profileFeature); @@ -204,7 +200,7 @@ public class ProfileManagerImpl implements ProfileManager { featureList = featureDAO.getAllProfileFeatures(); for (Profile profile : profileList) { - List profileFeatureList = new ArrayList(); + List profileFeatureList = new ArrayList<>(); for (ProfileFeature profileFeature : featureList) { if (profile.getProfileId() == profileFeature.getProfileId()) { profileFeatureList.add(profileFeature); @@ -224,5 +220,4 @@ public class ProfileManagerImpl implements ProfileManager { } return profileList; } - } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java index 75a58da1e89..b4b358bc320 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java @@ -38,7 +38,7 @@ import java.util.Map; public class TaskScheduleServiceImpl implements TaskScheduleService { - private static Log log = LogFactory.getLog(TaskScheduleServiceImpl.class); + private static final Log log = LogFactory.getLog(TaskScheduleServiceImpl.class); private PolicyConfiguration policyConfiguration; From 0df8c8d91cb07085559eafafa61864f1319d03ba Mon Sep 17 00:00:00 2001 From: Farheen99 Date: Tue, 10 Nov 2020 21:13:57 +0530 Subject: [PATCH 07/17] Disable publish button for releases with a published app --- .../components/AddNewReleaseForm/index.js | 5 +- .../ApssTable/AppDetailsDrawer/index.js | 16 ++++- .../Release/components/LifeCycle/index.js | 65 ++++++++++++++++--- .../Home/scenes/Apps/scenes/Release/index.js | 1 + 4 files changed, 75 insertions(+), 12 deletions(-) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/AddNewRelease/components/AddNewReleaseForm/index.js b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/AddNewRelease/components/AddNewReleaseForm/index.js index 0ae2d7ae595..6162c4fac0b 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/AddNewRelease/components/AddNewReleaseForm/index.js +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/AddNewRelease/components/AddNewReleaseForm/index.js @@ -127,7 +127,10 @@ class AddNewReleaseFormComponent extends React.Component { description: 'New release was added successfully', }); const uuid = res.data.data.uuid; - this.props.history.push('/publisher/apps/releases/' + uuid); + this.props.history.push({ + pathname: '/publisher/apps/releases/' + uuid, + state: { fullAppDetails: this.props.location.state.fullAppDetails }, + }); } else { this.setState({ loading: false, diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/components/AppList/components/ApssTable/AppDetailsDrawer/index.js b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/components/AppList/components/ApssTable/AppDetailsDrawer/index.js index 3698c5d840d..1a80bc120a3 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/components/AppList/components/ApssTable/AppDetailsDrawer/index.js +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/components/AppList/components/ApssTable/AppDetailsDrawer/index.js @@ -702,7 +702,14 @@ class AppDetailsDrawer extends React.Component { title="Click to view full details" placement="topRight" > - + Add new release for the application + + ); })} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/index.js b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/index.js index 7fb6cdb70e1..91f05673b2a 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/index.js +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/index.js @@ -232,6 +232,7 @@ class Release extends React.Component { this.changeCurrentLifecycleStatus } lifecycle={lifecycle} + appReleases={this.props.location.state} /> )} From fdaf8bd7efa5f86b9da7c4758b818a0dc650e9d7 Mon Sep 17 00:00:00 2001 From: Farheen99 Date: Thu, 12 Nov 2020 06:05:00 +0530 Subject: [PATCH 08/17] Update changes for lifecycle check method --- .../Release/components/LifeCycle/index.js | 39 ++++++++----------- 1 file changed, 17 insertions(+), 22 deletions(-) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/components/LifeCycle/index.js b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/components/LifeCycle/index.js index fc815d61f05..5660802b5ac 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/components/LifeCycle/index.js +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/components/LifeCycle/index.js @@ -77,6 +77,7 @@ class LifeCycle extends React.Component { current: 0, lifecycleSteps: [], lifeCycleStates: [], + isPublished: false, }; } @@ -91,6 +92,10 @@ class LifeCycle extends React.Component { lifecycleSteps, }); this.getLifeCycleHistory(); + + this.setState({ + isPublished: this.checkReleaseLifeCycleStatus(), + }); } componentDidUpdate(prevProps, prevState, snapshot) { @@ -204,26 +209,18 @@ class LifeCycle extends React.Component { state or not and assigned a boolean value to disable the publish button if an app release is already published */ - checkReleaseLifeCycleStatus = (proceedingStates, lifecycleState) => { + checkReleaseLifeCycleStatus = () => { if (typeof this.props.appReleases !== 'undefined') { - const currentAppUUID = this.props.uuid; let appReleases = this.props.appReleases.fullAppDetails; - let appRelease; - let isPublished; for (let i = 0; i < appReleases.length; i++) { - appRelease = appReleases[i]; if ( - currentAppUUID !== appRelease.uuid && - appRelease.currentStatus === 'PUBLISHED' && - proceedingStates.includes('PUBLISHED') && - lifecycleState === 'PUBLISHED' + this.props.uuid !== appReleases[i].uuid && + appReleases[i].currentStatus === 'PUBLISHED' ) { - isPublished = true; - return isPublished; + return true; } } - isPublished = false; - return isPublished; + return false; } return false; }; @@ -278,13 +275,11 @@ class LifeCycle extends React.Component {

{step.text}

{proceedingStates.map(lifecycleState => { return ( - // eslint-disable-next-line react/jsx-key this.showReasonModal(lifecycleState) } From 01e5e301738a3bf53f780bad8774f6b2bf8512df Mon Sep 17 00:00:00 2001 From: Farheen99 Date: Thu, 12 Nov 2020 10:01:58 +0530 Subject: [PATCH 09/17] Remove added setState method in componentDidMount --- .../Apps/scenes/Release/components/LifeCycle/index.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/components/LifeCycle/index.js b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/components/LifeCycle/index.js index 5660802b5ac..03c7801ac36 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/components/LifeCycle/index.js +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/Apps/scenes/Release/components/LifeCycle/index.js @@ -87,15 +87,13 @@ class LifeCycle extends React.Component { const lifecycleSteps = Object.keys(lifeCycleConfig).map(config => { return lifeCycleConfig[config]; }); + let isPublished = this.checkReleaseLifeCycleStatus(); this.setState({ current: lifeCycleConfig[this.props.currentStatus].step, lifecycleSteps, + isPublished, }); this.getLifeCycleHistory(); - - this.setState({ - isPublished: this.checkReleaseLifeCycleStatus(), - }); } componentDidUpdate(prevProps, prevState, snapshot) { From 6b228ee73e1132b8c0f063396856d360d3dc90ca Mon Sep 17 00:00:00 2001 From: "tcdlpds@gmail.com" Date: Fri, 13 Nov 2020 01:30:21 +0530 Subject: [PATCH 10/17] Fix monitoring re-applying issue when policy revoking --- .../core/mgt/impl/MonitoringManagerImpl.java | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java index 65394c71383..29878e05c01 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java @@ -267,14 +267,20 @@ public class MonitoringManagerImpl implements MonitoringManager { int enrollmentId; for (Device device : devices) { enrollmentId = device.getEnrolmentInfo().getId(); - if (persistedComplianceData.containsKey(enrollmentId)) { - notifiableDeviceEnrollments.put(enrollmentId, device); - } else if (appliedPolicyIds.containsKey(enrollmentId)){ - PolicyDeviceWrapper policyDeviceWrapper = new PolicyDeviceWrapper(); - policyDeviceWrapper.setDeviceId(device.getId()); - policyDeviceWrapper.setEnrolmentId(device.getEnrolmentInfo().getId()); - policyDeviceWrapper.setPolicyId(appliedPolicyIds.get(enrollmentId)); - firstTimeComplianceData.add(policyDeviceWrapper); + /* + When a policy has applied to the device, and the first monitoring operation runs on the policy, then it + is considered as a compliance policy and adds monitoring operation on the applied policy. + If the device has identified the applied policy as either compliance or non-compliance policy then + adds monitoring operation on the applied policy. + .*/ + if (appliedPolicyIds.containsKey(enrollmentId)) { + if (!persistedComplianceData.containsKey(enrollmentId)) { + PolicyDeviceWrapper policyDeviceWrapper = new PolicyDeviceWrapper(); + policyDeviceWrapper.setDeviceId(device.getId()); + policyDeviceWrapper.setEnrolmentId(device.getEnrolmentInfo().getId()); + policyDeviceWrapper.setPolicyId(appliedPolicyIds.get(enrollmentId)); + firstTimeComplianceData.add(policyDeviceWrapper); + } notifiableDeviceEnrollments.put(enrollmentId, device); } } From f347861000f3aa3b26c2ad689e5a2cf7c88f4de2 Mon Sep 17 00:00:00 2001 From: Malsha Piumini Date: Sat, 14 Nov 2020 17:25:36 +0000 Subject: [PATCH 11/17] Add functionality to filter Operation Logs --- .../service/api/DeviceManagementService.java | 34 +++- .../impl/DeviceManagementServiceImpl.java | 60 +++++-- .../impl/util/RequestValidationUtil.java | 164 ++++++++++++++++- .../impl/DeviceManagementServiceImplTest.java | 8 +- .../mgt/common/OperationLogFilters.java | 72 ++++++++ .../device/mgt/common/PaginationRequest.java | 9 +- .../mgt/dao/impl/GenericOperationDAOImpl.java | 161 +++++++++++++---- .../operation/OracleOperationDAOImpl.java | 158 +++++++++++++---- .../operation/PostgreSQLOperationDAOImpl.java | 157 ++++++++++++++--- .../operation/SQLServerOperationDAOImpl.java | 165 ++++++++++++++---- 10 files changed, 840 insertions(+), 148 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/OperationLogFilters.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index 60799bf5a27..0ab9dbfeac1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -1493,8 +1493,38 @@ public interface DeviceManagementService { @ApiParam( name = "ownership", value = "Provides the ownership of the required device.") - @QueryParam("owner") - String ownership); + @QueryParam("ownership") + String ownership, + @ApiParam( + name = "createdFrom", + value = "Since when user wants to filter operation logs using the created data and time") + @QueryParam("createdFrom") + Long createdFrom, + @ApiParam( + name = "createdTo", + value = "Till when user wants to filter operation logs using the created data and time") + @QueryParam("createdTo") + Long createdTo, + @ApiParam( + name = "updatedFrom", + value = "Since when user wants to filter operation logs using the received date and time") + @QueryParam("updatedFrom") + Long updatedFrom, + @ApiParam( + name = "updatedTo", + value = "Till when user wants to filter operation logs using the received date and time") + @QueryParam("updatedTo") + Long updatedTo, + @ApiParam( + name = "operationCode", + value = "Provides the operation codes to filter the operation logs via operation codes") + @QueryParam("operationCode") + List operationCode, + @ApiParam( + name = "operationStatus", + value = "Provides the status codes to filter operation logs via status") + @QueryParam("operationStatus") + List status); @GET @Produces(MediaType.APPLICATION_JSON) 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 73a07b7aadb..742fd7ed5d9 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 @@ -36,8 +36,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl; -import java.util.LinkedList; -import java.util.Queue; +import java.text.DateFormat; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.lang.StringUtils; @@ -45,16 +44,17 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceFilters; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.FeatureManager; import org.wso2.carbon.device.mgt.common.MonitoringOperation; +import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; -import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.OperationLogFilters; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.DeviceFilters; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; @@ -81,6 +81,7 @@ import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.device.mgt.common.search.PropertyMap; import org.wso2.carbon.device.mgt.common.search.SearchContext; + import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; @@ -92,14 +93,16 @@ import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; + import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceCompliance; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList; import org.wso2.carbon.device.mgt.jaxrs.beans.OperationRequest; +import org.wso2.carbon.device.mgt.jaxrs.beans.ComplianceDeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationList; import org.wso2.carbon.device.mgt.jaxrs.beans.OperationStatusBean; -import org.wso2.carbon.device.mgt.jaxrs.beans.ComplianceDeviceList; + import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; @@ -128,9 +131,13 @@ import javax.ws.rs.DefaultValue; import javax.ws.rs.core.Response; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; + import java.util.Date; import java.util.List; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Calendar; @Path("/devices") public class DeviceManagementServiceImpl implements DeviceManagementService { @@ -871,21 +878,30 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @QueryParam("offset") int offset, @QueryParam("limit") int limit, @QueryParam("owner") String owner, - @QueryParam("ownership") String ownership) { + @QueryParam("ownership") String ownership, + @QueryParam("createdFrom") Long createdFrom, + @QueryParam("createdTo") Long createdTo, + @QueryParam("updatedFrom") Long updatedFrom, + @QueryParam("updatedTo") Long updatedTo, + @QueryParam("operationCode") List operationCode, + @QueryParam("operationStatus") List status) { OperationList operationsList = new OperationList(); + RequestValidationUtil requestValidationUtil = new RequestValidationUtil(); RequestValidationUtil.validateOwnerParameter(owner); RequestValidationUtil.validatePaginationParameters(offset, limit); PaginationRequest request = new PaginationRequest(offset, limit); request.setOwner(owner); - PaginationResult result; - DeviceManagementProviderService dms; try { + //validating the operation log filters + OperationLogFilters olf = requestValidationUtil.validateOperationLogFilters(operationCode, createdFrom, + createdTo, updatedFrom, updatedTo, status, type); + request.setOperationLogFilters(olf); RequestValidationUtil.validateDeviceIdentifier(type, id); - dms = DeviceMgtAPIUtils.getDeviceManagementService(); + DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); if (!StringUtils.isBlank(ownership)) { request.setOwnership(ownership); } - result = dms.getOperations(new DeviceIdentifier(id, type), request); + PaginationResult result = dms.getOperations(new DeviceIdentifier(id, type), request); operationsList.setList((List) result.getData()); operationsList.setCount(result.getRecordsTotal()); return Response.status(Response.Status.OK).entity(operationsList).build(); @@ -895,6 +911,20 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (InputValidationException e) { + String msg = "Error occurred while fetching the operations for the '" + type + "' device, which " + + "carries the id '" + id + "'"; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while retrieving the list of [" + type + "] features with params " + + "{featureType: operation, hidden: true}"; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (DeviceTypeNotFoundException e) { + String msg = "No device type found with name '" + type + "'"; + log.error(msg, e); + return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java index a0259da67eb..7323b535126 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java @@ -23,11 +23,16 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpStatus; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.Feature; +import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.common.OperationLogFilters; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceTypeNotFoundException; import org.wso2.carbon.device.mgt.common.metadata.mgt.Metadata; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; @@ -35,20 +40,24 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ProfileFeature; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleInfo; import org.wso2.carbon.device.mgt.jaxrs.beans.Scope; +import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceTypeManagementService; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.policy.mgt.common.PolicyPayloadValidator; +import javax.ws.rs.core.Response; +import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.List; import java.util.ArrayList; +import java.util.Calendar; import java.util.Arrays; -import java.util.Collections; -import java.util.List; public class RequestValidationUtil { private static final Log log = LogFactory.getLog(RequestValidationUtil.class); - /** * Checks if multiple criteria are specified in a conditional request. * @@ -476,6 +485,155 @@ public class RequestValidationUtil { } } + /** + * Checks if operation log filters are valid + * + * @param type Device type upon which the selection is done + * @param createdFrom Since when created date and time upon to filter operation logs + * @param createdTo Till when created date and time upon to filter operation logs + * @param updatedFrom Since when received date and time upon to filter operation logs + * @param updatedTo Till when received date and time upon to filter operation logs + * @param status List of operation status codes upon to filter operation logs + */ + public OperationLogFilters validateOperationLogFilters(List operationCode, + Long createdFrom, Long createdTo, Long updatedFrom, + Long updatedTo, List status, String type) + throws DeviceTypeNotFoundException, DeviceManagementException { + OperationLogFilters operationLogFilters = new OperationLogFilters(); + Calendar date = Calendar.getInstance(); + long timeMilli = date.getTimeInMillis(); + + if (updatedFrom != null || updatedTo != null) { + validateDates(updatedFrom, updatedTo); + //if user only sends the fromDate toDate sets as current date + if (updatedFrom != null && updatedTo == null) { + timeMilli = timeMilli / 1000; + operationLogFilters.setUpdatedDayTo(timeMilli); + operationLogFilters.setUpdatedDayFrom(updatedFrom); + } else { + operationLogFilters.setUpdatedDayFrom(updatedFrom); + operationLogFilters.setUpdatedDayTo(updatedTo); + } + } + if (createdTo != null || createdFrom != null) { + validateDates(createdFrom, createdTo); + createdFrom = createdFrom * 1000; + //if user only sends the fromDate toDate sets as current date + if (createdFrom != null && createdTo == null) { + operationLogFilters.setCreatedDayFrom(createdFrom); + operationLogFilters.setCreatedDayTo(timeMilli); + } else { + createdTo = createdTo * 1000; + operationLogFilters.setCreatedDayFrom(createdFrom); + operationLogFilters.setCreatedDayTo(createdTo); + } + } + if (status != null && !status.isEmpty()) { + validateStatusFiltering(status); + operationLogFilters.setStatus(status); + } + + if (operationCode != null && !operationCode.isEmpty()) { + validateOperationCodeFiltering(operationCode, type); + operationLogFilters.setOperationCode(operationCode); + } + return operationLogFilters; + } + + /** + * Checks if date ranges requested by user are valid + * + * @param toDate Till when created/updated dates upon to validate dates + * @param fromDate Since when created/updated dates upon to validate dates + */ + public static void validateDates(Long fromDate, Long toDate) { + Calendar date = Calendar.getInstance(); + long timeMilli = date.getTimeInMillis(); + timeMilli = timeMilli / 1000; + //if user only sends toDate + if (fromDate == null && toDate != null) { + String msg = "Request parameter must sent with the from date parameter"; + log.error(msg); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder() + .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build()); + } + //if user sends future dates + if (fromDate != null && toDate != null) { + if (timeMilli < fromDate || timeMilli < toDate) { + String msg = "Bad Request cannot apply future dates"; + log.error(msg); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder() + .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build()); + } + } + //if user send future dates - only when from date sends + if (fromDate != null && toDate == null) { + if (fromDate > timeMilli) { + String msg = "Bad Request cannot apply future dates"; + log.error(msg); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder() + .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build()); + } + } + } + + /** + * Checks if user requested operation status codes are valid. + * + * @param status status codes upon to filter operation logs using status + */ + public static void validateStatusFiltering(List status) { + for (int i = 0; i < status.size(); i++) { + if (Constants.OperationStatus.COMPLETED.toUpperCase().equals(status.get(i)) + || Constants.OperationStatus.ERROR.toUpperCase().equals(status.get(i)) + || Constants.OperationStatus.NOTNOW.toUpperCase().equals(status.get(i)) + || Constants.OperationStatus.REPEATED.toUpperCase().equals(status.get(i)) + || Constants.OperationStatus.PENDING.toUpperCase().equals(status.get(i)) + || Constants.OperationStatus.IN_PROGRESS.toUpperCase().equals(status.get(i))) { + } else { + String msg = "Invalid status type: " + status + ". \nValid status types are COMPLETED | ERROR | " + + "IN_PROGRESS | NOTNOW | PENDING | REPEATED"; + log.error(msg); + throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder() + .setCode(HttpStatus.SC_BAD_REQUEST) + .setMessage(msg).build()); + } + } + } + + /** + * Checks if user requested operation codes are valid. + * + * @param operationCode operation codes upon to filter operation logs using operation codes + * @param type status codes upon to filter operation logs using status + */ + public static void validateOperationCodeFiltering(List operationCode, String type) + throws DeviceTypeNotFoundException, DeviceManagementException { + int count = 0; + List features; + DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); + FeatureManager fm = dms.getFeatureManager(type); + features = fm.getFeatures("operation"); + for (String oc : operationCode) { + for (Feature f : features) { + if (f.getCode().equals(oc)) { + count++; + break; + } + } + } + if (!(count == operationCode.size())) { + String msg = "Requested Operation code invalid"; + log.error(msg); + throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder() + .setCode(HttpStatus.SC_BAD_REQUEST) + .setMessage(msg).build()); + } + } + /** * Validate if the metaData and metaKey values are non empty & in proper format. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java index d6adc35fc23..bb9de05c1fd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java @@ -648,24 +648,28 @@ public class DeviceManagementServiceImplTest { @Test(description = "Testing getting operation list of a device") public void testGetDeviceOperations() { + List operationCodes = new ArrayList<>(); + List statusCodes = new ArrayList<>(); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); Response response = this.deviceManagementService .getDeviceOperations(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5, DEFAULT_USERNAME, - DEFAULT_OWNERSHIP); + DEFAULT_OWNERSHIP, null, null, null, null, operationCodes, statusCodes); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Expects to return HTTP 200 when the operation is retrieved successfully."); } @Test(description = "Testing getting operation list of a device when unable to retrieve operations") public void testGetDeviceOperationsException() throws OperationManagementException { + List operationCodes = new ArrayList<>(); + List statusCodes = new ArrayList<>(); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); Mockito.when(this.deviceManagementProviderService.getOperations(Mockito.any(DeviceIdentifier.class), Mockito.any(PaginationRequest.class))).thenThrow(new OperationManagementException()); Response response = this.deviceManagementService .getDeviceOperations(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5, DEFAULT_USERNAME, - DEFAULT_OWNERSHIP); + DEFAULT_OWNERSHIP, null, null, null, null, operationCodes, statusCodes); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "Expects to return HTTP 500 when an exception occurred while retrieving operation list of the device"); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/OperationLogFilters.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/OperationLogFilters.java new file mode 100644 index 00000000000..8796c62e0f6 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/OperationLogFilters.java @@ -0,0 +1,72 @@ +/* + * 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.mgt.common; + +import java.util.List; + +/** + * This class carries information related to operation log filtering values which will be used in the UI to filter operations. + */ +public class OperationLogFilters { + private List operationCode; + private Long createdDayFrom; + private Long createdDayTo ; + private Long updatedDayFrom; + private Long updatedDayTo ; + private List status; + public OperationLogFilters() { + } + public OperationLogFilters(List operationCode , Long createdDayFrom, Long createdDayTo, + Long updatedDayFrom, Long updatedDayTo, List status) { + this.operationCode = operationCode; + this.createdDayFrom = createdDayFrom; + this.createdDayTo = createdDayTo; + this.updatedDayFrom = updatedDayFrom; + this.updatedDayTo = updatedDayTo; + this.status = status; + } + public List getOperationCode() { + return operationCode; + } + public void setOperationCode(List operationCode) { + this.operationCode = operationCode; + } + public List getStatus() { + return status; + } + public void setStatus(List status) { + this.status = status; + } + public Long getUpdatedDayFrom() { + return updatedDayFrom; + } + public void setUpdatedDayFrom(Long updatedDayFrom) { + this.updatedDayFrom = updatedDayFrom; + } + public Long getUpdatedDayTo() { + return updatedDayTo; + } + public void setUpdatedDayTo(Long updatedDayTo) { + this.updatedDayTo = updatedDayTo; + } + public Long getCreatedDayFrom() { return createdDayFrom; } + public void setCreatedDayFrom(Long createdDayFrom) { this.createdDayFrom = createdDayFrom; } + public Long getCreatedDayTo() { return createdDayTo; } + public void setCreatedDayTo(Long createdDayTo) { this.createdDayTo = createdDayTo; } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java index 56cecfe008a..94cf5c52729 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java @@ -42,12 +42,17 @@ public class PaginationRequest { private String filter; private Map property = new HashMap<>(); private List statusList = new ArrayList<>(); - + private OperationLogFilters operationLogFilters = new OperationLogFilters(); + public OperationLogFilters getOperationLogFilters() { + return operationLogFilters; + } + public void setOperationLogFilters(OperationLogFilters operationLogFilters) { + this.operationLogFilters = operationLogFilters; + } public PaginationRequest(int start, int rowCount) { this.startIndex = start; this.rowCount = rowCount; } - public int getStartIndex() { return startIndex; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index 7094afdcd36..373b0d3a9b9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -44,12 +44,14 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.LinkedList; +import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.HashMap; +import java.util.Date; /** * This class holds the generic implementation of OperationDAO which can be used to support ANSI db syntax. @@ -1327,44 +1329,139 @@ public class GenericOperationDAOImpl implements OperationDAO { @Override public List getOperationsForDevice(int enrolmentId, PaginationRequest request) throws OperationManagementDAOException { - PreparedStatement stmt = null; - ResultSet rs = null; Operation operation; List operations = new ArrayList(); + String createdTo = null; + String createdFrom = null; + DateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); + boolean isCreatedDayProvided = false; + boolean isUpdatedDayProvided = false; //updated day = received day + boolean isOperationCodeProvided = false; + boolean isStatusProvided = false; + if (request.getOperationLogFilters().getCreatedDayFrom() != null) { + createdFrom = simple.format(request.getOperationLogFilters().getCreatedDayFrom()); + } + if (request.getOperationLogFilters().getCreatedDayTo() != null) { + createdTo = simple.format(request.getOperationLogFilters().getCreatedDayTo()); + } + Long updatedFrom = request.getOperationLogFilters().getUpdatedDayFrom(); + Long updatedTo = request.getOperationLogFilters().getUpdatedDayTo(); + List operationCode = request.getOperationLogFilters().getOperationCode(); + List status = request.getOperationLogFilters().getStatus(); + String sql = "SELECT " + + "o.ID, " + + "TYPE, " + + "o.CREATED_TIMESTAMP, " + + "o.RECEIVED_TIMESTAMP, " + + "o.OPERATION_CODE, " + + "om.STATUS, " + + "om.ID AS OM_MAPPING_ID, " + + "om.UPDATED_TIMESTAMP " + + "FROM " + + "DM_OPERATION o " + + "INNER JOIN " + + "(SELECT dm.OPERATION_ID, " + + "dm.ID, " + + "dm.STATUS, " + + "dm.UPDATED_TIMESTAMP " + + "FROM " + + "DM_ENROLMENT_OP_MAPPING dm " + + "WHERE " + + "dm.ENROLMENT_ID = ?"; + + if (updatedFrom != null && updatedFrom != 0 && updatedTo != null && updatedTo != 0) { + sql = sql + " AND dm.UPDATED_TIMESTAMP BETWEEN ? AND ?"; + isUpdatedDayProvided = true; + } + sql = sql + ") om ON o.ID = om.OPERATION_ID "; + if (createdFrom != null && !createdFrom.isEmpty() && createdTo != null && !createdTo.isEmpty()) { + sql = sql + " WHERE o.CREATED_TIMESTAMP BETWEEN ? AND ?"; + isCreatedDayProvided = true; + } + if ((isCreatedDayProvided) && (status != null && !status.isEmpty())) { + int size = status.size(); + sql = sql + " AND (om.STATUS = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR om.STATUS = ?"; + } + sql = sql + ")"; + isStatusProvided = true; + } else if ((!isCreatedDayProvided) && (status != null && !status.isEmpty())) { + int size = status.size(); + sql = sql + " WHERE (om.STATUS = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR om.STATUS = ?"; + } + sql = sql + ")"; + isStatusProvided = true; + } + if ((isCreatedDayProvided || isStatusProvided) && (operationCode != null && !operationCode.isEmpty())) { + int size = operationCode.size(); + sql = sql + " AND (o.OPERATION_CODE = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR o.OPERATION_CODE = ?"; + } + sql = sql + ")"; + isOperationCodeProvided = true; + } else if ((!isCreatedDayProvided && !isStatusProvided) && (operationCode != null && !operationCode.isEmpty())) { + int size = operationCode.size(); + sql = sql + " WHERE (o.OPERATION_CODE = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR o.OPERATION_CODE = ?"; + } + sql = sql + ")"; + isOperationCodeProvided = true; + } + sql = sql + " ORDER BY o.CREATED_TIMESTAMP DESC LIMIT ?,?"; try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + - "o.OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + - "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + - "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID " + - "ORDER BY o.CREATED_TIMESTAMP DESC, o.ID DESC LIMIT ?,?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, enrolmentId); - stmt.setInt(2, request.getStartIndex()); - stmt.setInt(3, request.getRowCount()); - rs = stmt.executeQuery(); - - while (rs.next()) { - operation = new Operation(); - operation.setId(rs.getInt("ID")); - operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); - operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); - if (rs.getLong("UPDATED_TIMESTAMP") == 0) { - operation.setReceivedTimeStamp(""); - } else { - operation.setReceivedTimeStamp( - new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString()); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIndex = 1; + stmt.setInt(paramIndex++, enrolmentId); + if (isUpdatedDayProvided) { + stmt.setLong(paramIndex++, updatedFrom); + stmt.setLong(paramIndex++, updatedTo); + } + if (isCreatedDayProvided) { + stmt.setString(paramIndex++, createdFrom); + stmt.setString(paramIndex++, createdTo); + } + if (isStatusProvided) { + int size = status.size(); + for (int i = 0; i < size; i++) { + stmt.setString(paramIndex++, status.get(i)); + } + } + if (isOperationCodeProvided) { + int size = operationCode.size(); + for (int i = 0; i < size; i++) { + stmt.setString(paramIndex++, operationCode.get(i)); + } + } + stmt.setInt(paramIndex++, request.getStartIndex()); + stmt.setInt(paramIndex, request.getRowCount()); + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); + if (rs.getLong("UPDATED_TIMESTAMP") == 0) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp( + new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); + OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); + operations.add(operation); + } } - operation.setCode(rs.getString("OPERATION_CODE")); - operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); - OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); - operations.add(operation); } } catch (SQLException e) { throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + "available for the device'" + enrolmentId + "' with status '", e); - } finally { - OperationManagementDAOUtil.cleanupResources(stmt, rs); } return operations; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java index 37de111d8a9..e84b723262d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java @@ -37,11 +37,13 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.HashMap; -import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.ArrayList; +import java.util.LinkedList; /** * This class holds the implementation of OperationDAO which can be used to support Oracle db syntax. @@ -53,44 +55,140 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { @Override public List getOperationsForDevice(int enrolmentId, PaginationRequest request) throws OperationManagementDAOException { - PreparedStatement stmt = null; - ResultSet rs = null; Operation operation; List operations = new ArrayList(); + String createdTo = null; + String createdFrom = null; + DateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); + boolean isCreatedDayProvided = false; + boolean isUpdatedDayProvided = false; //updated day = received day + boolean isOperationCodeProvided = false; + boolean isStatusProvided = false; + if (request.getOperationLogFilters().getCreatedDayFrom() != null) { + createdFrom = simple.format(request.getOperationLogFilters().getCreatedDayFrom()); + } + if (request.getOperationLogFilters().getCreatedDayTo() != null) { + createdTo = simple.format(request.getOperationLogFilters().getCreatedDayTo()); + } + Long updatedFrom = request.getOperationLogFilters().getUpdatedDayFrom(); + Long updatedTo = request.getOperationLogFilters().getUpdatedDayTo(); + List operationCode = request.getOperationLogFilters().getOperationCode(); + List status = request.getOperationLogFilters().getStatus(); + String sql = "SELECT " + + "o.ID, " + + "TYPE, " + + "o.CREATED_TIMESTAMP, " + + "o.RECEIVED_TIMESTAMP, " + + "o.OPERATION_CODE, " + + "om.STATUS, " + + "om.ID AS OM_MAPPING_ID, " + + "om.UPDATED_TIMESTAMP " + + "FROM " + + "DM_OPERATION o " + + "INNER JOIN " + + "(SELECT " + + "dm.OPERATION_ID, " + + "dm.ID, " + + "dm.STATUS, " + + "dm.UPDATED_TIMESTAMP " + + "FROM " + + "DM_ENROLMENT_OP_MAPPING dm " + + "WHERE " + + "dm.ENROLMENT_ID = ?"; + + if (updatedFrom != null && updatedFrom != 0 && updatedTo != null && updatedTo != 0) { + sql = sql + " AND dm.UPDATED_TIMESTAMP BETWEEN ? AND ?"; + isUpdatedDayProvided = true; + } + sql = sql + ") om ON o.ID = om.OPERATION_ID "; + if (createdFrom != null && !createdFrom.isEmpty() && createdTo != null && !createdTo.isEmpty()) { + sql = sql + " WHERE o.CREATED_TIMESTAMP BETWEEN ? AND ?"; + isCreatedDayProvided = true; + } + if ((isCreatedDayProvided) && (status != null && !status.isEmpty())) { + int size = status.size(); + sql = sql + " AND (om.STATUS = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR om.STATUS = ?"; + } + sql = sql + ")"; + isStatusProvided = true; + } else if ((!isCreatedDayProvided) && (status != null && !status.isEmpty())) { + int size = status.size(); + sql = sql + " WHERE (om.STATUS = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR om.STATUS = ?"; + } + sql = sql + ")"; + isStatusProvided = true; + } + if ((isCreatedDayProvided || isStatusProvided) && (operationCode != null && !operationCode.isEmpty())) { + int size = operationCode.size(); + sql = sql + " AND (o.OPERATION_CODE = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR o.OPERATION_CODE = ?"; + } + sql = sql + ")"; + isOperationCodeProvided = true; + } else if ((!isCreatedDayProvided && !isStatusProvided) && (operationCode != null && !operationCode.isEmpty())) { + int size = operationCode.size(); + sql = sql + " WHERE (o.OPERATION_CODE = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR o.OPERATION_CODE = ?"; + } + sql = sql + ")"; + isOperationCodeProvided = true; + } + sql = sql + " ORDER BY o.CREATED_TIMESTAMP DESC FFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + int paramIndex = 1; try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " - + "o.OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " - + "INNER JOIN (SELECT dm.OPERATION_ID, dm.ID, dm.STATUS, dm.UPDATED_TIMESTAMP FROM DM_ENROLMENT_OP_MAPPING dm " - + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC " - + "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, enrolmentId); - stmt.setInt(2, request.getStartIndex()); - stmt.setInt(3, request.getRowCount()); - rs = stmt.executeQuery(); - - while (rs.next()) { - operation = new Operation(); - operation.setId(rs.getInt("ID")); - operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); - operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); - if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { - operation.setReceivedTimeStamp(""); - } else { - operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(paramIndex++, enrolmentId); + if (isUpdatedDayProvided) { + stmt.setLong(paramIndex++, updatedFrom); + stmt.setLong(paramIndex++, updatedTo); + } + if (isCreatedDayProvided) { + stmt.setString(paramIndex++, createdFrom); + stmt.setString(paramIndex++, createdTo); + } + if (isStatusProvided) { + int size = status.size(); + for (int i = 0; i < size; i++) { + stmt.setString(paramIndex++, status.get(i)); + } + } + if (isOperationCodeProvided) { + int size = operationCode.size(); + for (int i = 0; i < size; i++) { + stmt.setString(paramIndex++, operationCode.get(i)); + } + } + stmt.setInt(paramIndex++, request.getStartIndex()); + stmt.setInt(paramIndex, request.getRowCount()); + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); + if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); + OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); + operations.add(operation); + } } - operation.setCode(rs.getString("OPERATION_CODE")); - operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); - OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); - operations.add(operation); } } catch (SQLException e) { throw new OperationManagementDAOException( "SQL error occurred while retrieving the operation " + "available for the device'" + enrolmentId + "' with status '", e); - } finally { - OperationManagementDAOUtil.cleanupResources(stmt, rs); } return operations; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java index 17ccdb27ce7..cbf6c074208 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java @@ -32,9 +32,11 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; -import java.util.ArrayList; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; +import java.util.ArrayList; /** * This class holds the implementation of OperationDAO which can be used to support PostgreSQL db syntax. @@ -44,42 +46,139 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { @Override public List getOperationsForDevice(int enrolmentId, PaginationRequest request) throws OperationManagementDAOException { - PreparedStatement stmt = null; - ResultSet rs = null; Operation operation; List operations = new ArrayList(); + String createdTo = null; + String createdFrom = null; + DateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); + boolean isCreatedDayProvided = false; + boolean isUpdatedDayProvided = false; //updated day = received day + boolean isOperationCodeProvided = false; + boolean isStatusProvided = false; + if (request.getOperationLogFilters().getCreatedDayFrom() != null) { + createdFrom = simple.format(request.getOperationLogFilters().getCreatedDayFrom()); + } + if (request.getOperationLogFilters().getCreatedDayTo() != null) { + createdTo = simple.format(request.getOperationLogFilters().getCreatedDayTo()); + } + Long updatedFrom = request.getOperationLogFilters().getUpdatedDayFrom(); + Long updatedTo = request.getOperationLogFilters().getUpdatedDayTo(); + List operationCode = request.getOperationLogFilters().getOperationCode(); + List status = request.getOperationLogFilters().getStatus(); + String sql = "SELECT " + + "o.ID, " + + "TYPE, " + + "o.CREATED_TIMESTAMP, " + + "o.RECEIVED_TIMESTAMP, " + + "o.OPERATION_CODE, " + + "om.STATUS, " + + "om.ID AS OM_MAPPING_ID, " + + "om.UPDATED_TIMESTAMP " + + "FROM " + + "DM_OPERATION o " + + "INNER JOIN " + + "(SELECT " + + "dm.OPERATION_ID, " + + "dm.ID, " + + "dm.STATUS, " + + "dm.UPDATED_TIMESTAMP " + + "FROM " + + "DM_ENROLMENT_OP_MAPPING dm " + + "WHERE " + + "dm.ENROLMENT_ID = ?"; + + if (updatedFrom != null && updatedFrom != 0 && updatedTo != null && updatedTo != 0) { + sql = sql + " AND dm.UPDATED_TIMESTAMP BETWEEN ? AND ?"; + isUpdatedDayProvided = true; + } + sql = sql + ") om ON o.ID = om.OPERATION_ID "; + if (createdFrom != null && !createdFrom.isEmpty() && createdTo != null && !createdTo.isEmpty()) { + sql = sql + " WHERE o.CREATED_TIMESTAMP BETWEEN ? AND ?"; + isCreatedDayProvided = true; + } + if ((isCreatedDayProvided) && (status != null && !status.isEmpty())) { + int size = status.size(); + sql = sql + " AND (om.STATUS = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR om.STATUS = ?"; + } + sql = sql + ")"; + isStatusProvided = true; + } else if ((!isCreatedDayProvided) && (status != null && !status.isEmpty())) { + int size = status.size(); + sql = sql + " WHERE (om.STATUS = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR om.STATUS = ?"; + } + sql = sql + ")"; + isStatusProvided = true; + } + if ((isCreatedDayProvided || isStatusProvided) && (operationCode != null && !operationCode.isEmpty())) { + int size = operationCode.size(); + sql = sql + " AND (o.OPERATION_CODE = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR o.OPERATION_CODE = ?"; + } + sql = sql + ")"; + isOperationCodeProvided = true; + } else if ((!isCreatedDayProvided && !isStatusProvided) && (operationCode != null && !operationCode.isEmpty())) { + int size = operationCode.size(); + sql = sql + " WHERE (o.OPERATION_CODE = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR o.OPERATION_CODE = ?"; + } + sql = sql + ")"; + isOperationCodeProvided = true; + } + sql = sql + " ORDER BY o.CREATED_TIMESTAMP DESC LIMIT ? OFFSET ?"; + int paramIndex = 1; try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + - "o.OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + - "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + - "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC LIMIT ? OFFSET ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, enrolmentId); - stmt.setInt(2, request.getRowCount()); - stmt.setInt(3, request.getStartIndex()); - rs = stmt.executeQuery(); - - while (rs.next()) { - operation = new Operation(); - operation.setId(rs.getInt("ID")); - operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); - operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); - if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { - operation.setReceivedTimeStamp(""); - } else { - operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(paramIndex++, enrolmentId); + if (isUpdatedDayProvided) { + stmt.setLong(paramIndex++, updatedFrom); + stmt.setLong(paramIndex++, updatedTo); + } + if (isCreatedDayProvided) { + stmt.setString(paramIndex++, createdFrom); + stmt.setString(paramIndex++, createdTo); + } + if (isStatusProvided) { + int size = status.size(); + for (int i = 0; i < size; i++) { + stmt.setString(paramIndex++, status.get(i)); + } + } + if (isOperationCodeProvided) { + int size = operationCode.size(); + for (int i = 0; i < size; i++) { + stmt.setString(paramIndex++, operationCode.get(i)); + } + } + stmt.setInt(paramIndex++, request.getStartIndex()); + stmt.setInt(paramIndex, request.getRowCount()); + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); + if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); + OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); + operations.add(operation); + } } - operation.setCode(rs.getString("OPERATION_CODE")); - operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); - OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); - operations.add(operation); } } catch (SQLException e) { throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + - "available for the device'" + enrolmentId, e); - } finally { - OperationManagementDAOUtil.cleanupResources(stmt, rs); + "available for the device'" + enrolmentId, e); } return operations; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java index a3520084f6b..164df0b452b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java @@ -56,12 +56,13 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.HashMap; -import java.util.LinkedList; import java.util.List; import java.util.Map; - +import java.util.ArrayList; +import java.util.LinkedList; /** * This class holds the implementation of OperationDAO which can be used to support SQLServer db syntax. */ @@ -72,44 +73,142 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { @Override public List getOperationsForDevice(int enrolmentId, PaginationRequest request) throws OperationManagementDAOException { - PreparedStatement stmt = null; - ResultSet rs = null; Operation operation; List operations = new ArrayList(); + String createdTo = null; + String createdFrom = null; + DateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); + boolean isCreatedDayProvided = false; + boolean isUpdatedDayProvided = false; //updated day = received day + boolean isOperationCodeProvided = false; + boolean isStatusProvided = false; + if (request.getOperationLogFilters().getCreatedDayFrom() != null) { + createdFrom = simple.format(request.getOperationLogFilters().getCreatedDayFrom()); + } + if (request.getOperationLogFilters().getCreatedDayTo() != null) { + createdTo = simple.format(request.getOperationLogFilters().getCreatedDayTo()); + } + Long updatedFrom = request.getOperationLogFilters().getUpdatedDayFrom(); + Long updatedTo = request.getOperationLogFilters().getUpdatedDayTo(); + List operationCode = request.getOperationLogFilters().getOperationCode(); + List status = request.getOperationLogFilters().getStatus(); + String sql = "SELECT " + + "o.ID, " + + "TYPE, " + + "o.CREATED_TIMESTAMP, " + + "o.RECEIVED_TIMESTAMP, " + + "o.OPERATION_CODE, " + + "om.STATUS, " + + "om.ID AS OM_MAPPING_ID, " + + "om.UPDATED_TIMESTAMP " + + "FROM " + + "DM_OPERATION o " + + "INNER JOIN " + + "(SELECT " + + "dm.OPERATION_ID, " + + "dm.ID, " + + "dm.STATUS, " + + "dm.UPDATED_TIMESTAMP " + + "FROM " + + "DM_ENROLMENT_OP_MAPPING dm " + + "WHERE " + + "dm.ENROLMENT_ID = ?"; + + if (updatedFrom != null && updatedFrom != 0 && updatedTo != null && updatedTo != 0) { + sql = sql + " AND dm.UPDATED_TIMESTAMP BETWEEN ? AND ?"; + isUpdatedDayProvided = true; + } + sql = sql + ") om ON o.ID = om.OPERATION_ID "; + if (createdFrom != null && !createdFrom.isEmpty() && createdTo != null && !createdTo.isEmpty()) { + sql = sql + " WHERE o.CREATED_TIMESTAMP BETWEEN ? AND ?"; + isCreatedDayProvided = true; + } + if ((isCreatedDayProvided) && (status != null && !status.isEmpty())) { + int size = status.size(); + sql = sql + " AND (om.STATUS = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR om.STATUS = ?"; + } + sql = sql + ")"; + isStatusProvided = true; + } else if ((!isCreatedDayProvided) && (status != null && !status.isEmpty())) { + int size = status.size(); + sql = sql + " WHERE (om.STATUS = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR om.STATUS = ?"; + } + sql = sql + ")"; + isStatusProvided = true; + } + if ((isCreatedDayProvided || isStatusProvided) && (operationCode != null && !operationCode.isEmpty())) { + // sql = sql + " AND o.OPERATION_CODE = ? "; + int size = operationCode.size(); + sql = sql + " AND (o.OPERATION_CODE = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR o.OPERATION_CODE = ?"; + } + sql = sql + ")"; + isOperationCodeProvided = true; + } else if ((!isCreatedDayProvided && !isStatusProvided) && (operationCode != null && !operationCode.isEmpty())) { + //sql = sql + " WHERE o.OPERATION_CODE = ? "; + int size = operationCode.size(); + sql = sql + " WHERE (o.OPERATION_CODE = ? "; + for (int i = 0; i < size - 1; i++) { + sql = sql + " OR o.OPERATION_CODE = ?"; + } + sql = sql + ")"; + isOperationCodeProvided = true; + } + sql = sql + " ORDER BY o.CREATED_TIMESTAMP DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + int paramIndex = 1; try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + - "o.OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + - "INNER JOIN (SELECT dm.OPERATION_ID, dm.ID, dm.STATUS, dm.UPDATED_TIMESTAMP FROM DM_ENROLMENT_OP_MAPPING dm " + - "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC " + - "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, enrolmentId); - stmt.setInt(2, request.getStartIndex()); - stmt.setInt(3, request.getRowCount()); - rs = stmt.executeQuery(); - - while (rs.next()) { - operation = new Operation(); - operation.setId(rs.getInt("ID")); - operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); - operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); - if (rs.getLong("UPDATED_TIMESTAMP") == 0) { - operation.setReceivedTimeStamp(""); - } else { - operation.setReceivedTimeStamp( - new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString()); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(paramIndex++, enrolmentId); + if (isUpdatedDayProvided) { + stmt.setLong(paramIndex++, updatedFrom); + stmt.setLong(paramIndex++, updatedTo); + } + if (isCreatedDayProvided) { + stmt.setString(paramIndex++, createdFrom); + stmt.setString(paramIndex++, createdTo); + } + if (isStatusProvided) { + int size = status.size(); + for (int i = 0; i < size; i++) { + stmt.setString(paramIndex++, status.get(i)); + } + } + if (isOperationCodeProvided) { + int size = operationCode.size(); + for (int i = 0; i < size; i++) { + stmt.setString(paramIndex++, operationCode.get(i)); + } + } + stmt.setInt(paramIndex++, request.getStartIndex()); + stmt.setInt(paramIndex, request.getRowCount()); + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); + if (rs.getLong("UPDATED_TIMESTAMP") == 0) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp( + new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); + OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); + operations.add(operation); + } } - operation.setCode(rs.getString("OPERATION_CODE")); - operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); - OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); - operations.add(operation); } } catch (SQLException e) { throw new OperationManagementDAOException("SQL error occurred while retrieving the operations " + - "available for the device '" + enrolmentId + "'", e); - } finally { - OperationManagementDAOUtil.cleanupResources(stmt, rs); + "available for the device '" + enrolmentId + "'", e); } return operations; } From 9229ce280d8b1c047928c0b34898e3355dc3f5d0 Mon Sep 17 00:00:00 2001 From: Dharmakeerthi Lasantha Date: Tue, 17 Nov 2020 03:58:32 +0000 Subject: [PATCH 12/17] Use device updated timestamp to filter updated devices --- .../core/dao/impl/AbstractDeviceDAOImpl.java | 62 +++++++------------ .../dao/impl/device/GenericDeviceDAOImpl.java | 25 +++----- .../dao/impl/device/OracleDeviceDAOImpl.java | 26 +++----- .../impl/device/PostgreSQLDeviceDAOImpl.java | 13 ++-- .../impl/device/SQLServerDeviceDAOImpl.java | 26 +++----- 5 files changed, 57 insertions(+), 95 deletions(-) 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 465b3529963..a9b443b5567 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 @@ -118,7 +118,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "UPDATE DM_DEVICE SET NAME = ?, DESCRIPTION = ?, LAST_UPDATED_TIMESTAMP = ? " + - "WHERE DEVICE_TYPE_ID = (SELECT ID FROM DM_DEVICE_TYPE WHERE NAME = ? AND (PROVIDER_TENANT_ID = ? OR SHARED_WITH_ALL_TENANTS = ?)) " + + "WHERE DEVICE_TYPE_ID = (SELECT ID FROM DM_DEVICE_TYPE " + + "WHERE NAME = ? AND (PROVIDER_TENANT_ID = ? OR SHARED_WITH_ALL_TENANTS = ?)) " + "AND DEVICE_IDENTIFICATION = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql, new String[]{"id"}); stmt.setString(1, device.getName()); @@ -164,20 +165,14 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { + "d.NAME, " + "t.NAME AS DEVICE_TYPE, " + "d.DEVICE_IDENTIFICATION " - + "FROM DM_DEVICE d, DM_DEVICE_TYPE t"; - - if (deviceData.getLastModifiedDate() != null) { - sql += ", DM_DEVICE_DETAIL dt"; - } - - sql += " WHERE " + + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + "t.NAME = ? AND " + "t.ID = d.DEVICE_TYPE_ID AND " + "d.DEVICE_IDENTIFICATION = ? AND " + "d.TENANT_ID = ?"; if (deviceData.getLastModifiedDate() != null) { - sql += " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; + sql += " AND d.LAST_UPDATED_TIMESTAMP > ?"; } sql += ") d1 WHERE d1.ID = e.DEVICE_ID AND "; @@ -197,7 +192,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { stmt.setString(paramIndx++, deviceData.getDeviceIdentifier().getId()); stmt.setInt(paramIndx++, tenantId); if (deviceData.getLastModifiedDate() != null) { - stmt.setLong(paramIndx++, deviceData.getLastModifiedDate().getTime()); + stmt.setTimestamp(paramIndx++, new Timestamp(deviceData.getLastModifiedDate().getTime())); } if (!StringUtils.isBlank(deviceData.getDeviceOwner())) { stmt.setString(paramIndx++, deviceData.getDeviceOwner()); @@ -354,15 +349,15 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + - "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_DETAIL dt " + - "WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " + - "AND dt.UPDATE_TIMESTAMP > ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC"; + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? " + + "AND d.LAST_UPDATED_TIMESTAMP > ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); int paramIdx = 1; stmt.setString(paramIdx++, deviceIdentifier.getType()); stmt.setString(paramIdx++, deviceIdentifier.getId()); stmt.setInt(paramIdx++, tenantId); - stmt.setLong(paramIdx++, since.getTime()); + stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); stmt.setInt(paramIdx, tenantId); rs = stmt.executeQuery(); if (rs.next()) { @@ -549,11 +544,10 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "(SELECT d.ID, d.DESCRIPTION, d.NAME, " + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION " + "FROM" + - " DM_DEVICE d, DM_DEVICE_TYPE t," + - " DM_DEVICE_DETAIL dt " + + " DM_DEVICE d, DM_DEVICE_TYPE t " + "WHERE " + "t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND" + - " dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?) d1 " + + " d.LAST_UPDATED_TIMESTAMP > ?) d1 " + "WHERE" + " d1.ID = e.DEVICE_ID AND TENANT_ID = ? " + "ORDER BY " + @@ -562,7 +556,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { int paramIdx = 1; stmt.setString(paramIdx++, deviceIdentifier); stmt.setInt(paramIdx++, tenantId); - stmt.setLong(paramIdx++, since.getTime()); + stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); stmt.setInt(paramIdx, tenantId); rs = stmt.executeQuery(); if (rs.next()) { @@ -589,14 +583,15 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + - "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_DETAIL dt " + - "WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " + - "AND dt.UPDATE_TIMESTAMP > ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? AND e.OWNER = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC"; + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? " + + "AND d.LAST_UPDATED_TIMESTAMP > ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? AND e.OWNER = ? " + + "ORDER BY e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceIdentifier.getType()); stmt.setString(2, deviceIdentifier.getId()); stmt.setInt(3, tenantId); - stmt.setLong(4, since.getTime()); + stmt.setTimestamp(4, new Timestamp(since.getTime())); stmt.setInt(5, tenantId); stmt.setString(6, owner); rs = stmt.executeQuery(); @@ -912,16 +907,12 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { sql = sql + " AND d.NAME LIKE ?"; isDeviceNameProvided = true; } - sql = sql + ") gd, DM_DEVICE_TYPE t"; + sql = sql + ") gd, DM_DEVICE_TYPE t WHERE gd.DEVICE_TYPE_ID = t.ID"; + //Add query for last updated timestamp if (since != null) { - sql = sql + ", DM_DEVICE_DETAIL dt"; + sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; isSinceProvided = true; } - sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; - //Add query for last updated timestamp - if (isSinceProvided) { - sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; - } //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; @@ -954,7 +945,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { stmt.setString(paramIdx++, deviceName + "%"); } if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); + stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); } if (isDeviceTypeProvided) { stmt.setString(paramIdx++, deviceType); @@ -1182,17 +1173,12 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "t.NAME AS DEVICE_TYPE " + "FROM " + "DM_DEVICE d, " + - "DM_DEVICE_TYPE t"; + "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; //Add query for last updated timestamp if (since != null) { - sql = sql + " , DM_DEVICE_DETAIL dt"; + sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; isSinceProvided = true; } - sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; - //Add query for last updated timestamp - if (isSinceProvided) { - sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; - } if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; isDeviceTypeProvided = true; @@ -1223,7 +1209,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { int paramIdx = 1; stmt.setInt(paramIdx++, tenantId); if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); + stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); } if (isDeviceTypeProvided) { stmt.setString(paramIdx++, request.getDeviceType()); 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 63df06538d8..ee9c9a774d1 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 @@ -36,6 +36,7 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -88,15 +89,12 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DEVICE_IDENTIFICATION, " + "t.NAME AS DEVICE_TYPE " + "FROM DM_DEVICE d, DM_DEVICE_TYPE t "; - //Add the query to filter active devices on timestamp - if (since != null) { - sql = sql + ", DM_DEVICE_DETAIL dt"; - isSinceProvided = true; - } + sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; //Add query for last updated timestamp - if (isSinceProvided) { - sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; + if (since != null) { + sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; + isSinceProvided = true; } //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { @@ -132,7 +130,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { int paramIdx = 1; stmt.setInt(paramIdx++, tenantId); if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); + stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); } if (isDeviceTypeProvided) { stmt.setString(paramIdx++, deviceType); @@ -232,14 +230,11 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { isDeviceNameProvided = true; } sql = sql + ") gd, DM_DEVICE_TYPE t"; - if (since != null) { - sql = sql + ", DM_DEVICE_DETAIL dt"; - isSinceProvided = true; - } sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; //Add query for last updated timestamp - if (isSinceProvided) { - sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; + if (since != null) { + sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; + isSinceProvided = true; } //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { @@ -274,7 +269,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setString(paramIdx++, deviceName + "%"); } if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); + stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); } if (isDeviceTypeProvided) { stmt.setString(paramIdx++, deviceType); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index 07bd3089ed0..86f8cccfea7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -36,6 +36,7 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -89,17 +90,12 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DEVICE_IDENTIFICATION, " + "t.NAME AS DEVICE_TYPE " + "FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t "; - //Add the query to filter active devices on timestamp + "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + //Add query for last updated timestamp if (since != null) { - sql = sql + ", DM_DEVICE_DETAIL dt"; + sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; isSinceProvided = true; } - sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; - //Add query for last updated timestamp - if (isSinceProvided) { - sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; - } //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; @@ -134,7 +130,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { int paramIdx = 1; stmt.setInt(paramIdx++, tenantId); if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); + stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); } if (isDeviceTypeProvided) { stmt.setString(paramIdx++, deviceType); @@ -235,16 +231,12 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND d.NAME LIKE ?"; isDeviceNameProvided = true; } - sql = sql + ") gd, DM_DEVICE_TYPE t"; + sql = sql + ") gd, DM_DEVICE_TYPE t WHERE gd.DEVICE_TYPE_ID = t.ID"; + //Add query for last updated timestamp if (since != null) { - sql = sql + ", DM_DEVICE_DETAIL dt"; + sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; isSinceProvided = true; } - sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; - //Add query for last updated timestamp - if (isSinceProvided) { - sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; - } //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; @@ -278,7 +270,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setString(paramIdx++, deviceName + "%"); } if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); + stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); } if (isDeviceTypeProvided) { stmt.setString(paramIdx++, deviceType); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index da1c8a26307..b39e1fbab25 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -35,6 +35,7 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -222,16 +223,12 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND d.NAME LIKE ?"; isDeviceNameProvided = true; } - sql = sql + ") gd, DM_DEVICE_TYPE t"; + sql = sql + ") gd, DM_DEVICE_TYPE t WHERE gd.DEVICE_TYPE_ID = t.ID"; + //Add query for last updated timestamp if (since != null) { - sql = sql + ", DM_DEVICE_DETAIL dt"; + sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; isSinceProvided = true; } - sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; - //Add query for last updated timestamp - if (isSinceProvided) { - sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; - } //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; @@ -265,7 +262,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setString(paramIdx++, deviceName + "%"); } if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); + stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); } if (isDeviceTypeProvided) { stmt.setString(paramIdx++, deviceType); 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 1d0d9c246c5..a56f094604a 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 @@ -37,6 +37,7 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -89,17 +90,12 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.NAME, " + "d.DEVICE_IDENTIFICATION, " + "t.NAME AS DEVICE_TYPE " + - "FROM DM_DEVICE d, DM_DEVICE_TYPE t "; - //Add the query to filter active devices on timestamp + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + //Add query for last updated timestamp if (since != null) { - sql = sql + ", DM_DEVICE_DETAIL dt"; + sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; isSinceProvided = true; } - sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; - //Add query for last updated timestamp - if (isSinceProvided) { - sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; - } //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; @@ -134,7 +130,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { int paramIdx = 1; stmt.setInt(paramIdx++, tenantId); if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); + stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); } if (isDeviceTypeProvided) { stmt.setString(paramIdx++, deviceType); @@ -234,16 +230,12 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND d.NAME LIKE ?"; isDeviceNameProvided = true; } - sql = sql + ") gd, DM_DEVICE_TYPE t"; + sql = sql + ") gd, DM_DEVICE_TYPE t WHERE gd.DEVICE_TYPE_ID = t.ID"; + //Add query for last updated timestamp if (since != null) { - sql = sql + ", DM_DEVICE_DETAIL dt"; + sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; isSinceProvided = true; } - sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; - //Add query for last updated timestamp - if (isSinceProvided) { - sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; - } //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; @@ -277,7 +269,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setString(paramIdx++, deviceName + "%"); } if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); + stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); } if (isDeviceTypeProvided) { stmt.setString(paramIdx++, deviceType); From 8238f7dd22c6866778fd68a108086690c67c9898 Mon Sep 17 00:00:00 2001 From: Farheen Boosary Date: Wed, 18 Nov 2020 19:26:15 +0000 Subject: [PATCH 13/17] Add Windows enterprise app installation support for publisher and store --- .../application/mgt/common/DeviceTypes.java | 2 +- .../mgt/common/response/Application.java | 8 + .../common/response/ApplicationRelease.java | 8 + .../common/services/ApplicationManager.java | 10 + .../common/wrapper/EntAppReleaseWrapper.java | 24 ++ .../mgt/core/impl/ApplicationManagerImpl.java | 78 +++- .../core/impl/SubscriptionManagerImpl.java | 13 + .../application/mgt/core/util/APIUtil.java | 6 + .../application/mgt/core/util/Constants.java | 4 + ...ApplicationManagementPublisherAPIImpl.java | 4 + .../react-app/public/conf/config.json | 8 +- .../components/NewAppDetailsForm/index.js | 48 +++ .../components/NewAppUploadForm/index.js | 388 +++++++++++++++--- .../components/AddNewAppForm/index.js | 23 +- .../components/AddNewReleaseForm/index.js | 6 + .../ApssTable/AppDetailsDrawer/index.js | 1 + .../components/EditRelease/index.js | 211 ++++++---- .../Release/components/ReleaseView/index.js | 40 +- .../react-app/public/conf/config.json | 3 + .../components/ReleaseView/index.js | 41 +- .../device/mgt/common/MDMAppConstants.java | 25 +- .../carbon/device/mgt/common/app/mgt/App.java | 8 + .../mgt/windows/EnterpriseApplication.java | 54 +++ .../mgt/windows/HostedAppxApplication.java | 71 ++++ .../app/mgt/windows/HostedMSIApplication.java | 52 +++ .../core/util/MDMWindowsOperationUtil.java | 146 +++++++ 26 files changed, 1118 insertions(+), 164 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/windows/EnterpriseApplication.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/windows/HostedAppxApplication.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/windows/HostedMSIApplication.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/MDMWindowsOperationUtil.java diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/DeviceTypes.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/DeviceTypes.java index 465b67cafdc..7fa8a02062b 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/DeviceTypes.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/DeviceTypes.java @@ -17,5 +17,5 @@ package org.wso2.carbon.device.application.mgt.common; public enum DeviceTypes { - ANDROID, IOS + ANDROID, IOS, WINDOWS } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/response/Application.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/response/Application.java index 778f7fc08d7..0cd8a72783c 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/response/Application.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/response/Application.java @@ -31,6 +31,10 @@ public class Application { required = true) private String name; + @ApiModelProperty(name = "installerName", + value = "Application Installer Name") + private String installerName; + @ApiModelProperty(name = "description", value = "Description of the application", required = true) @@ -173,4 +177,8 @@ public class Application { public boolean isAndroidEnterpriseApp() { return isAndroidEnterpriseApp; } public void setAndroidEnterpriseApp(boolean androidEnterpriseApp) { isAndroidEnterpriseApp = androidEnterpriseApp; } + + public String getInstallerName() { return installerName; } + + public void setInstallerName(String installerName) { this.installerName = installerName; } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/response/ApplicationRelease.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/response/ApplicationRelease.java index 36ed3e86485..25009bae1f2 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/response/ApplicationRelease.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/response/ApplicationRelease.java @@ -87,6 +87,10 @@ public class ApplicationRelease { value = "Application Rating") private double rating; + @ApiModelProperty(name = "packageName", + value = "package name of the application") + private String packageName; + public String getReleaseType() { return releaseType; } @@ -162,4 +166,8 @@ public class ApplicationRelease { public List getScreenshots() { return screenshots; } public void setScreenshots(List screenshots) { this.screenshots = screenshots; } + + public String getPackageName() { return packageName; } + + public void setPackageName(String packageName) { this.packageName = packageName; } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java index ab031305f8b..73f78478e70 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java @@ -281,6 +281,16 @@ public interface ApplicationManager { String getInstallableLifecycleState() throws ApplicationManagementException; + /** + * Check if there are subscription devices for operations + * + * @param operationId Id of the operation + * @param deviceId deviceId of the relevant device + * @return boolean value either true or false according to the situation + * @throws ApplicationManagementException + */ + boolean checkSubDeviceIdsForOperations(int operationId, int deviceId) throws ApplicationManagementException; + void updateSubsStatus (int deviceId, int operationId, String status) throws ApplicationManagementException; diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/wrapper/EntAppReleaseWrapper.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/wrapper/EntAppReleaseWrapper.java index ad79d9e7f31..c3c7ddb84dd 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/wrapper/EntAppReleaseWrapper.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/wrapper/EntAppReleaseWrapper.java @@ -60,6 +60,14 @@ public class EntAppReleaseWrapper { @NotNull private String supportedOsVersions; + @ApiModelProperty(name = "version", + value = "Version number of the applications installer specifically for windows") + private String version; + + @ApiModelProperty(name = "packageName", + value = "PackageName of the application installer specifically for windows") + private String packageName; + public String getReleaseType() { return releaseType; } @@ -99,4 +107,20 @@ public class EntAppReleaseWrapper { public String getSupportedOsVersions() { return supportedOsVersions; } public void setSupportedOsVersions(String supportedOsVersions) { this.supportedOsVersions = supportedOsVersions; } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getPackageName() { + return packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java index 1404c0c912f..3e4942158fd 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java @@ -141,6 +141,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); ApplicationDTO applicationDTO = APIUtil.convertToAppDTO(applicationWrapper); + //uploading application artifacts ApplicationReleaseDTO applicationReleaseDTO = uploadEntAppReleaseArtifacts( applicationDTO.getApplicationReleaseDTOs().get(0), applicationArtifact, @@ -338,9 +339,25 @@ public class ApplicationManagerImpl implements ApplicationManager { byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream()); applicationReleaseDTO.setInstallerName(applicationArtifact.getInstallerName()); try (ByteArrayInputStream binary = new ByteArrayInputStream(content)) { - ApplicationInstaller applicationInstaller = applicationStorageManager - .getAppInstallerData(binary, deviceType); - String packagename = applicationInstaller.getPackageName(); + ApplicationInstaller applicationInstaller = null; + String packagename; + if (!DeviceTypes.WINDOWS.toString().equalsIgnoreCase(deviceType)) { + applicationInstaller = applicationStorageManager.getAppInstallerData(binary, deviceType); + packagename = applicationInstaller.getPackageName(); + applicationReleaseDTO.setVersion(applicationInstaller.getVersion()); + applicationReleaseDTO.setPackageName(packagename); + } else { + String windowsInstallerName = applicationArtifact.getInstallerName(); + String extension = windowsInstallerName.substring(windowsInstallerName.lastIndexOf(".") + 1); + if (!extension.equalsIgnoreCase(Constants.MSI) && + !extension.equalsIgnoreCase(Constants.APPX)) { + String msg = "Application Type doesn't match with supporting application types of " + + deviceType + "platform which are APPX and MSI"; + log.error(msg); + throw new BadRequestException(msg); + } + packagename = applicationReleaseDTO.getPackageName(); + } try { ConnectionManagerUtil.openDBConnection(); @@ -354,8 +371,6 @@ public class ApplicationManagerImpl implements ApplicationManager { log.error(msg); throw new ApplicationManagementException(msg); } - applicationReleaseDTO.setVersion(applicationInstaller.getVersion()); - applicationReleaseDTO.setPackageName(packagename); String md5OfApp = StorageManagementUtil.getMD5(new ByteArrayInputStream(content)); if (md5OfApp == null) { String msg = "Error occurred while md5sum value retrieving process: application UUID " @@ -1012,6 +1027,7 @@ public class ApplicationManagerImpl implements ApplicationManager { log.error(msg); throw new BadRequestException(msg); } + ApplicationReleaseDTO applicationReleaseDTO = uploadEntAppReleaseArtifacts( APIUtil.releaseWrapperToReleaseDTO(entAppReleaseWrapper), applicationArtifact, deviceType.getName(), tenantId, true); @@ -2680,7 +2696,12 @@ public class ApplicationManagerImpl implements ApplicationManager { if (!StringUtils.isEmpty(entAppReleaseWrapper.getMetaData())) { applicationReleaseDTO.get().setMetaData(entAppReleaseWrapper.getMetaData()); } - + if (!StringUtils.isEmpty(entAppReleaseWrapper.getVersion())) { // Updating version + applicationReleaseDTO.get().setVersion(entAppReleaseWrapper.getVersion()); + } + if (!StringUtils.isEmpty(entAppReleaseWrapper.getPackageName())) { // Updating packageName + applicationReleaseDTO.get().setPackageName(entAppReleaseWrapper.getPackageName()); + } if (!StringUtils.isEmpty(applicationArtifact.getInstallerName()) && applicationArtifact.getInstallerStream() != null) { DeviceType deviceTypeObj = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); @@ -3114,6 +3135,17 @@ public class ApplicationManagerImpl implements ApplicationManager { throw new BadRequestException(msg); } unrestrictedRoles = applicationWrapper.getUnrestrictedRoles(); + + //Validating the version number and the packageName of the Windows applications + if (DeviceTypes.WINDOWS.toString().equalsIgnoreCase(applicationWrapper.getDeviceType())) { + if (applicationWrapper.getEntAppReleaseWrappers().get(0).getVersion() == null || + applicationWrapper.getEntAppReleaseWrappers().get(0).getPackageName() == null) { + String msg = "Application Version number or/and PackageName both are required only when the app type is " + + applicationWrapper.getDeviceType() + " platform type"; + log.error(msg); + throw new BadRequestException(msg); + } + } } else if (param instanceof WebAppWrapper) { WebAppWrapper webAppWrapper = (WebAppWrapper) param; appName = webAppWrapper.getName(); @@ -3326,6 +3358,15 @@ public class ApplicationManagerImpl implements ApplicationManager { log.error(msg); throw new BadRequestException(msg); } + //Validating the version number and the packageName of the Windows new applications releases + if (DeviceTypes.WINDOWS.toString().equalsIgnoreCase(deviceType)) { + if (entAppReleaseWrapper.get().getVersion() == null || entAppReleaseWrapper.get().getPackageName() == null) { + String msg = "Application Version number or/and PackageName..both are required only when the app type is " + + deviceType + " platform type"; + log.error(msg); + throw new BadRequestException(msg); + } + } } else if (param instanceof WebAppReleaseWrapper) { WebAppReleaseWrapper webAppReleaseWrapper = (WebAppReleaseWrapper) param; UrlValidator urlValidator = new UrlValidator(); @@ -3414,18 +3455,31 @@ public class ApplicationManagerImpl implements ApplicationManager { } } + @Override + public boolean checkSubDeviceIdsForOperations(int operationId, int deviceId) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + ConnectionManagerUtil.openDBConnection(); + List deviceSubIds = subscriptionDAO.getDeviceSubIdsForOperation(operationId, deviceId, tenantId); + if (deviceSubIds.isEmpty() || deviceSubIds == null) { + return false; + } + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while getting the device sub ids for the operations"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + return true; + } + @Override public void updateSubsStatus (int deviceId, int operationId, String status) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { ConnectionManagerUtil.beginDBTransaction(); List deviceSubIds = subscriptionDAO.getDeviceSubIdsForOperation(operationId, deviceId, tenantId); - if (deviceSubIds.isEmpty()){ - ConnectionManagerUtil.rollbackDBTransaction(); - String msg = "Couldn't find device subscription for operation id " + operationId; - log.error(msg); - throw new ApplicationManagementException(msg); - } if (!subscriptionDAO.updateDeviceSubStatus(deviceId, deviceSubIds, status, tenantId)){ ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Didn't update an any app subscription of device for operation Id: " + operationId; 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 c844ddaf085..248b0d272c9 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 @@ -82,6 +82,7 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.util.MDMAndroidOperationUtil; import org.wso2.carbon.device.mgt.core.util.MDMIOSOperationUtil; +import org.wso2.carbon.device.mgt.core.util.MDMWindowsOperationUtil; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.device.mgt.common.PaginationResult; @@ -1022,6 +1023,18 @@ public class SubscriptionManagerImpl implements SubscriptionManager { log.error(msg); throw new ApplicationManagementException(msg); } + } else if (DeviceTypes.WINDOWS.toString().equalsIgnoreCase(deviceType)) { + app.setType(mobileAppType); + app.setIdentifier(application.getPackageName()); + app.setMetaData(application.getApplicationReleases().get(0).getMetaData()); + app.setName(application.getInstallerName()); + if (SubAction.INSTALL.toString().equalsIgnoreCase(action)) { + return MDMWindowsOperationUtil.createInstallAppOperation(app); + } else { + String msg = "Invalid Action is found. Action: " + action; + log.error(msg); + throw new ApplicationManagementException(msg); + } } else { String msg = "Invalid device type is found. Device Type: " + deviceType; log.error(msg); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/APIUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/APIUtil.java index 12d28191b74..a2375f1d553 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/APIUtil.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/APIUtil.java @@ -304,6 +304,10 @@ public class APIUtil { applicationReleaseDTO.setIsSharedWithAllTenants(entAppReleaseWrapper.getIsSharedWithAllTenants()); applicationReleaseDTO.setMetaData(entAppReleaseWrapper.getMetaData()); applicationReleaseDTO.setSupportedOsVersions(entAppReleaseWrapper.getSupportedOsVersions()); + //Setting version number value specifically for windows type and in an instance of android and ios it will be null + applicationReleaseDTO.setVersion(entAppReleaseWrapper.getVersion()); + //Setting package name value specifically for windows type and in an instance of android and ios it will be null + applicationReleaseDTO.setPackageName(entAppReleaseWrapper.getPackageName()); } else if (param instanceof WebAppReleaseWrapper){ WebAppReleaseWrapper webAppReleaseWrapper = (WebAppReleaseWrapper) param; applicationReleaseDTO.setDescription(webAppReleaseWrapper.getDescription()); @@ -358,6 +362,7 @@ public class APIUtil { application.setTags(applicationDTO.getTags()); application.setUnrestrictedRoles(applicationDTO.getUnrestrictedRoles()); application.setRating(applicationDTO.getAppRating()); + application.setInstallerName(applicationDTO.getApplicationReleaseDTOs().get(0).getInstallerName()); List applicationReleases = new ArrayList<>(); if (ApplicationType.PUBLIC.toString().equals(applicationDTO.getType()) && application.getCategories() .contains("GooglePlaySyncedApp")) { @@ -384,6 +389,7 @@ public class APIUtil { applicationRelease.setDescription(applicationReleaseDTO.getDescription()); applicationRelease.setVersion(applicationReleaseDTO.getVersion()); + applicationRelease.setPackageName(applicationReleaseDTO.getPackageName()); applicationRelease.setUuid(applicationReleaseDTO.getUuid()); applicationRelease.setReleaseType(applicationReleaseDTO.getReleaseType()); applicationRelease.setPrice(applicationReleaseDTO.getPrice()); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/Constants.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/Constants.java index 11ca234e1a9..c18224f417e 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/Constants.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/Constants.java @@ -65,6 +65,10 @@ public class Constants { public static final String SUBSCRIBED = "SUBSCRIBED"; public static final String UNSUBSCRIBED = "UNSUBSCRIBED"; + //App type constants related to window device type + public static final String MSI = "MSI"; + public static final String APPX = "APPX"; + private static final Map AGENT_DATA = new HashMap<>(); static { AGENT_DATA.put("android", "android-agent.apk"); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java index 2b53e65da7f..74f4b4ee752 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java @@ -373,6 +373,10 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem log.error("ApplicationDTO Creation Failed"); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } + } catch (BadRequestException e) { + String msg = "Found incompatible payload with enterprise app release creating request."; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (ApplicationManagementException e) { String msg = "Error occurred while creating the application"; log.error(msg, e); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/public/conf/config.json b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/public/conf/config.json index de1726ce398..9264aac6d7f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/public/conf/config.json +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/public/conf/config.json @@ -85,6 +85,12 @@ } }, "deviceTypes": { - "mobileTypes": ["android", "ios"] + "mobileTypes": ["android", "ios", "windows"] + }, + "windowsDeviceType": { + "appType": ["msi", "appx"] + }, + "windowsAppxMsiKeyValueForMetaData": { + "metaKeyArray": ["Package_Url", "Dependency_Package_Url", "Certificate_Hash", "Encoded_Cert_Content", "Package_Family_Name", "Product_Id", "Content_Uri", "File_Hash"] } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/AddNewApp/components/AddNewAppForm/components/NewAppDetailsForm/index.js b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/AddNewApp/components/AddNewAppForm/components/NewAppDetailsForm/index.js index 4219e5fcd66..c1bfc1f5c0b 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/AddNewApp/components/AddNewAppForm/components/NewAppDetailsForm/index.js +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/AddNewApp/components/AddNewAppForm/components/NewAppDetailsForm/index.js @@ -46,6 +46,7 @@ class NewAppDetailsForm extends React.Component { categories: [], tags: [], deviceTypes: [], + selectedValue: null, fetching: false, roleSearchValue: [], unrestrictedRoles: [], @@ -312,12 +313,33 @@ class NewAppDetailsForm extends React.Component { }); }; + // Event handler for selecting the device type + handleSelect = event => { + this.setState({ + selectedValue: event, + }); + if (this.props.selectedValueHandler) { + this.props.selectedValueHandler(event); + } + }; + + // Event handler for selecting the windows app type + handleSelectForAppType = event => { + if (this.props.selectedAppTypeHandler) { + this.props.selectedAppTypeHandler(event); + } + }; + render() { + const config = this.props.context; + // Windows installation app types + const appTypes = config.windowsDeviceType.appType; const { formConfig } = this.props; const { categories, tags, deviceTypes, + selectedValue, fetching, unrestrictedRoles, } = this.state; @@ -358,6 +380,7 @@ class NewAppDetailsForm extends React.Component { )} + {/* App Type only shown for windows device types for enterprise apps */} + {selectedValue === 'windows' && + this.props.formConfig.installationType === 'ENTERPRISE' && ( + + {getFieldDecorator('appType', { + rules: [ + { + required: true, + message: 'Please select app type', + }, + ], + })( + , + )} + + )} + {/* description*/} {getFieldDecorator('description', { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/AddNewApp/components/AddNewAppForm/components/NewAppUploadForm/index.js b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/AddNewApp/components/AddNewAppForm/components/NewAppUploadForm/index.js index 32368cb26a0..eb918dc4232 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/AddNewApp/components/AddNewAppForm/components/NewAppUploadForm/index.js +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/src/scenes/Home/scenes/AddNewApp/components/AddNewAppForm/components/NewAppUploadForm/index.js @@ -33,6 +33,7 @@ import { } from 'antd'; import '@babel/polyfill'; import Authorized from '../../../../../../../../components/Authorized/Authorized'; +import { withConfigContext } from '../../../../../../../../components/ConfigContext'; const { Text } = Typography; @@ -59,6 +60,12 @@ function getBase64(file) { }); } +// function for access the full name of the binary file using the installation path +function extractBinaryFileName(installationPath) { + let UploadedBinaryName = installationPath.split('/'); + return UploadedBinaryName[UploadedBinaryName.length - 1]; +} + class NewAppUploadForm extends React.Component { constructor(props) { super(props); @@ -77,6 +84,7 @@ class NewAppUploadForm extends React.Component { osVersionsHelperText: '', osVersionsValidateStatus: 'validating', metaData: [], + appType: null, }; this.lowerOsVersion = null; this.upperOsVersion = null; @@ -93,6 +101,8 @@ class NewAppUploadForm extends React.Component { e.preventDefault(); const { formConfig } = this.props; const { specificElements } = formConfig; + let windowsAppTypeMetaArray = []; + let metaValue = []; this.props.form.validateFields((err, values) => { if (!err) { @@ -107,6 +117,19 @@ class NewAppUploadForm extends React.Component { releaseType, } = values; + /** + * To save the metaData value that receive from + * metaData UI In an windows app type creation + */ + if ( + ((this.props.formConfig.installationType === 'ENTERPRISE' && + this.props.selectedValue === 'windows') || + this.props.deviceType === 'windows') && + this.state.metaData.length !== 0 + ) { + metaValue = [...this.state.metaData]; + } + // add release data const release = { description: releaseDescription, @@ -116,6 +139,90 @@ class NewAppUploadForm extends React.Component { releaseType: releaseType, }; + const data = new FormData(); + const config = this.props.context; + // Accessing the Meta Key value for windows device type from the config.json file + const metaKeyValues = + config.windowsAppxMsiKeyValueForMetaData.metaKeyArray; + + /* + Setting up the app type specific values to the + metaData state field and Setting up the version + and the packageName for windows type + */ + if ( + (this.props.formConfig.installationType === 'ENTERPRISE' && + this.props.selectedValue === 'windows') || + this.props.deviceType === 'windows' + ) { + // Setting up the version and packageName + release.version = values.version; + release.packageName = values.packageName; + // setting the metaData value for appx type + if ( + this.props.selectedAppType === 'appx' || + this.state.appType === 'appx' + ) { + windowsAppTypeMetaArray = [ + { + key: metaKeyValues[0], + value: values.packageUrl, + }, + { + key: metaKeyValues[1], + value: values.dependencyPackageUrl, + }, + { + key: metaKeyValues[2], + value: values.certificateHash, + }, + { + key: metaKeyValues[3], + value: values.encodedCertContent, + }, + { + key: metaKeyValues[4], + value: values.packageName, + }, + ]; + windowsAppTypeMetaArray = [ + ...windowsAppTypeMetaArray, + ...metaValue, + ]; + } else if ( + this.props.selectedAppType === 'msi' || + this.state.appType === 'msi' + ) { + windowsAppTypeMetaArray = [ + { + key: metaKeyValues[5], + value: values.productId, + }, + { + key: metaKeyValues[6], + value: values.contentUri, + }, + { + key: metaKeyValues[7], + value: values.fileHash, + }, + ]; + windowsAppTypeMetaArray = [ + ...windowsAppTypeMetaArray, + ...metaValue, + ]; + } + this.setState( + { + metaData: windowsAppTypeMetaArray, + }, + () => { + release.metaData = JSON.stringify(this.state.metaData); + this.props.onSuccessReleaseData({ data, release }); + }, + ); + } + if (specificElements.hasOwnProperty('version')) { release.version = values.version; } @@ -126,7 +233,6 @@ class NewAppUploadForm extends React.Component { release.packageName = values.packageName; } - const data = new FormData(); let isFormValid = true; // flag to check if this form is valid if ( @@ -187,7 +293,16 @@ class NewAppUploadForm extends React.Component { if (specificElements.hasOwnProperty('binaryFile')) { data.append('binaryFile', binaryFile[0].originFileObj); } - this.props.onSuccessReleaseData({ data, release }); + // Condition to check is it not an Enterprise windows app creation or release + if ( + !( + this.props.selectedValue === 'windows' && + this.props.formConfig.installationType === 'ENTERPRISE' + ) && + this.props.deviceType !== 'windows' + ) { + this.props.onSuccessReleaseData({ data, release }); + } } } }); @@ -203,13 +318,44 @@ class NewAppUploadForm extends React.Component { icons: fileList, }); }; + handleBinaryFileChange = ({ fileList }) => { + let validity = true; + // To set the app type of windows by using the binary file in an new app release + if (this.props.formConfig.isNewRelease && fileList.length !== 0) { + let firstUploadedBinaryFileName = extractBinaryFileName( + this.props.uploadedInstalltionAppType, + ); + let FirstFileExtension = firstUploadedBinaryFileName.substr( + firstUploadedBinaryFileName.lastIndexOf('.') + 1, + ); + let LastFileExtension = fileList[0].name.substr( + fileList[0].name.lastIndexOf('.') + 1, + ); + if (FirstFileExtension !== LastFileExtension) { + validity = false; + } else if (LastFileExtension === 'msi' || LastFileExtension === 'appx') { + this.setState({ + appType: LastFileExtension, + }); + } + } + if (fileList.length === 1) { this.setState({ binaryFileHelperText: '', }); } - this.setState({ binaryFiles: fileList }); + + if (validity) { + this.setState({ + binaryFiles: fileList, + }); + } else { + this.setState({ + binaryFileHelperText: 'Upload Correct Binary File extension', + }); + } }; handleScreenshotChange = ({ fileList }) => { @@ -266,6 +412,7 @@ class NewAppUploadForm extends React.Component { render() { const { formConfig, supportedOsVersions } = this.props; const { getFieldDecorator } = this.props.form; + const config = this.props.context; const { icons, screenshots, @@ -399,7 +546,12 @@ class NewAppUploadForm extends React.Component { - {formConfig.specificElements.hasOwnProperty('packageName') && ( + + {/* Package Name field for windows device type and other specific scene using it */} + {(formConfig.specificElements.hasOwnProperty('packageName') || + (this.props.formConfig.installationType === 'ENTERPRISE' && + this.props.selectedValue === 'windows') || + this.props.deviceType === 'windows') && ( {getFieldDecorator('packageName', { rules: [ @@ -425,7 +577,11 @@ class NewAppUploadForm extends React.Component { )} - {formConfig.specificElements.hasOwnProperty('version') && ( + {/* Version field for windows device type and other specific scene using it */} + {(formConfig.specificElements.hasOwnProperty('version') || + (this.props.formConfig.installationType === 'ENTERPRISE' && + this.props.selectedValue === 'windows') || + this.props.deviceType === 'windows') && ( {getFieldDecorator('version', { rules: [ @@ -438,6 +594,127 @@ class NewAppUploadForm extends React.Component { )} + {/* Windows Appx App Type Fields */} + {/* For Windows appx app type only -> Package Url */} + {((this.props.formConfig.installationType === 'ENTERPRISE' && + this.props.selectedValue === 'windows' && + this.props.selectedAppType === 'appx') || + this.state.appType === 'appx') && ( + + {getFieldDecorator('packageUrl', { + rules: [ + { + required: true, + message: 'Please input the package url', + }, + ], + })()} + + )} + + {/* For Windows appx app type only -> Dependency Package Url */} + {((this.props.formConfig.installationType === 'ENTERPRISE' && + this.props.selectedValue === 'windows' && + this.props.selectedAppType === 'appx') || + this.state.appType === 'appx') && ( + + {getFieldDecorator('dependencyPackageUrl', {})( + , + )} + + )} + + {/* For Windows appx app type only -> Certificate Hash */} + {((this.props.formConfig.installationType === 'ENTERPRISE' && + this.props.selectedValue === 'windows' && + this.props.selectedAppType === 'appx') || + this.state.appType === 'appx') && ( + + {getFieldDecorator('certificateHash', { + rules: [ + { + required: true, + message: 'Please input the certificate hash', + }, + ], + })()} + + )} + + {/* For Windows appx app type only -> Encoded Certificate Content */} + {((this.props.formConfig.installationType === 'ENTERPRISE' && + this.props.selectedValue === 'windows' && + this.props.selectedAppType === 'appx') || + this.state.appType === 'appx') && ( + + {getFieldDecorator('encodedCertContent', { + rules: [ + { + required: true, + message: 'Give the encoded cert content', + }, + ], + })( +