diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml index 46c6482561..2d8a1dc40c 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/GrafanaAPIProxyService.java b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/GrafanaAPIProxyService.java index afbf98d345..81f6f9bf4a 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/GrafanaAPIProxyService.java +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/GrafanaAPIProxyService.java @@ -45,9 +45,9 @@ import javax.ws.rs.core.*; @Scope( name = "Using Grafana APIs required for Grafana iframes", description = "Grafana API proxy to validate requests.", - key = "perm:grafana:api:view", - roles = {"Internal/grafanamgt-user"}, - permissions = {"/analytics-mgt/grafana-mgt/api/view"} + key = "grafana:api:view", + roles = {"Internal/devicemgt-user"}, + permissions = {"/device-mgt/grafana/view"} ) } ) @@ -71,7 +71,7 @@ public interface GrafanaAPIProxyService { tags = "Analytics", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:grafana:api:view") + @ExtensionProperty(name = SCOPE, value = "grafana:api:view") }) } ) @@ -88,7 +88,7 @@ public interface GrafanaAPIProxyService { tags = "Analytics", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:grafana:api:view") + @ExtensionProperty(name = SCOPE, value = "grafana:api:view") }) } ) @@ -104,7 +104,7 @@ public interface GrafanaAPIProxyService { tags = "Analytics", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:grafana:api:view") + @ExtensionProperty(name = SCOPE, value = "grafana:api:view") }) } ) @@ -121,7 +121,7 @@ public interface GrafanaAPIProxyService { tags = "Analytics", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:grafana:api:view") + @ExtensionProperty(name = SCOPE, value = "grafana:api:view") }) } ) @@ -137,7 +137,7 @@ public interface GrafanaAPIProxyService { tags = "Analytics", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:grafana:api:view") + @ExtensionProperty(name = SCOPE, value = "grafana:api:view") }) } ) diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml index 7b39827240..a759665e92 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml index cb89652674..ce25a77c31 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/grafana-mgt/pom.xml b/components/analytics-mgt/grafana-mgt/pom.xml index 8d10307c7e..7bc9db7e86 100644 --- a/components/analytics-mgt/grafana-mgt/pom.xml +++ b/components/analytics-mgt/grafana-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core analytics-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/pom.xml b/components/analytics-mgt/pom.xml index 2bacce641b..bc9ce9529f 100644 --- a/components/analytics-mgt/pom.xml +++ b/components/analytics-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml index b264448977..951f3813a2 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml @@ -20,7 +20,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT 4.0.0 diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml index e8d23d4294..8fc927f575 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml index 7d17b52f92..00bad68142 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml @@ -21,7 +21,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml index c805d76f9a..6f278017d0 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml index d8a899d9a0..0529a0a238 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java index 49f76f0622..594096cc62 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java @@ -19,11 +19,16 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Scope; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Mediation; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevision; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevisionDeployment; import org.json.JSONObject; import org.wso2.carbon.apimgt.api.model.*; @@ -43,7 +48,7 @@ public interface PublisherRESTAPIServices { boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) throws APIServicesException, BadRequestException, UnexpectedResponseException; - JSONObject getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + JSONObject getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid) throws APIServicesException, BadRequestException, UnexpectedResponseException; JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) @@ -60,15 +65,15 @@ public interface PublisherRESTAPIServices { throws APIServicesException, BadRequestException, UnexpectedResponseException; JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIIdentifier apiIdentifier) + String apiUuid) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean addApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, Mediation mediation) throws APIServicesException, BadRequestException, UnexpectedResponseException; - boolean updateApiSpecificMediationPolicyContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Mediation mediation) + boolean deleteApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, Mediation mediation) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean changeLifeCycleStatus(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, @@ -103,11 +108,11 @@ public interface PublisherRESTAPIServices { String uuid, String documentID) throws APIServicesException, BadRequestException, UnexpectedResponseException; - Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, Documentation documentation) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIInfo api, String docId, String docContent) + String apiUuid, String docId, String docContent) throws APIServicesException, BadRequestException, UnexpectedResponseException; } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java index bcc282e843..20ced0213f 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java @@ -22,6 +22,11 @@ import com.google.gson.Gson; import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Scope; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Mediation; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevision; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevisionDeployment; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; @@ -29,6 +34,7 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.Unexpected import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.ScopeUtils; import okhttp3.*; +import okhttp3.Request.Builder; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -228,10 +234,10 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } @Override - public JSONObject getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + public JSONObject getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String getAllApi = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID(); + String getAllApi = endPointPrefix + Constants.API_ENDPOINT + apiUuid; Request request = new Request.Builder() .url(getAllApi) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER @@ -250,7 +256,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); //TODO: max attempt count - return getApi(apiApplicationKey, refreshedAccessToken, apiIdentifier); + return getApi(apiApplicationKey, refreshedAccessToken, apiUuid); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { String msg = "Bad Request, Invalid request"; log.error(msg); @@ -335,6 +341,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { " \"apiThrottlingPolicy\": " + api.getApiThrottlingPolicy() + ",\n" + " \"authorizationHeader\": \"" + api.getAuthorizationHeader() + "\",\n" + " \"visibility\": \"" + api.getVisibility() + "\",\n" + + " \"mediationPolicies\": " + (api.getInSequence() != null ? "[{\"name\": \"" + api.getInSequence() + "\",\"type\": \"in\"}]" : null) + ",\n" + " \"subscriptionAvailability\": \"" + api.getSubscriptionAvailability() + "\",\n" + " \"subscriptionAvailableTenants\": [],\n" + " \"additionalProperties\": [],\n" + @@ -350,7 +357,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { " \"endpointConfig\": " + api.getEndpointConfig().toString() + ",\n" + " \"endpointImplementationType\": \"ENDPOINT\",\n" + " \"scopes\": " + api.getScopes().toString() + ",\n" + - " \"operations\": " + api.getOperations().toString() + ",\n" + + " \"operations\": " + (api.getOperations() != null ? api.getOperations().toString() : null) + ",\n" + " \"threatProtectionPolicies\": null,\n" + " \"categories\": [],\n" + " \"keyManagers\": " + gson.toJson(api.getKeyManagers()) + ",\n" + @@ -422,6 +429,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { " \"apiThrottlingPolicy\": " + api.getApiThrottlingPolicy() + ",\n" + " \"authorizationHeader\": \"" + api.getAuthorizationHeader() + "\",\n" + " \"visibility\": \"" + api.getVisibility() + "\",\n" + + " \"mediationPolicies\": " + (api.getInSequence() != null ? "[{\"name\": \"" + api.getInSequence() + "\",\"type\": \"in\"}]" : null) + ",\n" + " \"subscriptionAvailability\": \"" + api.getSubscriptionAvailability() + "\",\n" + " \"subscriptionAvailableTenants\": [],\n" + " \"additionalProperties\": [],\n" + @@ -437,7 +445,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { " \"endpointConfig\": " + api.getEndpointConfig().toString() + ",\n" + " \"endpointImplementationType\": \"ENDPOINT\",\n" + " \"scopes\": " + api.getScopes().toString() + ",\n" + - " \"operations\": " + api.getOperations().toString() + ",\n" + + " \"operations\": " + (api.getOperations() != null? api.getOperations().toString() : null) + ",\n" + " \"threatProtectionPolicies\": null,\n" + " \"categories\": [],\n" + " \"keyManagers\": " + gson.toJson(api.getKeyManagers()) + ",\n" + @@ -484,11 +492,16 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { String uuid, String asyncApiDefinition) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String addNewScope = endPointPrefix + Constants.API_ENDPOINT + uuid; + String saveAsyncAPI = endPointPrefix + Constants.API_ENDPOINT + uuid + "/asyncapi"; + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("apiDefinition", asyncApiDefinition) + .build(); - RequestBody requestBody = RequestBody.create(JSON, asyncApiDefinition); Request request = new Request.Builder() - .url(addNewScope) + .url(saveAsyncAPI) + .addHeader(Constants.HEADER_CONTENT_TYPE, "multipart/form-data") .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .put(requestBody) @@ -523,10 +536,10 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { @Override public JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIIdentifier apiIdentifier) + String apiUuid) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String getAPIMediationEndPoint = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/mediation-policies"; + String getAPIMediationEndPoint = endPointPrefix + Constants.API_ENDPOINT + apiUuid + "/mediation-policies"; Request request = new Request.Builder() .url(getAPIMediationEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER @@ -545,7 +558,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); //TODO: max attempt count - return getAllApiSpecificMediationPolicies(apiApplicationKey, refreshedAccessToken, apiIdentifier); + return getAllApiSpecificMediationPolicies(apiApplicationKey, refreshedAccessToken, apiUuid); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { String msg = "Bad Request, Invalid request"; log.error(msg); @@ -566,12 +579,17 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { String uuid, Mediation mediation) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String addAPIMediation = endPointPrefix + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid() - + "/content"; + String addAPIMediation = endPointPrefix + Constants.API_ENDPOINT + uuid + "/mediation-policies"; - RequestBody requestBody = RequestBody.create(JSON, String.valueOf(mediation)); - Request request = new Request.Builder() + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("inlineContent", mediation.getConfig()) + .addFormDataPart("type", mediation.getType()) + .build(); + + Request request = new Builder() .url(addAPIMediation) + .addHeader(Constants.HEADER_CONTENT_TYPE, "multipart/form-data") .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .post(requestBody) @@ -604,26 +622,23 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } - @Override - public boolean updateApiSpecificMediationPolicyContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + public boolean deleteApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, Mediation mediation) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String updateApiMediationEndPOint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid() - + "/content"; + String deleteApiMediationEndPOint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid(); - RequestBody requestBody = RequestBody.create(JSON, String.valueOf(mediation)); Request request = new Request.Builder() - .url(updateApiMediationEndPOint) + .url(deleteApiMediationEndPOint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) - .put(requestBody) + .delete() .build(); try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { // Check response status + if (HttpStatus.SC_NO_CONTENT == response.code()) { // Check response status return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -631,7 +646,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); //TODO: max attempt count - return updateApiSpecificMediationPolicyContent(apiApplicationKey, refreshedAccessToken, uuid, mediation); + return deleteApiSpecificMediationPolicy(apiApplicationKey, refreshedAccessToken, uuid, mediation); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { String msg = "Bad Request, Invalid mediation policy"; log.error(msg); @@ -1009,18 +1024,19 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { String addNewScope = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents"; String document = "{\n" + - " \"name\": \" " + documentation.getName() + " \",\n" + - " \"type\": \" " + documentation.getType() + " \",\n" + - " \"summary\": \" " + documentation.getSummary() + " \",\n" + - " \"sourceType\": \" " + documentation.getSourceType() + " \",\n" + - " \"inlineContent\": \" " + documentation.getSourceType() + " \",\n" + - " \"visibility\": \" " + documentation.getVisibility() + " \",\n" + - " \"createdBy\": \" admin \"\n" + + " \"name\": \"" + documentation.getName() + "\",\n" + + " \"type\": \"" + documentation.getType() + "\",\n" + + " \"summary\": \"" + documentation.getSummary() + "\",\n" + + " \"sourceType\": \"" + documentation.getSourceType() + "\",\n" + + " \"inlineContent\": \"" + documentation.getSourceType() + "\",\n" + + " \"visibility\": \"" + documentation.getVisibility() + "\",\n" + + " \"createdBy\": \"admin\"\n" + "}"; RequestBody requestBody = RequestBody.create(JSON, document); Request request = new Request.Builder() .url(addNewScope) + .addHeader(Constants.HEADER_CONTENT_TYPE, Constants.APPLICATION_JSON) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .post(requestBody) @@ -1054,14 +1070,19 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { @Override public boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIInfo api, String docId, String docContent) + String apiUuid, String docId, String docContent) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String addDocumentationContentEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getId() + "/documents/" + docId; + String addDocumentationContentEndPoint = endPointPrefix + Constants.API_ENDPOINT + apiUuid + "/documents/" + docId + "/content"; + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("inlineContent", docContent) + .build(); - RequestBody requestBody = RequestBody.create(JSON, docContent); Request request = new Request.Builder() .url(addDocumentationContentEndPoint) + .addHeader(Constants.HEADER_CONTENT_TYPE, "multipart/form-data") .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .post(requestBody) @@ -1077,7 +1098,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); //TODO: max attempt count - return addDocumentationContent(apiApplicationKey, refreshedAccessToken, api, docId, docContent); + return addDocumentationContent(apiApplicationKey, refreshedAccessToken, apiUuid, docId, docContent); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { String msg = "Bad Request, Invalid documentation request body"; log.error(msg); diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/APIInfo.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/APIInfo.java index a6f76116d9..b7443b0f53 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/APIInfo.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/APIInfo.java @@ -1,12 +1,12 @@ /* - * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2023, 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 + * 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 @@ -19,13 +19,8 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; import org.json.JSONObject; -import org.wso2.carbon.apimgt.api.model.APICategory; -import org.wso2.carbon.apimgt.api.model.CORSConfiguration; -import org.wso2.carbon.apimgt.api.model.WebsubSubscriptionConfiguration; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; +import java.util.*; /** * This class represents the API response. @@ -70,7 +65,6 @@ public class APIInfo { private String accessControlRoles; private BusinessInformation businessInformation; private CORSConfiguration corsConfiguration; - private WebsubSubscriptionConfiguration websubSubscriptionConfiguration; private String workflowStatus; private String createdTime; private String lastUpdatedTime; @@ -79,11 +73,16 @@ public class APIInfo { private List scopes = new ArrayList(); private List operations; private String threatProtectionPolicies; - private List apiCategories; private List keyManagers = new ArrayList(); private JSONObject serviceInfo = new JSONObject(); private AdvertiseInfo advertiseInfo; + private String asyncApiDefinition; + + private Set uriTemplates = new LinkedHashSet(); + private String inSequence; + + private Map wsUriMapping; public String getId() { return id; } @@ -372,14 +371,6 @@ public class APIInfo { this.corsConfiguration = corsConfiguration; } - public WebsubSubscriptionConfiguration getWebsubSubscriptionConfiguration() { - return websubSubscriptionConfiguration; - } - - public void setWebsubSubscriptionConfiguration(WebsubSubscriptionConfiguration websubSubscriptionConfiguration) { - this.websubSubscriptionConfiguration = websubSubscriptionConfiguration; - } - public String getWorkflowStatus() { return workflowStatus; } @@ -444,14 +435,6 @@ public class APIInfo { this.threatProtectionPolicies = threatProtectionPolicies; } - public List getApiCategories() { - return apiCategories; - } - - public void setApiCategories(List apiCategories) { - this.apiCategories = apiCategories; - } - public List getKeyManagers() { return keyManagers; } @@ -475,4 +458,36 @@ public class APIInfo { public void setAdvertiseInfo(AdvertiseInfo advertiseInfo) { this.advertiseInfo = advertiseInfo; } + + public String getInSequence() { + return inSequence; + } + + public void setInSequence(String inSequence) { + this.inSequence = inSequence; + } + + public String getAsyncApiDefinition() { + return asyncApiDefinition; + } + + public void setAsyncApiDefinition(String asyncApiDefinition) { + this.asyncApiDefinition = asyncApiDefinition; + } + + public Set getUriTemplates() { + return uriTemplates; + } + + public void setUriTemplates(Set uriTemplates) { + this.uriTemplates = uriTemplates; + } + + public Map getWsUriMapping() { + return wsUriMapping; + } + + public void setWsUriMapping(Map wsUriMapping) { + this.wsUriMapping = wsUriMapping; + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/APIRevision.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/APIRevision.java new file mode 100644 index 0000000000..581fbb1792 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/APIRevision.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; + +import org.wso2.carbon.apimgt.api.model.APIRevisionDeployment; + +import java.io.Serializable; +import java.util.List; + +public class APIRevision implements Serializable { + private static final long serialVersionUID = 1L; + private int id; + private String apiUUID; + private String revisionUUID; + private String description; + private String createdBy; + private String createdTime; + private List apiRevisionDeploymentList; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getApiUUID() { + return apiUUID; + } + + public void setApiUUID(String apiUUID) { + this.apiUUID = apiUUID; + } + + public String getRevisionUUID() { + return revisionUUID; + } + + public void setRevisionUUID(String revisionUUID) { + this.revisionUUID = revisionUUID; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public String getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(String createdTime) { + this.createdTime = createdTime; + } + + public List getApiRevisionDeploymentList() { + return apiRevisionDeploymentList; + } + + public void setApiRevisionDeploymentList(List apiRevisionDeploymentList) { + this.apiRevisionDeploymentList = apiRevisionDeploymentList; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/APIRevisionDeployment.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/APIRevisionDeployment.java new file mode 100644 index 0000000000..20c84232cc --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/APIRevisionDeployment.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; + +import java.io.Serializable; + +public class APIRevisionDeployment implements Serializable { + private static final long serialVersionUID = 1L; + private int id; + private String revisionUUID; + private String deployment; + private String vhost; + private boolean isDisplayOnDevportal; + private String deployedTime; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getRevisionUUID() { + return revisionUUID; + } + + public void setRevisionUUID(String revisionUUID) { + this.revisionUUID = revisionUUID; + } + + public String getDeployment() { + return deployment; + } + + public void setDeployment(String deployment) { + this.deployment = deployment; + } + + public String getVhost() { + return vhost; + } + + public void setVhost(String vhost) { + this.vhost = vhost; + } + + public boolean isDisplayOnDevportal() { + return isDisplayOnDevportal; + } + + public void setDisplayOnDevportal(boolean displayOnDevportal) { + isDisplayOnDevportal = displayOnDevportal; + } + + public String getDeployedTime() { + return deployedTime; + } + + public void setDeployedTime(String deployedTime) { + this.deployedTime = deployedTime; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/AdvertiseInfo.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/AdvertiseInfo.java index 93511526aa..9ed465bc72 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/AdvertiseInfo.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/AdvertiseInfo.java @@ -1,12 +1,12 @@ /* - * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2023, 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 + * 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 @@ -15,7 +15,6 @@ * specific language governing permissions and limitations * under the License. */ - package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; /** diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/BusinessInformation.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/BusinessInformation.java index ad32e51f15..4310d50cbf 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/BusinessInformation.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/BusinessInformation.java @@ -1,12 +1,12 @@ /* - * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2023, 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 + * 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 diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/CORSConfiguration.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/CORSConfiguration.java new file mode 100644 index 0000000000..1bee613429 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/CORSConfiguration.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; + +import java.util.List; + +/** + * API CORS Configuration + */ +public class CORSConfiguration { + + private boolean corsConfigurationEnabled; + private List accessControlAllowOrigins; + private boolean accessControlAllowCredentials; + private List accessControlAllowHeaders; + private List accessControlAllowMethods; + + public CORSConfiguration(boolean corsConfigurationEnabled, List accessControlAllowOrigins, + boolean accessControlAllowCredentials, + List accessControlAllowHeaders, List accessControlAllowMethods) { + this.corsConfigurationEnabled = corsConfigurationEnabled; + this.accessControlAllowOrigins = accessControlAllowOrigins; + this.accessControlAllowCredentials = accessControlAllowCredentials; + this.accessControlAllowHeaders = accessControlAllowHeaders; + this.accessControlAllowMethods = accessControlAllowMethods; + } + + public boolean isCorsConfigurationEnabled() { + return corsConfigurationEnabled; + } + + public void setCorsConfigurationEnabled(boolean corsConfigurationEnabled) { + this.corsConfigurationEnabled = corsConfigurationEnabled; + } + + public List getAccessControlAllowOrigins() { + return accessControlAllowOrigins; + } + + public void setAccessControlAllowOrigins(List accessControlAllowOrigins) { + this.accessControlAllowOrigins = accessControlAllowOrigins; + } + + public boolean isAccessControlAllowCredentials() { + return accessControlAllowCredentials; + } + + public void setAccessControlAllowCredentials(boolean accessControlAllowCredentials) { + this.accessControlAllowCredentials = accessControlAllowCredentials; + } + + public List getAccessControlAllowHeaders() { + return accessControlAllowHeaders; + } + + public void setAccessControlAllowHeaders(List accessControlAllowHeaders) { + this.accessControlAllowHeaders = accessControlAllowHeaders; + } + + public List getAccessControlAllowMethods() { + return accessControlAllowMethods; + } + + public void setAccessControlAllowMethods(List accessControlAllowMethods) { + this.accessControlAllowMethods = accessControlAllowMethods; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Documentation.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Documentation.java new file mode 100644 index 0000000000..5d54bc7567 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Documentation.java @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; + +import java.util.Date; + +public class Documentation { + + private static final long serialVersionUID = 1L; + private String id; + private String documentId; + private DocumentationType type; + private String name; + private String summary; + private DocumentSourceType sourceType; + private String sourceUrl; + private DocumentVisibility visibility; + private Date lastUpdated; + private String filePath; + private Date createdDate; + private String otherTypeName; + + public String getOtherTypeName() { + return this.otherTypeName; + } + + public void setOtherTypeName(String otherTypeName) { + this.otherTypeName = otherTypeName; + } + + public String getFilePath() { + return this.filePath; + } + + public void setFilePath(String filePath) { + this.filePath = filePath; + } + + public String getSourceUrl() { + return this.sourceUrl; + } + + public void setSourceUrl(String sourceUrl) { + this.sourceUrl = sourceUrl; + } + + public Documentation(DocumentationType type, String name) { + this.type = type; + this.name = name; + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } else if (o != null && this.getClass() == o.getClass()) { + Documentation that = (Documentation)o; + return this.name.equals(that.name) && this.type == that.type; + } else { + return false; + } + } + + public DocumentationType getType() { + return this.type; + } + + public String getName() { + return this.name; + } + + public String getSummary() { + return this.summary; + } + + public void setSummary(String summary) { + this.summary = summary; + } + + public DocumentVisibility getVisibility() { + return this.visibility; + } + + public void setVisibility(DocumentVisibility visibility) { + this.visibility = visibility; + } + + public DocumentSourceType getSourceType() { + return this.sourceType; + } + + public void setSourceType(DocumentSourceType sourceType) { + this.sourceType = sourceType; + } + + public int hashCode() { + int result = this.type.hashCode(); + result = 31 * result + this.name.hashCode(); + return result; + } + + public Date getLastUpdated() { + return this.lastUpdated; + } + + public void setLastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + } + + public String getId() { + return this.id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDocumentId() { + return documentId; + } + + public void setDocumentId(String documentId) { + this.documentId = documentId; + } + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public static enum DocumentVisibility { + OWNER_ONLY("owner_only"), + PRIVATE("private"), + API_LEVEL("api_level"); + + private String visibility; + + private DocumentVisibility(String visibility) { + this.visibility = visibility; + } + } + + public static enum DocumentSourceType { + INLINE("In line"), + MARKDOWN("Markdown"), + URL("URL"), + FILE("File"); + + private String type; + + private DocumentSourceType(String type) { + this.type = type; + } + } + + public static enum DocumentationType { + HOWTO("How To"), + SAMPLES("Samples"), + PUBLIC_FORUM("Public Forum"), + SUPPORT_FORUM("Support Forum"), + API_MESSAGE_FORMAT("API Message Format"), + SWAGGER_DOC("Swagger API Definition"), + OTHER("Other"); + + private String type; + + private DocumentationType(String type) { + this.type = type; + } + + public String getType() { + return type; + } + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Mediation.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Mediation.java new file mode 100644 index 0000000000..5e5125006c --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Mediation.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; + +public class Mediation { + + private String uuid; + private String name; + private String type; + private String config; + private boolean isGlobal; + + public Mediation(){} + + public void setUuid(String id){ + this.uuid=id; + } + public String getUuid(){return uuid;} + + public void setName(String name){this.name=name;} + + public String getName(){return name;} + + public void setType(String mType){this.type=mType;} + + public String getType(){return type;} + + public void setConfig(String mConfig){this.config=mConfig;} + + public String getConfig(){return config;} + + public boolean isGlobal() { + return isGlobal; + } + + public void setGlobal(boolean isGlobal) { + this.isGlobal = isGlobal; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Operations.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Operations.java index 51f2c1ee4c..2dd00c4482 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Operations.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Operations.java @@ -1,12 +1,12 @@ /* - * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2023, 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 + * 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 diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Scope.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Scope.java new file mode 100644 index 0000000000..01d3f53d36 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Scope.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; + +import java.io.Serializable; +import java.util.Objects; + +public class Scope implements Serializable{ + + private static final long serialVersionUID = 1L; + + String key; + String name; + String roles; + String description; + String id; + int usageCount; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getRoles() { + return roles; + } + + public void setRoles(String roles) { + this.roles = roles; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getUsageCount() { + return usageCount; + } + + public void setUsageCount(int usageCount) { + this.usageCount = usageCount; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Scope scope = (Scope) o; + + if (id != null ? !id.equals(scope.id) : scope.id != null) return false; + if (!key.equals(scope.key)) return false; + if (!name.equals(scope.name)) return false; + if (roles != null ? !roles.equals(scope.roles) : scope.roles != null) return false; + return description != null ? description.equals(scope.description) : scope.description == null; + } + + @Override + public int hashCode() { + return Objects.hash(key, name, roles, description, id); + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/URITemplate.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/URITemplate.java new file mode 100644 index 0000000000..9cd69a9f11 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/URITemplate.java @@ -0,0 +1,440 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; + +import org.json.simple.JSONValue; +import org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO; +import org.wso2.carbon.apimgt.api.model.APIProductIdentifier; +import org.wso2.carbon.apimgt.api.model.Scope; +import org.wso2.carbon.apimgt.api.model.policy.PolicyConstants; + +import java.io.Serializable; +import java.util.*; + +public class URITemplate implements Serializable{ + + private static final long serialVersionUID = 1L; + + private String uriTemplate; + private String resourceURI; + private String resourceSandboxURI; + private String httpVerb; + private String authType; + private LinkedHashSet httpVerbs = new LinkedHashSet(); + private List authTypes = new ArrayList(); + private List throttlingConditions = new ArrayList(); + private String applicableLevel; + private String throttlingTier; + private List throttlingTiers = new ArrayList(); + private org.wso2.carbon.apimgt.api.model.Scope scope; + private String mediationScript; + private List scopes = new ArrayList(); + private Map mediationScripts = new HashMap(); + private ConditionGroupDTO[] conditionGroups; + private int id; + private Set usedByProducts = new HashSet<>(); + private String amznResourceName; + private int amznResourceTimeout; + + public ConditionGroupDTO[] getConditionGroups() { + return conditionGroups; + } + + public void setConditionGroups(ConditionGroupDTO[] conditionGroups) { + this.conditionGroups = conditionGroups; + } + + public String getMediationScript() { + return mediationScript; + } + + + public List getThrottlingConditions() { + return throttlingConditions; + } + + public void setThrottlingConditions(List throttlingConditions) { + this.throttlingConditions = throttlingConditions; + } + + public void setMediationScript(String mediationScript) { + this.mediationScript = mediationScript; + } + /** + * Set mediation script for a given http method + * @param method http method name + * @param mediationScript mediation script content + */ + public void setMediationScripts(String method, String mediationScript){ + if (mediationScript != null && !mediationScript.trim().equals("") && !mediationScript.trim().equals("null")){ + mediationScripts.put(method, mediationScript); + } + + } + + /** + * Generating the script by aggregating scripts of each http method to form a single script in to be + * used when generating synapse configuration file. + * + * @return aggregated script in the following format, + * if (http-method = 'GET'){ + * //script for GET + * } + * .... + * .... + * if (http-method = 'POST'){ + * //script for POST + * } + */ + public String getAggregatedMediationScript(){ + if (mediationScripts.isEmpty()){ + return "null"; + }else if (mediationScripts.size() == 1 && httpVerbs.size() == 1){ + return mediationScript; + }else{ + StringBuilder aggregatedScript = new StringBuilder(); + + for (Map.Entry entry : mediationScripts.entrySet()){ + String httpMethod = entry.getKey(); + String mediationScript = entry.getValue(); + + aggregatedScript.append("if (mc.getProperty('REST_METHOD') == '").append(httpMethod).append("'){"); + aggregatedScript.append(mediationScript); + aggregatedScript.append("}"); + + } + + return aggregatedScript.toString(); + } + } + + public String getThrottlingTier() { + return throttlingTier; + } + + public void setThrottlingTier(String throttlingTier) { + this.throttlingTier = throttlingTier; + } + + public List getThrottlingTiers(){ + return throttlingTiers; + } + + public void setThrottlingTiers(List throttlingTiers) { + this.throttlingTiers = throttlingTiers; + } + + public String getHTTPVerb() { + return httpVerb; + } + + public void setHTTPVerb(String httpVerb) { + this.httpVerb = httpVerb; + } + + public String getAuthType() { + return authType; + } + + public void setAuthType(String authType) { + this.authType = authType; + + } + + public String getResourceURI() { + return resourceURI; + } + + public void setResourceURI(String resourceURI) { + this.resourceURI = resourceURI; + } + + public boolean isResourceURIExist(){ + return this.resourceURI != null; + } + + public String getResourceSandboxURI() { + return resourceSandboxURI; + } + + public void setResourceSandboxURI(String resourceSandboxURI) { + this.resourceSandboxURI = resourceSandboxURI; + } + + public boolean isResourceSandboxURIExist(){ + return this.resourceSandboxURI != null; + } + + public String getUriTemplate() { + return uriTemplate; + } + + public void setUriTemplate(String template) { + this.uriTemplate = template; + } + + public void setHttpVerbs(String httpVerb) { + + httpVerbs.add(httpVerb); + } + + public LinkedHashSet getHttpVerbs() { + + return httpVerbs; + } + + + + public void setAuthTypes(String authType) { + + authTypes.add(authType); + } + + public String getAuthTypes() { + + return authType; + } + + + public String getMethodsAsString() { + StringBuilder stringBuilder = new StringBuilder(); + for (String method : httpVerbs) { + stringBuilder.append(method).append(" "); + } + return stringBuilder.toString().trim(); + } + + public String getAuthTypeAsString() { + StringBuilder stringBuilder = new StringBuilder(); + for (String authType : authTypes) { + stringBuilder.append(authType).append(" "); + } + return stringBuilder.toString().trim(); + } + + public String getThrottlingConditionsAsString() { + StringBuilder stringBuilder = new StringBuilder(); + for (String authType : throttlingConditions) { + stringBuilder.append(authType).append(" "); + } + return stringBuilder.toString().trim(); + } + + public void setThrottlingTiers(String tier) { + throttlingTiers.add(tier); + } + + public String getThrottlingTiersAsString() { + StringBuilder stringBuilder = new StringBuilder(); + for (String tier : throttlingTiers) { + if (tier.contains(PolicyConstants.THROTTLING_TIER_CONTENT_AWARE_SEPERATOR)) { + stringBuilder.append(tier.substring(0, + tier.indexOf(PolicyConstants.THROTTLING_TIER_CONTENT_AWARE_SEPERATOR)).trim()).append(" "); + } else { + stringBuilder.append(tier.trim()).append(" "); + } + } + return stringBuilder.toString().trim(); + } + + public boolean checkContentAwareFromThrottlingTiers() { + // use the content aware property appended to throttling tiers + if (!throttlingTiers.isEmpty()) { + String throttlingTierWithContentAware = throttlingTiers.get(0); + if (throttlingTierWithContentAware != null && + throttlingTierWithContentAware.contains(PolicyConstants.THROTTLING_TIER_CONTENT_AWARE_SEPERATOR)) { + String[] splitThrottlingTiers = + throttlingTierWithContentAware.split(PolicyConstants.THROTTLING_TIER_CONTENT_AWARE_SEPERATOR); + return Boolean.valueOf(splitThrottlingTiers[splitThrottlingTiers.length - 1]); + } + } + return false; + } + + public org.wso2.carbon.apimgt.api.model.Scope getScope() { + return scope; + } + public List getScopes() { + return scopes; + } + + public void setScope(org.wso2.carbon.apimgt.api.model.Scope scope) { + this.scope = scope; + } + + public void setScopes(org.wso2.carbon.apimgt.api.model.Scope scope){ + this.scopes.add(scope); + } + + public String getResourceMap(){ + Map verbs = new LinkedHashMap(); + int i = 0; + for (String method : httpVerbs) { + Map verb = new LinkedHashMap(); + verb.put("auth_type",authTypes.get(i)); + verb.put("throttling_tier",throttlingTiers.get(i)); + //Following parameter is not required as it not need to reflect UI level. If need please enable it. + // /verb.put("throttling_conditions", throttlingConditions.get(i)); + try{ + org.wso2.carbon.apimgt.api.model.Scope tmpScope = scopes.get(i); + if(tmpScope != null){ + verb.put("scope",tmpScope.getKey()); + } + }catch(IndexOutOfBoundsException e){ + //todo need to rewrite to prevent this type of exceptions + } + verbs.put(method,verb); + i++; + } + //todo this is a hack to make key validation service stub from braking need to rewrite. + return JSONValue.toJSONString(verbs); + } + + public String getApplicableLevel() { + return applicableLevel; + } + + public void setApplicableLevel(String applicableLevel) { + this.applicableLevel = applicableLevel; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + URITemplate that = (URITemplate) o; + + if (!uriTemplate.equals(that.uriTemplate)) { + return false; + } + if (resourceURI != null ? !resourceURI.equals(that.resourceURI) : that.resourceURI != null) { + return false; + } + if (resourceSandboxURI != null ? !resourceSandboxURI.equals(that.resourceSandboxURI) : that + .resourceSandboxURI != null) { + return false; + } + if (!httpVerb.equals(that.httpVerb)) { + return false; + } + if (!authType.equals(that.authType)) { + return false; + } + if (!httpVerbs.equals(that.httpVerbs)) { + return false; + } + if (!authTypes.equals(that.authTypes)) { + return false; + } + if (throttlingConditions != null ? !throttlingConditions.equals(that.throttlingConditions) : that + .throttlingConditions != null) { + return false; + } + if (applicableLevel != null ? !applicableLevel.equals(that.applicableLevel) : that.applicableLevel != null) { + return false; + } + if (!throttlingTier.equals(that.throttlingTier)) { + return false; + } + if (!throttlingTiers.equals(that.throttlingTiers)) { + return false; + } + if (scope != null ? !scope.equals(that.scope) : that.scope != null) { + return false; + } + if (mediationScript != null ? !mediationScript.equals(that.mediationScript) : that.mediationScript != null) { + return false; + } + if (scopes != null ? !scopes.equals(that.scopes) : that.scopes != null) { + return false; + } + if (mediationScripts != null ? !mediationScripts.equals(that.mediationScripts) : that.mediationScripts != + null) { + return false; + } + // Probably incorrect - comparing Object[] arrays with Arrays.equals + return Arrays.equals(conditionGroups, that.conditionGroups); + } + + @Override + public int hashCode() { + int result = uriTemplate.hashCode(); + result = 31 * result + (resourceURI != null ? resourceURI.hashCode() : 0); + result = 31 * result + (resourceSandboxURI != null ? resourceSandboxURI.hashCode() : 0); + result = 31 * result + (httpVerb != null ? httpVerb.hashCode() : 0); + result = 31 * result + (authType != null ? authType.hashCode() : 0); + result = 31 * result + (httpVerbs != null ? httpVerbs.hashCode() : 0); + result = 31 * result + (authTypes != null ? authTypes.hashCode() : 0); + result = 31 * result + (throttlingConditions != null ? throttlingConditions.hashCode() : 0); + result = 31 * result + (applicableLevel != null ? applicableLevel.hashCode() : 0); + result = 31 * result + (throttlingTier != null ? throttlingTier.hashCode() : 0); + result = 31 * result + (throttlingTiers != null ? throttlingTiers.hashCode() : 0); + result = 31 * result + (scope != null ? scope.hashCode() : 0); + result = 31 * result + (mediationScript != null ? mediationScript.hashCode() : 0); + result = 31 * result + (scopes != null ? scopes.hashCode() : 0); + result = 31 * result + (mediationScripts != null ? mediationScripts.hashCode() : 0); + result = 31 * result + Arrays.hashCode(conditionGroups); + return result; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public List retrieveAllScopes() { + return this.scopes; + } + + public void addAllScopes(List scopes) { + + this.scopes = scopes; + } + + public Set retrieveUsedByProducts() { + return usedByProducts; + } + + public void addUsedByProduct(APIProductIdentifier usedByProduct) { + usedByProducts.add(usedByProduct); + } + + public void setAmznResourceName(String amznResourceName) { + this.amznResourceName = amznResourceName; + } + + public String getAmznResourceName() { + return amznResourceName; + } + + public void setAmznResourceTimeout(int amznResourceTimeout) { + this.amznResourceTimeout = amznResourceTimeout; + } + + public int getAmznResourceTimeout() { + return amznResourceTimeout; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/ScopeUtils.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/ScopeUtils.java index e8f602f992..58cff08553 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/ScopeUtils.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/ScopeUtils.java @@ -18,6 +18,9 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.util; +import java.util.HashSet; +import java.util.Set; + /** * This class represents the scope data. */ @@ -53,7 +56,7 @@ public class ScopeUtils { } public void setRoles(String roles) { - this.roles = roles; + this.roles = removeDuplicatesFromRoleString(roles); } public String getDescription() { @@ -75,4 +78,13 @@ public class ScopeUtils { "}"; return jsonString; } + + private static String removeDuplicatesFromRoleString(String roleString) { + String[] roles = roleString.split(","); + Set roleSet = new HashSet<>(); + for(String role : roles) { + roleSet.add(role.trim()); + } + return String.join(",", roleSet); + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml index b9b4567912..02f206b74a 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml @@ -21,7 +21,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT 4.0.0 diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml index ab79320b39..8b1385eced 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml @@ -21,7 +21,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml index 615f07c01e..2595950b9d 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml @@ -133,6 +133,10 @@ org.json.wso2 json + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.device.mgt.core + @@ -199,7 +203,25 @@ org.wso2.carbon.user.api, org.wso2.carbon.user.core.service;version="[4.8,5)", org.wso2.carbon.user.core.tenant;version="[4.8,5)", - org.wso2.carbon.utils;version="[4.8,5)" + org.wso2.carbon.utils;version="[4.8,5)", + io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.listener, + io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.util, + io.entgra.device.mgt.core.device.mgt.common.exceptions, + io.entgra.device.mgt.core.device.mgt.common.metadata.mgt, + io.entgra.device.mgt.core.device.mgt.core.config, + io.entgra.device.mgt.core.device.mgt.core.config.permission, + org.wso2.carbon.base;version="1.0", + org.wso2.carbon;version="4.6", + org.wso2.carbon.core;version="4.6", + org.wso2.carbon.core.util;version="4.6", + org.wso2.carbon.registry.core.service;version="1.0", + org.wso2.carbon.user.api;version="1.0", + org.wso2.carbon.user.core.service;version="4.6", + org.wso2.carbon.user.core.tenant;version="4.6", + org.wso2.carbon.utils;version="4.6", + org.wso2.carbon.utils.multitenancy;version="4.6", + org.apache.commons.lang, + org.json jsr311-api;scope=compile|runtime;inline=false diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherService.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherService.java index 5edf16d076..eec6cfcab7 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherService.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherService.java @@ -35,4 +35,22 @@ public interface APIPublisherService { void publishAPI(APIConfig api) throws APIManagerPublisherException; void updateScopeRoleMapping() throws APIManagerPublisherException; + + /** + * Add default scopes defined in the cdm-config.xml + */ + void addDefaultScopesIfNotExist(); + + /** + * If the permissions are in the permission list, identify the relevant scopes of the supplied permission list + * and put the role there; if the permissions are in the removedPermission list, update the relevant scopes by + * deleting the role from those scopes. + * + * @param roleName Role Name + * @param permissions List of adding permissions + * @param removedPermissions List of removing permissions + * @throws APIManagerPublisherException If error occurred while updating the scope role mapping + */ + void updateScopeRoleMapping(String roleName, String[] permissions, String[] removedPermissions) throws APIManagerPublisherException; + } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java index c9921d52b0..6b0ad92758 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -24,6 +24,12 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServi import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Scope; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Mediation; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevision; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevisionDeployment; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.CORSConfiguration; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; @@ -32,19 +38,30 @@ import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherC import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope; import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiUriTemplate; import io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; +import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermission; +import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermissions; +import io.entgra.device.mgt.core.device.mgt.core.config.permission.ScopeMapping; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONObject; +import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIProvider; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.*; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIManagerFactory; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.user.api.AuthorizationManager; +import org.wso2.carbon.user.api.Permission; import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.Tenant; import org.wso2.carbon.user.core.tenant.TenantSearchResult; @@ -75,6 +92,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { public static final String SUBSCRIPTION_TO_CURRENT_TENANT = "CURRENT_TENANT"; public static final String API_GLOBAL_VISIBILITY = "PUBLIC"; public static final String API_PRIVATE_VISIBILITY = "PRIVATE"; + private static final String ADMIN_ROLE_KEY = ",admin"; private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class); @@ -145,12 +163,13 @@ public class APIPublisherServiceImpl implements APIPublisherService { for (int i = 0; i < apiList.length(); i++) { JSONObject apiObj = apiList.getJSONObject(i); if (apiObj.getString("name").equals(apiIdentifier.getApiName().replace(Constants.SPACE, - Constants.EMPTY_STRING))){ + Constants.EMPTY_STRING))) { apiFound = true; apiIdentifier.setUuid(apiObj.getString("id")); break; } } + String apiUuid = apiIdentifier.getUUID(); if (!apiFound) { // add new scopes as shared scopes for (ApiScope apiScope : apiConfig.getScopes()) { @@ -160,15 +179,16 @@ public class APIPublisherServiceImpl implements APIPublisherService { scope.setName(apiScope.getName()); scope.setDescription(apiScope.getDescription()); scope.setKey(apiScope.getKey()); - scope.setRoles(apiScope.getRoles()); + scope.setRoles(apiScope.getRoles() + ADMIN_ROLE_KEY); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } } APIInfo api = getAPI(apiConfig, true); JSONObject createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api); + apiUuid = createdAPI.getString("id"); if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, - createdAPI.getString("id"), apiConfig.getAsyncApiDefinition()); + apiUuid, apiConfig.getAsyncApiDefinition()); } if (CREATED_STATUS.equals(createdAPI.getString("lifeCycleStatus"))) { // if endpoint type "dynamic" and then add in sequence @@ -179,13 +199,13 @@ public class APIPublisherServiceImpl implements APIPublisherService { mediation.setType("in"); mediation.setGlobal(false); publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, - accessTokenInfo, createdAPI.getString("id"), mediation); + accessTokenInfo, apiUuid, mediation); } publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo, - createdAPI.getString("id"), PUBLISH_ACTION); + apiUuid, PUBLISH_ACTION); APIRevision apiRevision = new APIRevision(); - apiRevision.setApiUUID(createdAPI.getString("id")); + apiRevision.setApiUUID(apiUuid); apiRevision.setDescription("Initial Revision"); String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, accessTokenInfo, apiRevision).getString("id"); @@ -198,7 +218,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { List apiRevisionDeploymentList = new ArrayList<>(); apiRevisionDeploymentList.add(apiRevisionDeployment); publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, - createdAPI.getString("id"), apiRevisionId, apiRevisionDeploymentList); + apiUuid, apiRevisionId, apiRevisionDeploymentList); } } else { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { @@ -234,7 +254,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { scope.setName(apiScope.getName()); scope.setDescription(apiScope.getDescription()); scope.setKey(apiScope.getKey()); - scope.setRoles(apiScope.getRoles()); + scope.setRoles(apiScope.getRoles() + ADMIN_ROLE_KEY); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } @@ -243,7 +263,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { // Get existing API JSONObject existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, - apiIdentifier); + apiUuid); if (scopesToMoveAsSharedScopes.size() > 0) { // update API to remove local scopes APIInfo api = getAPI(apiConfig, false); @@ -255,20 +275,20 @@ public class APIPublisherServiceImpl implements APIPublisherService { scope.setName(apiScope.getName()); scope.setDescription(apiScope.getDescription()); scope.setKey(apiScope.getKey()); - scope.setRoles(apiScope.getRoles()); + scope.setRoles(apiScope.getRoles() + ADMIN_ROLE_KEY); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } } - existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiIdentifier); + existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiUuid); APIInfo api = getAPI(apiConfig, true); api.setLastUpdatedTime(existingAPI.getString("lifeCycleStatus")); - api.setId(existingAPI.getString("id")); + api.setId(apiUuid); publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, - existingAPI.getString("id"), apiConfig.getAsyncApiDefinition()); + apiUuid, apiConfig.getAsyncApiDefinition()); } // if endpoint type "dynamic" and then add /update in sequence @@ -279,48 +299,55 @@ public class APIPublisherServiceImpl implements APIPublisherService { mediation.setType("in"); mediation.setGlobal(false); - List mediationList = (List) publisherRESTAPIServices + JSONArray mediationList = (JSONArray) publisherRESTAPIServices .getAllApiSpecificMediationPolicies(apiApplicationKey, accessTokenInfo, - apiIdentifier).get("list"); + apiUuid).get("list"); boolean isMediationPolicyFound = false; - for (Mediation m : mediationList) { - if (apiConfig.getInSequenceName().equals(m.getName())) { - m.setConfig(apiConfig.getInSequenceConfig()); - publisherRESTAPIServices. - updateApiSpecificMediationPolicyContent(apiApplicationKey, - accessTokenInfo, existingAPI.getString("id"), m); + for (int i = 0; i < mediationList.length(); i++) { + JSONObject mediationObj = mediationList.getJSONObject(i); + if (apiConfig.getInSequenceName().equals(mediationObj.getString("name"))) { + mediation.setUuid(mediationObj.getString("id")); + publisherRESTAPIServices.deleteApiSpecificMediationPolicy(apiApplicationKey, + accessTokenInfo, apiUuid, mediation); + publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, + accessTokenInfo, apiUuid, mediation); isMediationPolicyFound = true; break; } } if (!isMediationPolicyFound) { publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, - accessTokenInfo, existingAPI.getString("id"), mediation); + accessTokenInfo, apiUuid, mediation); } } - // This will retrieve the deployed revision - JSONArray revisionDeploymentList = (JSONArray) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, - accessTokenInfo, existingAPI.getString("id"), true).get("list"); - // This will retrieve the un deployed revision list - JSONArray undeployedRevisionList = (JSONArray) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, - accessTokenInfo, existingAPI.getString("id"), false).get("list"); int apiRevisionCount = (int) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, - accessTokenInfo, existingAPI.getString("id"), null).get("count"); - + accessTokenInfo, apiUuid, null).get("count"); if (apiRevisionCount >= 5) { - JSONObject latestRevisionDeployment = revisionDeploymentList.getJSONObject(0); - JSONObject earliestUndeployRevision = undeployedRevisionList.getJSONObject(0); - publisherRESTAPIServices.undeployAPIRevisionDeployment(apiApplicationKey, - accessTokenInfo, latestRevisionDeployment, existingAPI.getString("id")); - publisherRESTAPIServices.deleteAPIRevision(apiApplicationKey, accessTokenInfo, - earliestUndeployRevision, existingAPI.getString("id")); + // This will retrieve the deployed revision + JSONArray revisionDeploymentList = (JSONArray) publisherRESTAPIServices.getAPIRevisions( + apiApplicationKey, accessTokenInfo, apiUuid, + true).get("list"); + if (revisionDeploymentList.length() > 0) { + JSONObject latestRevisionDeployment = revisionDeploymentList.getJSONObject(0); + publisherRESTAPIServices.undeployAPIRevisionDeployment(apiApplicationKey, + accessTokenInfo, latestRevisionDeployment, apiUuid); + } + // This will retrieve the un deployed revision list + JSONArray undeployedRevisionList = (JSONArray) publisherRESTAPIServices.getAPIRevisions( + apiApplicationKey, accessTokenInfo, apiUuid, + false).get("list"); + if (undeployedRevisionList.length() > 0) { + JSONObject earliestUndeployRevision = undeployedRevisionList.getJSONObject(0); + publisherRESTAPIServices.deleteAPIRevision(apiApplicationKey, accessTokenInfo, + earliestUndeployRevision, apiUuid); + } } // create new revision APIRevision apiRevision = new APIRevision(); - apiRevision.setApiUUID(existingAPI.getString("id")); + apiRevision.setApiUUID(apiUuid); apiRevision.setDescription("Updated Revision"); String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, accessTokenInfo, apiRevision).getString("id"); @@ -334,17 +361,15 @@ public class APIPublisherServiceImpl implements APIPublisherService { apiRevisionDeploymentList.add(apiRevisionDeployment); publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, - existingAPI.getString("id"), apiRevisionId, apiRevisionDeploymentList); + apiUuid, apiRevisionId, apiRevisionDeploymentList); if (CREATED_STATUS.equals(existingAPI.getString("lifeCycleStatus"))) { - publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey,accessTokenInfo, - existingAPI.getString("id"), PUBLISH_ACTION); + publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo, + apiUuid, PUBLISH_ACTION); } } } - if (apiConfig.getApiDocumentationSourceFile() != null) { - APIInfo api = getAPI(apiConfig, true); - + if (apiUuid != null && apiConfig.getApiDocumentationSourceFile() != null) { String fileName = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "api-docs" + File.separator + @@ -362,7 +387,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { br.close(); String docContent = stringBuilder.toString(); - Documentation apiDocumentation = new Documentation(DocumentationType.HOWTO, apiConfig.getApiDocumentationName()); + Documentation apiDocumentation = new Documentation(Documentation.DocumentationType.HOWTO, apiConfig.getApiDocumentationName()); apiDocumentation.setVisibility(Documentation.DocumentVisibility.API_LEVEL); apiDocumentation.setSourceType(Documentation.DocumentSourceType.MARKDOWN); apiDocumentation.setCreatedDate(new Date()); @@ -371,25 +396,27 @@ public class APIPublisherServiceImpl implements APIPublisherService { apiDocumentation.setOtherTypeName(null); JSONArray documentList = (JSONArray) publisherRESTAPIServices.getDocumentations(apiApplicationKey, - accessTokenInfo, api.getId()).get("list"); + accessTokenInfo, apiUuid).get("list"); if (documentList.length() > 0) { for (int i = 0; i < documentList.length(); i++) { JSONObject existingDoc = documentList.getJSONObject(i); if (existingDoc.getString("name").equals(apiConfig.getApiDocumentationName()) - && existingDoc.getString("type").equals(DocumentationType.HOWTO)) { + && existingDoc.getString("type").equals(Documentation.DocumentationType.HOWTO.name())) { publisherRESTAPIServices.deleteDocumentations(apiApplicationKey, accessTokenInfo, - api.getId(), existingDoc.getString("documentId")); + apiUuid, existingDoc.getString("documentId")); } } } else { log.info("There is no any existing api documentation."); } - Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiApplicationKey, accessTokenInfo, - api.getId(), apiDocumentation); - publisherRESTAPIServices.addDocumentationContent(apiApplicationKey, accessTokenInfo, api, - createdDoc.getId(), docContent); + io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiApplicationKey, accessTokenInfo, + apiUuid, apiDocumentation); + + publisherRESTAPIServices.addDocumentationContent(apiApplicationKey, accessTokenInfo, apiUuid, + createdDoc.getDocumentId(), docContent); + } } catch (APIManagementException | IOException | APIServicesException | BadRequestException | UnexpectedResponseException e) { @@ -408,6 +435,35 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } + public void addDefaultScopesIfNotExist() { + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); + DefaultPermissions defaultPermissions = deviceManagementConfig.getDefaultPermissions(); + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + try { + APIApplicationKey apiApplicationKey = + apiApplicationServices.createAndRetrieveApplicationCredentials(); + AccessTokenInfo accessTokenInfo = + apiApplicationServices.generateAccessTokenFromRegisteredApplication( + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + + PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl(); + + Scope scope = new Scope(); + for (DefaultPermission defaultPermission: defaultPermissions.getDefaultPermissions()) { + //todo check whether scope is available or not + ScopeMapping scopeMapping = defaultPermission.getScopeMapping(); + scope.setName(scopeMapping.getName()); + scope.setDescription(scopeMapping.getName()); + scope.setKey(scopeMapping.getKey()); + scope.setRoles(scopeMapping.getDefaultRoles() + ADMIN_ROLE_KEY); + publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + } + } catch (BadRequestException | UnexpectedResponseException | APIServicesException e) { + log.error("Error occurred while adding default scopes"); + } + } + + @Override public void updateScopeRoleMapping() throws APIManagerPublisherException { @@ -428,6 +484,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { log.error(errorMsg, e); throw new APIManagerPublisherException(e); } + UserStoreManager userStoreManager; try { for (String tenantDomain : tenants) { @@ -440,20 +497,40 @@ public class APIPublisherServiceImpl implements APIPublisherService { String fileName = CarbonUtils.getCarbonConfigDirPath() + File.separator + "etc" + File.separator + tenantDomain + ".csv"; + try { + userStoreManager = APIPublisherDataHolder.getInstance().getUserStoreManager(); + } catch (UserStoreException e) { + log.error("Unable to retrieve user store manager for tenant: " + tenantDomain); + return; + } if (Files.exists(Paths.get(fileName))) { BufferedReader br = new BufferedReader(new FileReader(fileName)); int lineNumber = 0; Map roles = new HashMap<>(); - String line = ""; + Map> rolePermissions = new HashMap<>(); + String line; String splitBy = ","; - while ((line = br.readLine()) != null) //returns a Boolean value - { + while ((line = br.readLine()) != null) { //returns a Boolean value lineNumber++; String[] scopeMapping = line.split(splitBy); // use comma as separator + String role; if (lineNumber == 1) { // skip titles - for (int i = 0; i < scopeMapping.length; i++) { - if (i > 3) { - roles.put(i, scopeMapping[i]); // add roles to the map + for (int i = 4; i < scopeMapping.length; i++) { + role = scopeMapping[i]; + roles.put(i, role); // add roles to the map + if (!"admin".equals(role)) { + try { + if (!userStoreManager.isExistingRole(role)) { + try { + addRole(role); + } catch (UserStoreException e) { + log.error("Error occurred when adding new role: " + role, e); + } + } + } catch (UserStoreException e) { + log.error("Error occurred when checking the existence of role: " + role, e); + } + rolePermissions.put(role, new ArrayList<>()); } } continue; @@ -468,11 +545,15 @@ public class APIPublisherServiceImpl implements APIPublisherService { scopeMapping[2] != null ? StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY); // scope.setPermissions( // scopeMapping[3] != null ? StringUtils.trim(scopeMapping[3]) : StringUtils.EMPTY); + String permission = scopeMapping[3] != null ? StringUtils.trim(scopeMapping[3]) : StringUtils.EMPTY; String roleString = ""; for (int i = 4; i < scopeMapping.length; i++) { if (scopeMapping[i] != null && StringUtils.trim(scopeMapping[i]).equals("Yes")) { roleString = roleString + "," + roles.get(i); + if (rolePermissions.containsKey(roles.get(i)) && StringUtils.isNotEmpty(permission)) { + rolePermissions.get(roles.get(i)).add(permission); + } } } if (roleString.length() > 1) { @@ -487,16 +568,28 @@ public class APIPublisherServiceImpl implements APIPublisherService { if (scopeObj.getString("name").equals(scopeMapping[2] != null ? StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY)) { scope.setId(scopeObj.getString("id")); + +// Including already existing roles + JSONArray existingRolesArray = (JSONArray) scopeObj.get("bindings"); + for (int j = 0; j < existingRolesArray.length(); j++) { + roleString = roleString + "," + existingRolesArray.get(j); + } } } + scope.setRoles(roleString); if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getKey())) { publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); } else { // todo: come to this level means, that scope is removed from API, but haven't removed from the scope-role-permission-mappings list - if (log.isDebugEnabled()) { - log.debug(scope.getKey() + " not available as shared scope"); - } + log.warn(scope.getKey() + " not available as shared scope"); + } + } + for (String role : rolePermissions.keySet()) { + try { + updatePermissions(role, rolePermissions.get(role)); + } catch (UserStoreException e) { + log.error("Error occurred when adding permissions to role: " + role, e); } } } @@ -509,8 +602,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } - } - catch (APIServicesException e) { + } catch (APIServicesException e) { String errorMsg = "Error while processing Publisher REST API response"; log.error(errorMsg, e); throw new APIManagerPublisherException(e); @@ -522,11 +614,150 @@ public class APIPublisherServiceImpl implements APIPublisherService { String errorMsg = "Unexpected response from the server"; log.error(errorMsg, e); throw new APIManagerPublisherException(e); - }finally { + } finally { PrivilegedCarbonContext.endTenantFlow(); } } + @Override + public void updateScopeRoleMapping(String roleName, String[] permissions, String[] removedPermissions) throws APIManagerPublisherException { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + APIApplicationKey apiApplicationKey; + AccessTokenInfo accessTokenInfo; + try { + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); + accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + } catch (APIServicesException e) { + String errorMsg = "Error occurred while generating the API application"; + log.error(errorMsg, e); + throw new APIManagerPublisherException(e); + } + + try { + PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl(); + JSONObject scopeObject = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); + Map permScopeMap = APIPublisherDataHolder.getInstance().getPermScopeMapping(); + if (permissions.length != 0) { + updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeObject, permissions, permScopeMap, false); + } + if (removedPermissions.length != 0) { + updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeObject, removedPermissions, permScopeMap, true); + } + + try { + updatePermissions(roleName, Arrays.asList(permissions)); + } catch (UserStoreException e) { + String errorMsg = "Error occurred when adding permissions to role: " + roleName; + log.error(errorMsg, e); + throw new APIManagerPublisherException(errorMsg, e); + } + } catch (APIServicesException e) { + String errorMsg = "Error while processing Publisher REST API response"; + log.error(errorMsg, e); + throw new APIManagerPublisherException(errorMsg, e); + } catch (BadRequestException e) { + String errorMsg = "Error while calling Publisher REST APIs"; + log.error(errorMsg, e); + throw new APIManagerPublisherException(errorMsg, e); + } catch (UnexpectedResponseException e) { + String errorMsg = "Unexpected response from the server"; + log.error(errorMsg, e); + throw new APIManagerPublisherException(errorMsg, e); + } + } + + /** + * Update Scopes + * + * @param roleName Role Name + * @param publisherRESTAPIServices {@link PublisherRESTAPIServices} + * @param apiApplicationKey {@link APIApplicationKey} + * @param accessTokenInfo {@link AccessTokenInfo} + * @param scopeObject scope object returning from APIM + * @param permissions List of permissions + * @param permScopeMap Permission Scope map + * @param removingPermissions if list of permissions has to be removed from the role send true, otherwise sends false. + * @throws APIManagerPublisherException If the method receives invalid permission to update. + */ + private void updateScopes (String roleName, PublisherRESTAPIServices publisherRESTAPIServices, + APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + JSONObject scopeObject, String[] permissions, Map permScopeMap, boolean removingPermissions ) + throws APIManagerPublisherException { + for (String permission : permissions) { + String scopeValue = permScopeMap.get(permission); + if (scopeValue == null) { + String msg = "Found invalid permission: " + permission + ". Hence aborting the scope role " + + "mapping process"; + log.error(msg); + throw new APIManagerPublisherException(msg); + } + + JSONArray scopeList = (JSONArray) scopeObject.get("list"); + for (int i = 0; i < scopeList.length(); i++) { + JSONObject scopeObj = scopeList.getJSONObject(i); + if (scopeObj.getString("name").equals(scopeValue)) { + Scope scope = new Scope(); + scope.setName(scopeObj.getString("name")); + scope.setKey(scopeObj.getString("name")); + scope.setDescription(scopeObj.getString("description")); + scope.setId(scopeObj.getString("id")); + + // Including already existing roles + JSONArray existingRolesArray = (JSONArray) scopeObj.get("bindings"); + List existingRoleList = new ArrayList(); + + for (int j = 0; j < existingRolesArray.length(); j++) { + existingRoleList.add((String) existingRolesArray.get(j)); + } + + if (removingPermissions) { + existingRoleList.remove(roleName); + } else { + if (!existingRoleList.contains(roleName)) { + existingRoleList.add(roleName); + } + } + scope.setRoles(String.join(",", existingRoleList)); + + try { + if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getKey())) { + publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); + } else { + // todo: come to this level means, that scope is removed from API, but haven't removed from the scope-role-permission-mappings list + log.warn(scope.getKey() + " not available as shared scope"); + } + } catch (APIServicesException | BadRequestException | UnexpectedResponseException e) { + log.error("Error occurred while updating role scope mapping via APIM REST endpoint.", e); + } + break; + } + } + } + } + + private void updatePermissions(String role, List permissions) throws UserStoreException { + AuthorizationManager authorizationManager = APIPublisherDataHolder.getInstance().getUserRealm() + .getAuthorizationManager(); + if (log.isDebugEnabled()) { + log.debug("Updating the role '" + role + "'"); + } + if (permissions != null && !permissions.isEmpty()) { + authorizationManager.clearRoleAuthorization(role); + for (String permission : permissions) { + authorizationManager.authorizeRole(role, permission, CarbonConstants.UI_PERMISSION_ACTION); + } + } + } + + private void addRole(String role) throws UserStoreException { + UserStoreManager userStoreManager = APIPublisherDataHolder.getInstance().getUserStoreManager(); + if (log.isDebugEnabled()) { + log.debug("Persisting the role " + role + " in the underlying user store"); + } + userStoreManager.addRole(role, new String[]{"admin"}, new Permission[0]); + } + private APIInfo getAPI(APIConfig config, boolean includeScopes) { APIInfo apiInfo = new APIInfo(); @@ -558,46 +789,50 @@ public class APIPublisherServiceImpl implements APIPublisherService { } apiInfo.setPolicies(availableTiers); - if (config.getEndpointType() == null) { - List operations = new ArrayList(); - List scopeSet = new ArrayList(); - Iterator iterator; - for (iterator = config.getUriTemplates().iterator(); iterator.hasNext(); ) { - ApiUriTemplate apiUriTemplate = iterator.next(); - JSONObject operation = new JSONObject(); - operation.put("target", apiUriTemplate.getUriTemplate()); - operation.put("verb", apiUriTemplate.getHttpVerb()); - operation.put("authType", apiUriTemplate.getAuthType()); - operation.put("throttlingPolicy", UNLIMITED_TIER); - if (includeScopes) { - if (apiUriTemplate.getScope() != null) { - String scopeString = "{\n" + - " \"scope\": {\n" + - " \"id\": null,\n" + - " \"name\": \"" + apiUriTemplate.getScope().getKey() + "\",\n" + - " \"displayName\": \"" + apiUriTemplate.getScope().getName() + "\",\n" + - " \"description\": \"" + apiUriTemplate.getScope().getDescription() + "\",\n" + - " \"bindings\": [\n" + - " \"" + apiUriTemplate.getScope().getRoles() + "\"\n" + - " ],\n" + - " \"usageCount\": null\n" + - " },\n" + - " \"shared\": true\n" + - " }"; - JSONObject scope = new JSONObject(scopeString); - scopeSet.add(scope); - - Set scopes = new HashSet<>(); - scopes.add(apiUriTemplate.getScope().getKey()); - operation.put("scopes", scopes); - } - } - operations.add(operation); - } - apiInfo.setScopes(scopeSet); - apiInfo.setOperations(operations); + if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) { + apiInfo.setAsyncApiDefinition(config.getAsyncApiDefinition()); } + //set operations and scopes + List operations = new ArrayList(); + List scopeSet = new ArrayList(); + Iterator iterator; + for (iterator = config.getUriTemplates().iterator(); iterator.hasNext(); ) { + ApiUriTemplate apiUriTemplate = iterator.next(); + JSONObject operation = new JSONObject(); + operation.put("target", apiUriTemplate.getUriTemplate()); + operation.put("verb", apiUriTemplate.getHttpVerb()); + operation.put("authType", apiUriTemplate.getAuthType()); + operation.put("throttlingPolicy", UNLIMITED_TIER); + operation.put("uriMapping", apiUriTemplate.getUriMapping()); + if (includeScopes) { + if (apiUriTemplate.getScope() != null) { + String scopeString = "{\n" + + " \"scope\": {\n" + + " \"id\": null,\n" + + " \"name\": \"" + apiUriTemplate.getScope().getKey() + "\",\n" + + " \"displayName\": \"" + apiUriTemplate.getScope().getName() + "\",\n" + + " \"description\": \"" + apiUriTemplate.getScope().getDescription() + "\",\n" + + " \"bindings\": [\n" + + " \"" + apiUriTemplate.getScope().getRoles() + "\"\n" + + " ],\n" + + " \"usageCount\": null\n" + + " },\n" + + " \"shared\": true\n" + + " }"; + JSONObject scope = new JSONObject(scopeString); + scopeSet.add(scope); + + Set scopes = new HashSet<>(); + scopes.add(apiUriTemplate.getScope().getKey()); + operation.put("scopes", scopes); + } + } + operations.add(operation); + } + apiInfo.setScopes(scopeSet); + apiInfo.setOperations(operations); + if (config.isSharedWithAllTenants()) { apiInfo.setSubscriptionAvailability(SUBSCRIPTION_TO_ALL_TENANTS); apiInfo.setVisibility(API_GLOBAL_VISIBILITY); @@ -626,7 +861,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { if (config.getEndpointType() != null && "dynamic".equals(config.getEndpointType())) { endpointConfig = "{\n" + - " \"endpoint_type\": \"http\",\n" + + " \"endpoint_type\": \"default\",\n" + " \"sandbox_endpoints\": {\n" + " \"url\": \" default \"\n" + " },\n" + @@ -635,13 +870,12 @@ public class APIPublisherServiceImpl implements APIPublisherService { " }\n" + " }"; endPointConfig = new JSONObject(endpointConfig); - //TODO: Will be used in dynamic endpoints -// apiInfo.setInSequence(config.getInSequenceName()); + apiInfo.setInSequence(config.getInSequenceName()); } // if ws endpoint if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) { - endpointConfig = "{\n" + + endpointConfig = "{\n" + " \"endpoint_type\": \"ws\",\n" + " \"sandbox_endpoints\": {\n" + " \"url\": \"" + config.getEndpoint() + "\"\n" + @@ -688,42 +922,18 @@ public class APIPublisherServiceImpl implements APIPublisherService { apiInfo.setServiceInfo(null); return apiInfo; + } - //TODO: Will be used in WS or dynamic endpoints -// if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) { -// api.setAsyncApiDefinition(config.getAsyncApiDefinition()); -// AsyncApiParser asyncApiParser = new AsyncApiParser(); -// try { -// api.setUriTemplates(asyncApiParser.getURITemplates(config.getAsyncApiDefinition(), true)); -// } catch (APIManagementException e) { -// -// } -// api.setWsUriMapping(asyncApiParser.buildWSUriMapping(config.getAsyncApiDefinition())); -// } else { -// api.setSwaggerDefinition(APIPublisherUtil.getSwaggerDefinition(config)); -// -// Set uriTemplates = new HashSet<>(); -// Iterator iterator; -// for (iterator = config.getUriTemplates().iterator(); iterator.hasNext(); ) { -// ApiUriTemplate apiUriTemplate = iterator.next(); -// URITemplate uriTemplate = new URITemplate(); -// uriTemplate.setAuthType(apiUriTemplate.getAuthType()); -// uriTemplate.setHTTPVerb(apiUriTemplate.getHttpVerb()); -// uriTemplate.setResourceURI(apiUriTemplate.getResourceURI()); -// uriTemplate.setUriTemplate(apiUriTemplate.getUriTemplate()); -// if (includeScopes) { -// Scope scope = new Scope(); -// if (apiUriTemplate.getScope() != null) { -// scope.setName(apiUriTemplate.getScope().getName()); -// scope.setDescription(apiUriTemplate.getScope().getDescription()); -// scope.setKey(apiUriTemplate.getScope().getKey()); -// scope.setRoles(apiUriTemplate.getScope().getRoles()); -// uriTemplate.setScopes(scope); -// } -// } -// uriTemplates.add(uriTemplate); -// } -// api.setUriTemplates(uriTemplates); -// } + /** + * This method will construct the permission scope mapping hash map. This will call in each API publish call. + * @param scopes API Scopes + */ + private void constructPemScopeMap(Set scopes) { + APIPublisherDataHolder apiPublisherDataHolder = APIPublisherDataHolder.getInstance(); + Map permScopeMap = apiPublisherDataHolder.getPermScopeMapping(); + for (ApiScope scope : scopes) { + permScopeMap.put(scope.getPermissions(), scope.getKey()); + } + apiPublisherDataHolder.setPermScopeMapping(permScopeMap); } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherStartupHandler.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherStartupHandler.java index 55a1733498..4d8835463e 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherStartupHandler.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherStartupHandler.java @@ -86,6 +86,7 @@ public class APIPublisherStartupHandler implements ServerStartupObserver { try { publisher.updateScopeRoleMapping(); + publisher.addDefaultScopesIfNotExist(); } catch (APIManagerPublisherException e) { log.error("failed to update scope role mapping.", e); } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/exception/APIManagerPublisherException.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/exception/APIManagerPublisherException.java index 47e28aefb9..281fdbbf16 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/exception/APIManagerPublisherException.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/exception/APIManagerPublisherException.java @@ -28,4 +28,12 @@ public class APIManagerPublisherException extends Exception { public APIManagerPublisherException(Throwable cause) { super(cause); } + + public APIManagerPublisherException(String errorMessage) { + super(errorMessage); + } + + public APIManagerPublisherException(String errorMessage, Throwable cause) { + super(errorMessage, cause); + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java index bc7b8af32c..0d67edc7a9 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java @@ -19,11 +19,19 @@ package io.entgra.device.mgt.core.apimgt.webapp.publisher.internal; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIConfig; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.core.service.RegistryService; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.utils.ConfigurationContextService; +import java.util.HashMap; +import java.util.Map; import java.util.Stack; public class APIPublisherDataHolder { @@ -35,6 +43,10 @@ public class APIPublisherDataHolder { private RegistryService registryService; private boolean isServerStarted; private Stack unpublishedApis = new Stack<>(); + private Map permScopeMapping; + + private MetadataManagementService metadataManagementService; + private static APIPublisherDataHolder thisInstance = new APIPublisherDataHolder(); private APIPublisherDataHolder() { @@ -79,6 +91,25 @@ public class APIPublisherDataHolder { realmService.getTenantManager() : null); } + public UserStoreManager getUserStoreManager() throws UserStoreException { + if (realmService == null) { + String msg = "Realm service has not initialized."; + throw new IllegalStateException(msg); + } + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + return realmService.getTenantUserRealm(tenantId).getUserStoreManager(); + } + + public UserRealm getUserRealm() throws UserStoreException { + UserRealm realm; + if (realmService == null) { + throw new IllegalStateException("Realm service not initialized"); + } + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + realm = realmService.getTenantUserRealm(tenantId); + return realm; + } + private void setTenantManager(TenantManager tenantManager) { this.tenantManager = tenantManager; } @@ -114,4 +145,15 @@ public class APIPublisherDataHolder { this.unpublishedApis = unpublishedApis; } + public Map getPermScopeMapping() {return permScopeMapping;} + + public void setPermScopeMapping(Map permScopeMapping) {this.permScopeMapping = permScopeMapping;} + + public MetadataManagementService getMetadataManagementService() { + return metadataManagementService; + } + + public void setMetadataManagementService(MetadataManagementService metadataManagementService) { + this.metadataManagementService = metadataManagementService; + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java index df71dcb231..86a790d957 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java @@ -17,19 +17,22 @@ */ package io.entgra.device.mgt.core.apimgt.webapp.publisher.internal; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherServiceImpl; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherStartupHandler; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherServiceImpl; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherStartupHandler; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; import org.osgi.service.component.annotations.*; import org.wso2.carbon.core.ServerStartupObserver; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.user.core.service.RealmService; +import java.util.HashMap; + @Component( name = "io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherServiceComponent", immediate = true) @@ -52,6 +55,7 @@ public class APIPublisherServiceComponent { /* Registering declarative service instances exposed by DeviceManagementServiceComponent */ this.registerServices(componentContext); + APIPublisherDataHolder.getInstance().setPermScopeMapping(new HashMap<>()); if (log.isDebugEnabled()) { log.debug("Webapp publisher bundle has been successfully initialized"); @@ -116,4 +120,15 @@ public class APIPublisherServiceComponent { APIPublisherDataHolder.getInstance().setRegistryService(null); } + protected void setMetaDataMgtService(MetadataManagementService metadataManagementService) { + if (metadataManagementService != null && log.isDebugEnabled()) { + log.debug("Meta data mgt mgt service initialized"); + } + APIPublisherDataHolder.getInstance().setMetadataManagementService(metadataManagementService); + } + + protected void unsetMetaDataMgtService(MetadataManagementService metadataManagementService) { + APIPublisherDataHolder.getInstance().setMetadataManagementService(null); + } + } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java index da503fc4d7..6e39f0e940 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java @@ -17,6 +17,21 @@ */ package io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.listener; +import com.google.gson.Gson; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; +import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermission; +import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermissions; +import org.apache.catalina.Lifecycle; +import org.apache.catalina.LifecycleEvent; +import org.apache.catalina.LifecycleListener; +import org.apache.catalina.core.StandardContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIConfig; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil; @@ -35,7 +50,9 @@ import org.wso2.carbon.user.api.UserStoreException; import javax.servlet.ServletContext; import java.io.IOException; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Set; @SuppressWarnings("unused") @@ -49,68 +66,123 @@ public class APIPublisherLifecycleListener implements LifecycleListener { @Override public void lifecycleEvent(LifecycleEvent lifecycleEvent) { - if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType()) && WebappPublisherConfig.getInstance() - .isPublished()) { - StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); - ServletContext servletContext = context.getServletContext(); - String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); - boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); + if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType()) ) { + if (WebappPublisherConfig.getInstance() + .isPublished()) { + StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); + ServletContext servletContext = context.getServletContext(); + String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); + boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); - String profile = System.getProperty(PROPERTY_PROFILE); - if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase()) - && isManagedApi) { - try { - AnnotationProcessor annotationProcessor = new AnnotationProcessor(context); - Set annotatedSwaggerAPIClasses = annotationProcessor. - scanStandardContext(io.swagger.annotations.SwaggerDefinition.class.getName()); - List apiDefinitions = annotationProcessor.extractAPIInfo(servletContext, - annotatedSwaggerAPIClasses); - for (APIResourceConfiguration apiDefinition : apiDefinitions) { - APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition); - APIPublisherUtil.setResourceAuthTypes(servletContext,apiConfig); - try { - int tenantId = APIPublisherDataHolder.getInstance().getTenantManager(). - getTenantId(apiConfig.getTenantDomain()); + String profile = System.getProperty(PROPERTY_PROFILE); + if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase()) + && isManagedApi) { + try { + AnnotationProcessor annotationProcessor = new AnnotationProcessor(context); + Set annotatedSwaggerAPIClasses = annotationProcessor. + scanStandardContext(io.swagger.annotations.SwaggerDefinition.class.getName()); + List apiDefinitions = annotationProcessor.extractAPIInfo(servletContext, + annotatedSwaggerAPIClasses); - boolean isTenantActive = APIPublisherDataHolder.getInstance(). - getTenantManager().isTenantActive(tenantId); - if (isTenantActive) { - boolean isServerStarted = APIPublisherDataHolder.getInstance().isServerStarted(); - if (isServerStarted) { - APIPublisherService apiPublisherService = - APIPublisherDataHolder.getInstance().getApiPublisherService(); - if (apiPublisherService == null) { - throw new IllegalStateException( - "API Publisher service is not initialized properly"); - } - apiPublisherService.publishAPI(apiConfig); - } else { - if (log.isDebugEnabled()) { - log.debug("Server has not started yet. Hence adding API '" + - apiConfig.getName() + "' to the queue"); - } - APIPublisherDataHolder.getInstance().getUnpublishedApis().push(apiConfig); - } - } else { - log.error("No tenant [" + apiConfig.getTenantDomain() + "] " + - "found when publishing the Web app"); - } - } catch (Throwable e) { - log.error("Error occurred while publishing API '" + apiConfig.getName() + - "' with the context '" + apiConfig.getContext() + - "' and version '" + apiConfig.getVersion() + "'", e); + APIPublisherDataHolder apiPublisherDataHolder = APIPublisherDataHolder.getInstance(); + MetadataManagementService metadataManagementService = + apiPublisherDataHolder.getMetadataManagementService(); + Metadata metadata = metadataManagementService.retrieveMetadata("perm-scope-mapping"); + if (metadata != null) { + HashMap permScopeMapping = + new Gson().fromJson(metadata.getMetaValue().toString(), HashMap.class); + apiPublisherDataHolder.setPermScopeMapping(permScopeMapping); } + + Map permScopeMap = apiPublisherDataHolder.getPermScopeMapping(); + for (APIResourceConfiguration apiDefinition : apiDefinitions) { + APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition); + for (ApiScope scope : apiConfig.getScopes()) { + permScopeMap.put(scope.getPermissions(), scope.getKey()); + } + APIPublisherUtil.setResourceAuthTypes(servletContext,apiConfig); + try { + int tenantId = APIPublisherDataHolder.getInstance().getTenantManager(). + getTenantId(apiConfig.getTenantDomain()); + + boolean isTenantActive = APIPublisherDataHolder.getInstance(). + getTenantManager().isTenantActive(tenantId); + if (isTenantActive) { + boolean isServerStarted = APIPublisherDataHolder.getInstance().isServerStarted(); + if (isServerStarted) { + APIPublisherService apiPublisherService = + APIPublisherDataHolder.getInstance().getApiPublisherService(); + if (apiPublisherService == null) { + throw new IllegalStateException( + "API Publisher service is not initialized properly"); + } + apiPublisherService.publishAPI(apiConfig); + } else { + if (log.isDebugEnabled()) { + log.debug("Server has not started yet. Hence adding API '" + + apiConfig.getName() + "' to the queue"); + } + APIPublisherDataHolder.getInstance().getUnpublishedApis().push(apiConfig); + } + } else { + log.error("No tenant [" + apiConfig.getTenantDomain() + "] " + + "found when publishing the Web app"); + } + } catch (Throwable e) { + log.error("Error occurred while publishing API '" + apiConfig.getName() + + "' with the context '" + apiConfig.getContext() + + "' and version '" + apiConfig.getVersion() + "'", e); + } + } + + Metadata existingMetaData = metadataManagementService.retrieveMetadata("perm-scope" + + "-mapping"); + if (existingMetaData != null) { + existingMetaData.setMetaValue(new Gson().toJson(permScopeMap)); + metadataManagementService.updateMetadata(existingMetaData); + } else { + Metadata newMetaData = new Metadata(); + newMetaData.setMetaKey("perm-scope-mapping"); + + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); + DefaultPermissions defaultPermissions = deviceManagementConfig.getDefaultPermissions(); + + for (DefaultPermission defaultPermission : defaultPermissions.getDefaultPermissions()) { + permScopeMap.put(defaultPermission.getName(), defaultPermission.getScopeMapping().getKey()); + } + newMetaData.setMetaValue(new Gson().toJson(permScopeMap)); + metadataManagementService.createMetadata(newMetaData); + } + apiPublisherDataHolder.setPermScopeMapping(permScopeMap); + } catch (IOException e) { + log.error("Error encountered while discovering annotated classes", e); + } catch (ClassNotFoundException e) { + log.error("Error while scanning class for annotations", e); + } catch (UserStoreException e) { + log.error("Error while retrieving tenant admin user for the tenant domain" + + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(), e); + } catch (Throwable e) { + // This is done to stop tomcat failure if a webapp failed to publish apis. + log.error("Failed to Publish api from " + servletContext.getContextPath(), e); } - } catch (IOException e) { - log.error("Error encountered while discovering annotated classes", e); - } catch (ClassNotFoundException e) { - log.error("Error while scanning class for annotations", e); - } catch (UserStoreException e) { - log.error("Error while retrieving tenant admin user for the tenant domain" - + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(), e); - } catch (Throwable e) { - // This is done to stop tomcat failure if a webapp failed to publish apis. - log.error("Failed to Publish api from " + servletContext.getContextPath(), e); + } + } else { + APIPublisherDataHolder apiPublisherDataHolder = APIPublisherDataHolder.getInstance(); + MetadataManagementService metadataManagementService = + apiPublisherDataHolder.getMetadataManagementService(); + try { + Metadata existingMetaData = metadataManagementService.retrieveMetadata("perm-scope" + + "-mapping"); + if (existingMetaData != null) { + existingMetaData.setMetaValue(new Gson().toJson(apiPublisherDataHolder.getPermScopeMapping() + )); + metadataManagementService.updateMetadata(existingMetaData); + } else { + log.error("Couldn't find 'perm-scope-mapping' Meta entry while API publishing has been turned" + + " off."); + } + } catch (MetadataManagementException e) { + log.error("Failed to Load Meta-Mgt data.", e); } } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java index 4a085ff715..015eba4802 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java @@ -54,7 +54,7 @@ public class AnnotationProcessor { private static final String PACKAGE_ORG_APACHE = "org.apache"; private static final String PACKAGE_ORG_CODEHAUS = "org.codehaus"; private static final String PACKAGE_ORG_SPRINGFRAMEWORK = "org.springframework"; - public static final String WILD_CARD = "/*"; + public static final String WILD_CARD = "/"; private static final String SWAGGER_ANNOTATIONS_INFO = "info"; private static final String SWAGGER_ANNOTATIONS_TAGS = "tags"; private static final String SWAGGER_ANNOTATIONS_EXTENSIONS = "extensions"; @@ -77,7 +77,7 @@ public class AnnotationProcessor { private static final String ANNOTATIONS_SCOPES = "scopes"; private static final String ANNOTATIONS_SCOPE = "scope"; private static final String DEFAULT_SCOPE_NAME = "default admin scope"; - private static final String DEFAULT_SCOPE_KEY = "perm:admin"; + private static final String DEFAULT_SCOPE_KEY = "dm:admin"; private static final String DEFAULT_SCOPE_PERMISSION = "/permision/device-mgt"; private static final String DEFAULT_SCOPE_ROLE = "admin"; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/utils/TestUtils.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/utils/TestUtils.java index 0161c5cef5..988bd9c5f7 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/utils/TestUtils.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/utils/TestUtils.java @@ -37,7 +37,7 @@ public class TestUtils { template.setResourceURI("https://localhost:9443/api/device-mgt/windows/v1.0/admin/devices/reboot"); template.setUriTemplate(uriTemplate); ApiScope scope = new ApiScope(); - scope.setKey("perm:windows:reboot"); + scope.setKey("win:ops:reboot"); scope.setName("Reboot"); scope.setRoles("/permission/admin/device-mgt/devices/owning-device/operations/windows/reboot"); scope.setDescription("Lock reset on Windows devices"); diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index 48514dd429..e9e07fb3b9 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml index 7925c9e662..74d2f7aecf 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core application-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/DepConfig.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/DepConfig.java new file mode 100644 index 0000000000..244f88fb08 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/DepConfig.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.common; + +public class DepConfig { + + private String agentPackageName; + private String consumerKey; + private String consumerSecret; + private String accessToken; + private String accessSecret; + private String accessTokenExpiry; + private String vppToken; + + public String getAgentPackageName() { + return agentPackageName; + } + + public void setAgentPackageName(String agentPackageName) { + this.agentPackageName = agentPackageName; + } + + public String getConsumerKey() { + return consumerKey; + } + + public void setConsumerKey(String consumerKey) { + this.consumerKey = consumerKey; + } + + public String getConsumerSecret() { + return consumerSecret; + } + + public void setConsumerSecret(String consumerSecret) { + this.consumerSecret = consumerSecret; + } + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public String getVppToken() { + return vppToken; + } + + public void setVppToken(String vppToken) { + this.vppToken = vppToken; + } + + public String getAccessSecret() { + return accessSecret; + } + + public void setAccessSecret(String accessSecret) { + this.accessSecret = accessSecret; + } + + public String getAccessTokenExpiry() { + return accessTokenExpiry; + } + + public void setAccessTokenExpiry(String accessTokenExpiry) { + this.accessTokenExpiry = accessTokenExpiry; + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ItuneAppDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ItuneAppDTO.java new file mode 100644 index 0000000000..a76a9ec12b --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ItuneAppDTO.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.common.dto; + +public class ItuneAppDTO { + int id; + String packageName; + String version; + String description; + String title; + String paymentMethod; + String iconURL; + String category; + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getIconURL() { + return iconURL; + } + + public void setIconURL(String iconURL) { + this.iconURL = iconURL; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getPackageName() { + return packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getPaymentMethod() { + return paymentMethod; + } + + public void setPaymentMethod(String paymentMethod) { + this.paymentMethod = paymentMethod; + } + +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ProxyResponse.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ProxyResponse.java new file mode 100644 index 0000000000..80d5f94df1 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ProxyResponse.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.common.dto; + +public class ProxyResponse { + + private int code; + private String data; + private String executorResponse; + + public int getCode() { return code; } + + public void setCode(int code) { this.code = code; } + + public String getData() { return data; } + + public void setData(String data) { this.data = data; } + + public String getExecutorResponse() { return executorResponse; } + + public void setExecutorResponse(String executorResponse) { this.executorResponse = executorResponse; } +} \ No newline at end of file diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppAssetDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppAssetDTO.java new file mode 100644 index 0000000000..1ce0d3c3cf --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppAssetDTO.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.common.dto; + +public class VppAssetDTO extends VppItuneAssetDTO { + int id; + int appId; + int tenantId; + String createdTime; + String lastUpdatedTime; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getAppId() { + return appId; + } + + public void setAppId(int appId) { + this.appId = appId; + } + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public String getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(String createdTime) { + this.createdTime = createdTime; + } + + public String getLastUpdatedTime() { + return lastUpdatedTime; + } + + public void setLastUpdatedTime(String lastUpdatedTime) { + this.lastUpdatedTime = lastUpdatedTime; + } + +} \ No newline at end of file diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppAssociationDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppAssociationDTO.java new file mode 100644 index 0000000000..b2178febfa --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppAssociationDTO.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.common.dto; + +public class VppAssociationDTO { + int id; + String adamId; + String clientUserId; + String pricingParam; + String associationType; + + int assetId; + int clientId; + int tenantId; + String createdTime; + String lastUpdatedTime; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getAdamId() { + return adamId; + } + + public void setAdamId(String adamId) { + this.adamId = adamId; + } + + public String getClientUserId() { + return clientUserId; + } + + public void setClientUserId(String clientUserId) { + this.clientUserId = clientUserId; + } + + public String getPricingParam() { + return pricingParam; + } + + public void setPricingParam(String pricingParam) { + this.pricingParam = pricingParam; + } + + public String getAssociationType() { + return associationType; + } + + public void setAssociationType(String associationType) { + this.associationType = associationType; + } + + public int getAssetId() { + return assetId; + } + + public void setAssetId(int assetId) { + this.assetId = assetId; + } + + public int getClientId() { + return clientId; + } + + public void setClientId(int clientId) { + this.clientId = clientId; + } + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public String getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(String createdTime) { + this.createdTime = createdTime; + } + + public String getLastUpdatedTime() { + return lastUpdatedTime; + } + + public void setLastUpdatedTime(String lastUpdatedTime) { + this.lastUpdatedTime = lastUpdatedTime; + } + +} \ No newline at end of file diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppItuneAssetDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppItuneAssetDTO.java new file mode 100644 index 0000000000..71e9429c68 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppItuneAssetDTO.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2018 - 2023, 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 String LicenseString ); 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 + * String AS ISString 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 io.entgra.device.mgt.core.application.mgt.common.dto; + +import java.util.List; + +public class VppItuneAssetDTO { + + + String adamId; + String assignedCount; + String availableCount; + String deviceAssignable; + String pricingParam; + String productType; + String retiredCount; + String revocable; + + List supportedPlatforms; + + public List getSupportedPlatforms() { + return supportedPlatforms; + } + + public void setSupportedPlatforms(List supportedPlatforms) { + this.supportedPlatforms = supportedPlatforms; + } + + public String getAdamId() { + return adamId; + } + + public void setAdamId(String adamId) { + this.adamId = adamId; + } + + public String getAssignedCount() { + return assignedCount; + } + + public void setAssignedCount(String assignedCount) { + this.assignedCount = assignedCount; + } + + public String getAvailableCount() { + return availableCount; + } + + public void setAvailableCount(String availableCount) { + this.availableCount = availableCount; + } + + public String getDeviceAssignable() { + return deviceAssignable; + } + + public void setDeviceAssignable(String deviceAssignable) { + this.deviceAssignable = deviceAssignable; + } + + public String getPricingParam() { + return pricingParam; + } + + public void setPricingParam(String pricingParam) { + this.pricingParam = pricingParam; + } + + public String getProductType() { + return productType; + } + + public void setProductType(String productType) { + this.productType = productType; + } + + public String getRetiredCount() { + return retiredCount; + } + + public void setRetiredCount(String retiredCount) { + this.retiredCount = retiredCount; + } + + public String getRevocable() { + return revocable; + } + + public void setRevocable(String revocable) { + this.revocable = revocable; + } + + +} \ No newline at end of file diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppItuneUserDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppItuneUserDTO.java new file mode 100644 index 0000000000..d9ebb4ee59 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppItuneUserDTO.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.common.dto; + +public class VppItuneUserDTO { + String clientUserId; + String inviteCode; + String status; + String email; + String managedId; + + public String getClientUserId() { + return clientUserId; + } + + public void setClientUserId(String clientUserId) { + this.clientUserId = clientUserId; + } + + public String getInviteCode() { + return inviteCode; + } + + public void setInviteCode(String inviteCode) { + this.inviteCode = inviteCode; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getManagedId() { + return managedId; + } + + public void setManagedId(String managedId) { + this.managedId = managedId; + } + +} \ No newline at end of file diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppPaginationDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppPaginationDTO.java new file mode 100644 index 0000000000..95cf054f9c --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppPaginationDTO.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.common.dto; + +public class VppPaginationDTO { + + int currentPageIndex; + int size; + String tokenExpirationDate; + int nextPageIndex; + int totalPages; + String uId; + String versionId; + + public int getCurrentPageIndex() { + return currentPageIndex; + } + + public void setCurrentPageIndex(int currentPageIndex) { + this.currentPageIndex = currentPageIndex; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + public String getTokenExpirationDate() { + return tokenExpirationDate; + } + + public void setTokenExpirationDate(String tokenExpirationDate) { + this.tokenExpirationDate = tokenExpirationDate; + } + + public int getNextPageIndex() { + return nextPageIndex; + } + + public void setNextPageIndex(int nextPageIndex) { + this.nextPageIndex = nextPageIndex; + } + + public int getTotalPages() { + return totalPages; + } + + public void setTotalPages(int totalPages) { + this.totalPages = totalPages; + } + + public String getuId() { + return uId; + } + + public void setuId(String uId) { + this.uId = uId; + } + + public String getVersionId() { + return versionId; + } + + public void setVersionId(String versionId) { + this.versionId = versionId; + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppUserDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppUserDTO.java new file mode 100644 index 0000000000..4ea7929014 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppUserDTO.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.common.dto; + +public class VppUserDTO extends VppItuneUserDTO { + int id; + String dmUsername; + int tenantId; + String createdTime; + String lastUpdatedTime; + String tmpPassword; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getDmUsername() { + return dmUsername; + } + + public void setDmUsername(String dmUsername) { + this.dmUsername = dmUsername; + } + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public String getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(String createdTime) { + this.createdTime = createdTime; + } + + public String getLastUpdatedTime() { + return lastUpdatedTime; + } + + public void setLastUpdatedTime(String lastUpdatedTime) { + this.lastUpdatedTime = lastUpdatedTime; + } + + public String getTmpPassword() { + return tmpPassword; + } + + public void setTmpPassword(String tmpPassword) { + this.tmpPassword = tmpPassword; + } + + @Override + public String toString() { + return "VppUserDTO{" + + "id=" + id + + ", dmUsername='" + dmUsername + '\'' + + ", tenantId=" + tenantId + + ", createdTime='" + createdTime + '\'' + + ", lastUpdatedTime='" + lastUpdatedTime + '\'' + + ", tmpPassword='" + tmpPassword + '\'' + + ", clientUserId='" + clientUserId + '\'' + + ", inviteCode='" + inviteCode + '\'' + + ", status='" + status + '\'' + + ", email='" + email + '\'' + + ", managedId='" + managedId + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/response/Application.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/response/Application.java index 025f352e4c..0d62a46a5b 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/response/Application.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/response/Application.java @@ -108,6 +108,12 @@ public class Application { value = "if the app is favoured by the user") private boolean isFavourite; + @ApiModelProperty(name = "isExternalAppStoreApp", + value = "Is the app coming from an external application store", + required = true, + example = "true or false") + private boolean isExternalAppStoreApp; + public String getPackageName() { return packageName; } @@ -194,4 +200,12 @@ public class Application { public void setFavourite(boolean favourite) { isFavourite = favourite; } + + public boolean isExternalAppStoreApp() { + return isExternalAppStoreApp; + } + + public void setExternalAppStoreApp(boolean externalAppStoreApp) { + isExternalAppStoreApp = externalAppStoreApp; + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java index 44c9d3c983..ceed8f5544 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java @@ -17,14 +17,7 @@ */ package io.entgra.device.mgt.core.application.mgt.common.services; -import io.entgra.device.mgt.core.application.mgt.common.ApplicationArtifact; -import io.entgra.device.mgt.core.application.mgt.common.ApplicationList; import io.entgra.device.mgt.core.application.mgt.common.ApplicationType; -import io.entgra.device.mgt.core.application.mgt.common.Filter; -import io.entgra.device.mgt.core.application.mgt.common.LifecycleChanger; -import io.entgra.device.mgt.core.application.mgt.common.LifecycleState; -import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; -import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.RequestValidatingException; import io.entgra.device.mgt.core.application.mgt.common.exception.ResourceManagementException; @@ -34,8 +27,21 @@ import io.entgra.device.mgt.core.application.mgt.common.response.Category; import io.entgra.device.mgt.core.application.mgt.common.response.Tag; import io.entgra.device.mgt.core.application.mgt.common.wrapper.*; import io.entgra.device.mgt.core.device.mgt.common.Base64File; +import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import org.apache.cxf.jaxrs.ext.multipart.Attachment; - +import io.entgra.device.mgt.core.application.mgt.common.ApplicationArtifact; +import io.entgra.device.mgt.core.application.mgt.common.LifecycleChanger; +import io.entgra.device.mgt.core.application.mgt.common.ApplicationList; +import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; +import io.entgra.device.mgt.core.application.mgt.common.Filter; +import io.entgra.device.mgt.core.application.mgt.common.LifecycleState; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.CustomAppReleaseWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.EntAppReleaseWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationUpdateWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.PublicAppReleaseWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.WebAppReleaseWrapper; import java.util.List; /** @@ -269,6 +275,17 @@ public interface ApplicationManager { */ ApplicationDTO getApplication(int applicationId) throws ApplicationManagementException; + /** + * This method is responsible to provide application data for given deviceId. + * + * @param deviceId id of the device + * @return {@link ApplicationDTO} + * @throws ApplicationManagementException + * if an error occurred while getting subscribed app details for relevant device id, + */ + ApplicationList getSubscribedAppsOfDevice(int deviceId, PaginationRequest request) + throws ApplicationManagementException; + /** * To get the Application for given Id. * diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/SubscriptionManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/SubscriptionManager.java index 8219354946..cd66878019 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/SubscriptionManager.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/SubscriptionManager.java @@ -27,6 +27,7 @@ import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import java.util.List; import java.util.Properties; @@ -207,4 +208,13 @@ public interface SubscriptionManager { */ PaginationResult getAppInstalledSubscribeDevices(PaginationRequest request, String appUUID, String subType, String subTypeName) throws ApplicationManagementException; + + + /*** + * This method is responsible for retrieving application details of the passed operation id. + * @param id ID of the related operation + * @return {@link Activity} Activity result of the app information. + * @throws {@link SubscriptionManagementException} Exception of the subscription management + */ + Activity getOperationAppDetails(String id) throws SubscriptionManagementException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/VPPApplicationManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/VPPApplicationManager.java new file mode 100644 index 0000000000..7075424c33 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/VPPApplicationManager.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.common.services; + +import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssociationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; + +import java.io.IOException; +import java.util.List; + +public interface VPPApplicationManager { + + VppUserDTO addUser(VppUserDTO userDTO) throws ApplicationManagementException; + + VppUserDTO getUserByDMUsername(String emmUsername) throws ApplicationManagementException; + + void updateUser(VppUserDTO userDTO) throws ApplicationManagementException; + + void syncUsers(String clientId) throws ApplicationManagementException; + + void syncAssets(int nextPageIndex) throws ApplicationManagementException; + + VppAssetDTO getAssetByAppId(int appId) throws ApplicationManagementException; + + ProxyResponse callVPPBackend(String url, String payload, String accessToken, String method) throws IOException; + + boolean addAssociation(VppAssetDTO asset, List vppUsers) throws + ApplicationManagementException; + + VppAssociationDTO getAssociation(int assetId, int userId) throws ApplicationManagementException; + + VppAssociationDTO getUserAssociation(String adamId, String emmUsername) throws ApplicationManagementException; +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppAssociateRequestWrapper.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppAssociateRequestWrapper.java new file mode 100644 index 0000000000..7cea9d52c8 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppAssociateRequestWrapper.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.common.wrapper; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; + +import java.util.ArrayList; +import java.util.List; + +public class VppAssociateRequestWrapper { + + List assets; + List clientUserIds; + + public List getAssets() { + return assets; + } + + public void setAssets(List assets) { + this.assets = assets; + } + + public List getClientUserIds() { + return clientUserIds; + } + + public void setClientUserIds(List clientUserIds) { + this.clientUserIds = clientUserIds; + } + +} \ No newline at end of file diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppItuneAssetResponseWrapper.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppItuneAssetResponseWrapper.java new file mode 100644 index 0000000000..26c45207ab --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppItuneAssetResponseWrapper.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.common.wrapper; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppPaginationDTO; + +import java.util.ArrayList; +import java.util.List; + +public class VppItuneAssetResponseWrapper extends VppPaginationDTO { + + List assets; + + public List getAssets() { + return assets; + } + + public void setAssets(List assets) { + this.assets = assets; + } + +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppItuneUserRequestWrapper.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppItuneUserRequestWrapper.java new file mode 100644 index 0000000000..4189fa557a --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppItuneUserRequestWrapper.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.common.wrapper; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; + +import java.util.ArrayList; +import java.util.List; + +public class VppItuneUserRequestWrapper { + + List users; + + public VppItuneUserRequestWrapper() { + users = new ArrayList<>(); + } + public List getUser() { + return users; + } + + public void setUser(List users) { + this.users = users; + } + +} \ No newline at end of file diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppItuneUserResponseWrapper.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppItuneUserResponseWrapper.java new file mode 100644 index 0000000000..64ee578241 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppItuneUserResponseWrapper.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.common.wrapper; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppPaginationDTO; + +import java.util.ArrayList; +import java.util.List; + +public class VppItuneUserResponseWrapper extends VppPaginationDTO { + + List users; + + public VppItuneUserResponseWrapper() { + users = new ArrayList<>(); + } + public List getUser() { + return users; + } + + public void setUser(List users) { + this.users = users; + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml index 581dcf9204..5ebd2d7226 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core application-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml @@ -173,6 +173,11 @@ + + + org.apache.httpcomponents + httpclient + org.apache.felix org.apache.felix.scr.ds-annotations diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationDAO.java index 71e71e2abc..13be8be454 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationDAO.java @@ -22,6 +22,7 @@ import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.CategoryDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.TagDTO; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import java.util.List; @@ -150,6 +151,16 @@ public interface ApplicationDAO { */ ApplicationDTO getApplication(int applicationId, int tenantId) throws ApplicationManagementDAOException; + /** + * To get the application with the given id + * + * @param deviceId ID of the device which the apps are installed on. + * @param tenantId ID of the tenant. + * @return the application + * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception. + */ + List getSubscribedAppsOfDevice(int deviceId, int tenantId, PaginationRequest request) throws ApplicationManagementDAOException; + /** * To get the application with the given uuid * diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SubscriptionDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SubscriptionDAO.java index 8b5caec6ac..804a4a29e2 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SubscriptionDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SubscriptionDAO.java @@ -23,6 +23,7 @@ import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDT import io.entgra.device.mgt.core.application.mgt.common.dto.ScheduledSubscriptionDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import java.util.List; import java.util.Map; @@ -252,4 +253,15 @@ public interface SubscriptionDAO { * @throws {@link ApplicationManagementDAOException} if connections establishment fails. */ Map getCurrentInstalledAppVersion(int appId, List deviceIdList, String installedVersion) throws ApplicationManagementDAOException; + + + /** + * Retrieves app details by operation id. + * + * @param operationId ID of the operation which app details needs to be retrieved + * @param tenantId ID of tenant + * @return {@link Activity} + * @throws ApplicationManagementDAOException if error occurred while retrieving the app details + */ + Activity getOperationAppDetails(int operationId, int tenantId) throws ApplicationManagementDAOException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/VppApplicationDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/VppApplicationDAO.java new file mode 100644 index 0000000000..02aec95174 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/VppApplicationDAO.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.core.dao; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssociationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; + + +public interface VppApplicationDAO { + + int addVppUser(VppUserDTO userDTO, int tenantId) throws ApplicationManagementDAOException; + + VppUserDTO updateVppUser(VppUserDTO userDTO, int tenantId) throws ApplicationManagementDAOException; + + VppUserDTO getUserByDMUsername(String emmUsername, int tenantId) throws ApplicationManagementDAOException; + + VppAssetDTO getAssetByAppId(int appId, int tenantId) throws ApplicationManagementDAOException; + + int addAsset(VppAssetDTO vppAssetDTO, int tenantId) throws ApplicationManagementDAOException; + + VppAssetDTO updateAsset(VppAssetDTO vppAssetDTO, int tenantId) throws ApplicationManagementDAOException; + + VppAssociationDTO getAssociation(int assetId, int userId, int tenantId) throws ApplicationManagementDAOException; + + int addAssociation(VppAssociationDTO vppAssociationDTO, int tenantId) throws ApplicationManagementDAOException; + + VppAssociationDTO updateAssociation(VppAssociationDTO vppAssociationDTO, int tenantId) throws ApplicationManagementDAOException; +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java index 554bd32b1e..1a29b33b2d 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java @@ -17,25 +17,36 @@ */ package io.entgra.device.mgt.core.application.mgt.core.dao.common; -import io.entgra.device.mgt.core.application.mgt.common.exception.UnsupportedDatabaseEngineException; import io.entgra.device.mgt.core.application.mgt.core.dao.*; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.GenericApplicationDAOImpl; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.OracleApplicationDAOImpl; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.PostgreSQLApplicationDAOImpl; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.SQLServerApplicationDAOImpl; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.release.GenericApplicationReleaseDAOImpl; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.release.OracleApplicationReleaseDAOImpl; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.release.PostgreSQLApplicationReleaseDAOImpl; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.release.SQLServerApplicationReleaseDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.spapplication.GenericSPApplicationDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.spapplication.OracleSPApplicationDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.spapplication.PostgreSQLSPApplicationDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.spapplication.SQLServerSPApplicationDAOImpl; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.lifecyclestate.GenericLifecycleStateDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility.GenericVisibilityDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility.OracleVisibilityDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility.PostgreSQLVisibilityDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility.SQLServerVisibilityDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp.GenericVppApplicationDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp.OracleVppApplicationDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp.PostgreSQLVppApplicationDAO; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp.SQLServerVppApplicationDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.util.Constants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import io.entgra.device.mgt.core.application.mgt.common.exception.UnsupportedDatabaseEngineException; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.PostgreSQLApplicationDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.SQLServerApplicationDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.release.OracleApplicationReleaseDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.release.PostgreSQLApplicationReleaseDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.release.SQLServerApplicationReleaseDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.lifecyclestate.OracleLifecycleStateDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.lifecyclestate.PostgreSQLLifecycleStateDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.lifecyclestate.SQLServerLifecycleStateDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.review.GenericReviewDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.GenericApplicationDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.release.GenericApplicationReleaseDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.OracleApplicationDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.lifecyclestate.GenericLifecycleStateDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.review.OracleReviewDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.review.PostgreSQLReviewDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.review.SQLServerReviewDAOImpl; @@ -43,14 +54,7 @@ import io.entgra.device.mgt.core.application.mgt.core.dao.impl.subscription.Gene import io.entgra.device.mgt.core.application.mgt.core.dao.impl.subscription.OracleSubscriptionDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.subscription.PostgreSQLSubscriptionDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.subscription.SQLServerSubscriptionDAOImpl; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility.GenericVisibilityDAOImpl; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility.OracleVisibilityDAOImpl; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility.PostgreSQLVisibilityDAOImpl; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility.SQLServerVisibilityDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil; -import io.entgra.device.mgt.core.application.mgt.core.util.Constants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import javax.sql.DataSource; import java.sql.SQLException; @@ -226,4 +230,28 @@ public class ApplicationManagementDAOFactory { } throw new IllegalStateException("Database engine has not initialized properly."); } + + + /** + * To get the instance of VppApplicationImplementation of the particular database engine. + * @return specific VppApplicationImplementation + */ + public static VppApplicationDAO getVppApplicationDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case Constants.DataBaseTypes.DB_TYPE_H2: + case Constants.DataBaseTypes.DB_TYPE_MYSQL: + return new GenericVppApplicationDAOImpl(); + case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new PostgreSQLVppApplicationDAO(); + case Constants.DataBaseTypes.DB_TYPE_ORACLE: + return new OracleVppApplicationDAOImpl(); + case Constants.DataBaseTypes.DB_TYPE_MSSQL: + return new SQLServerVppApplicationDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java index 82f4b3d191..5999767301 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java @@ -29,6 +29,7 @@ import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManag import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -652,6 +653,84 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic } } + @Override + public List getSubscribedAppsOfDevice(int deviceId, int tenantId, PaginationRequest request) throws + ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Getting all installed apps of device " + deviceId + + " from the database"); + } + List appList = null; + + String sql = "SELECT " + + "AP_APP.ID AS APP_ID, " + + "AP_APP.NAME AS APP_NAME, " + + "AP_APP.DESCRIPTION AS APP_DESCRIPTION, " + + "AP_APP.TYPE AS APP_TYPE, " + + "AP_APP.STATUS AS APP_STATUS, " + + "AP_APP.SUB_TYPE AS APP_SUB_TYPE, " + + "AP_APP.CURRENCY AS APP_CURRENCY, " + + "AP_APP.RATING AS APP_RATING, " + + "AP_APP.DEVICE_TYPE_ID AS APP_DEVICE_TYPE_ID, " + + "AP_APP_RELEASE.ID AS RELEASE_ID, " + + "AP_APP_RELEASE.DESCRIPTION AS RELEASE_DESCRIPTION, " + + "AP_APP_RELEASE.VERSION AS RELEASE_VERSION, " + + "AP_APP_RELEASE.UUID AS RELEASE_UUID, " + + "AP_APP_RELEASE.RELEASE_TYPE AS RELEASE_TYPE, " + + "AP_APP_RELEASE.INSTALLER_LOCATION AS AP_RELEASE_STORED_LOC, " + + "AP_APP_RELEASE.ICON_LOCATION AS AP_RELEASE_ICON_LOC, " + + "AP_APP_RELEASE.BANNER_LOCATION AS AP_RELEASE_BANNER_LOC, " + + "AP_APP_RELEASE.SC_1_LOCATION AS AP_RELEASE_SC1, " + + "AP_APP_RELEASE.SC_2_LOCATION AS AP_RELEASE_SC2, " + + "AP_APP_RELEASE.SC_3_LOCATION AS AP_RELEASE_SC3, " + + "AP_APP_RELEASE.APP_HASH_VALUE AS RELEASE_HASH_VALUE, " + + "AP_APP_RELEASE.APP_PRICE AS RELEASE_PRICE, " + + "AP_APP_RELEASE.APP_META_INFO AS RELEASE_META_INFO, " + + "AP_APP_RELEASE.PACKAGE_NAME AS PACKAGE_NAME, " + + "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + + "AP_APP_RELEASE.RATING AS RELEASE_RATING, " + + "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, " + + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT " + + "FROM AP_APP " + + "JOIN AP_APP_RELEASE ON AP_APP.ID = AP_APP_RELEASE.AP_APP_ID " + + "JOIN AP_DEVICE_SUBSCRIPTION ON AP_APP_RELEASE.ID = AP_DEVICE_SUBSCRIPTION.AP_APP_RELEASE_ID " + + "WHERE AP_DEVICE_SUBSCRIPTION.DM_DEVICE_ID = ? AND AP_DEVICE_SUBSCRIPTION.TENANT_ID= ? " + +"AND AP_DEVICE_SUBSCRIPTION.STATUS= 'COMPLETED'"; + + if (request != null) { + sql = sql + " LIMIT ?,?"; + } + + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, deviceId); + stmt.setInt(2, tenantId); + if (request != null) { + stmt.setInt(3, request.getStartIndex()); + stmt.setInt(4, request.getRowCount()); + } + try (ResultSet rs = stmt.executeQuery()) { + appList = new ArrayList<>(); + while (rs.next()) { + ApplicationDTO app = DAOUtil.loadDeviceApp(rs); + appList.add(app); + } + return appList; + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection for getting all apps installed on the device of " + + "device Id: " + deviceId + "."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while while running SQL to get all installed apps of device with device Id: " + deviceId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + @Override public boolean updateApplication(ApplicationDTO applicationDTO, int tenantId) throws ApplicationManagementDAOException { diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java index bd3bdf3bb6..9dd324123c 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java @@ -17,19 +17,20 @@ */ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.subscription; +import io.entgra.device.mgt.core.application.mgt.core.dao.SubscriptionDAO; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; +import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.ExecutionStatus; import io.entgra.device.mgt.core.application.mgt.common.SubAction; import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ScheduledSubscriptionDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; -import io.entgra.device.mgt.core.application.mgt.core.dao.SubscriptionDAO; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; -import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; -import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import java.sql.*; import java.util.*; @@ -1425,4 +1426,44 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc throw new ApplicationManagementDAOException(msg, e); } } + + public Activity getOperationAppDetails(int operationId, int tenantId) throws ApplicationManagementDAOException { + try { + String sql = "SELECT " + + "AP.NAME, " + + "AP.TYPE, " + + "AR.PACKAGE_NAME, " + + "AR.VERSION, " + + "DS.SUBSCRIBED_BY, " + + "DS.STATUS, " + + "DS.ACTION_TRIGGERED_FROM " + + "FROM AP_APP_SUB_OP_MAPPING SOP " + + "JOIN AP_DEVICE_SUBSCRIPTION DS ON SOP.AP_DEVICE_SUBSCRIPTION_ID = DS.ID " + + "JOIN AP_APP_RELEASE AR ON DS.AP_APP_RELEASE_ID = AR.ID " + + "JOIN AP_APP AP ON AP.ID = AR.AP_APP_ID " + + " WHERE SOP.OPERATION_ID = ? AND SOP.TENANT_ID = ?"; + + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, operationId); + stmt.setInt(2,tenantId); + try (ResultSet rs = stmt.executeQuery()) { + return DAOUtil.loadOperationActivity(rs); + } + } + } catch (DBConnectionException e) { + String msg = + "Error occurred while getting the app details from the database related to operation " + operationId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to retrieve app details of operation" + operationId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "More than one app for operation " + operationId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/GenericVppApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/GenericVppApplicationDAOImpl.java new file mode 100644 index 0000000000..38fa090f94 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/GenericVppApplicationDAOImpl.java @@ -0,0 +1,508 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssociationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; +import io.entgra.device.mgt.core.application.mgt.core.dao.VppApplicationDAO; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; +import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.*; +import java.util.List; + +public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements VppApplicationDAO { + private static final Log log = LogFactory.getLog(GenericVppApplicationDAOImpl.class); + + @Override + public int addVppUser(VppUserDTO userDTO, int tenantId) + throws ApplicationManagementDAOException { + int vppUserId = -1; + String sql = "INSERT INTO " + + "AP_VPP_USER(" + + "CLIENT_USER_ID, " + + "DM_USERNAME, " + + "TENANT_ID, " + + "EMAIL, " + + "INVITE_CODE, " + + "STATUS," + + "CREATED_TIME," + + "LAST_UPDATED_TIME," + + "MANAGED_ID," + + "TEMP_PASSWORD) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + long currentTime = System.currentTimeMillis(); + stmt.setString(1, userDTO.getClientUserId()); + stmt.setString(2, userDTO.getDmUsername()); + stmt.setInt(3, tenantId); + stmt.setString(4, userDTO.getEmail()); + stmt.setString(5, userDTO.getInviteCode()); + stmt.setString(6, userDTO.getStatus()); + stmt.setLong(7, currentTime); + stmt.setLong(8, currentTime); + stmt.setString(9, userDTO.getManagedId()); + stmt.setString(10, userDTO.getTmpPassword()); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + vppUserId = rs.getInt(1); + } + } + return vppUserId; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when adding the vpp user"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to add the vpp user."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public VppUserDTO updateVppUser(VppUserDTO userDTO, int tenantId) + throws ApplicationManagementDAOException { + + String sql = "UPDATE AP_VPP_USER SET "; + if (userDTO.getClientUserId() != null && !userDTO.getClientUserId().isEmpty()) { + sql += "CLIENT_USER_ID = ?,"; + } + if (userDTO.getDmUsername() != null && !userDTO.getDmUsername().isEmpty()) { + sql += "DM_USERNAME = ?,"; + } + if (userDTO.getEmail() != null && !userDTO.getEmail().isEmpty()) { + sql += "EMAIL = ?,"; + } + if (userDTO.getInviteCode() != null && !userDTO.getInviteCode().isEmpty()) { + sql += "INVITE_CODE = ?,"; + } + if (userDTO.getStatus() != null && !userDTO.getStatus().isEmpty()) { + sql += "STATUS = ?,"; + } + if (userDTO.getManagedId() != null && !userDTO.getManagedId().isEmpty()) { + sql += "MANAGED_ID = ?,"; + } + if (userDTO.getTmpPassword() != null && !userDTO.getTmpPassword().isEmpty()) { + sql += "TEMP_PASSWORD = ?,"; + } + + sql += " TENANT_ID = ?, LAST_UPDATED_TIME = ? WHERE ID = ?"; + + try { + Connection conn = this.getDBConnection(); + long updatedTime = System.currentTimeMillis(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int x = 0; + + if (userDTO.getClientUserId() != null && !userDTO.getClientUserId().isEmpty()) { + stmt.setString(++x, userDTO.getClientUserId()); + } + if (userDTO.getDmUsername() != null && !userDTO.getDmUsername().isEmpty()) { + stmt.setString(++x, userDTO.getDmUsername()); + } + if (userDTO.getEmail() != null && !userDTO.getEmail().isEmpty()) { + stmt.setString(++x, userDTO.getEmail()); + } + if (userDTO.getInviteCode() != null && !userDTO.getInviteCode().isEmpty()) { + stmt.setString(++x, userDTO.getInviteCode()); + } + if (userDTO.getStatus() != null && !userDTO.getStatus().isEmpty()) { + stmt.setString(++x, userDTO.getStatus()); + } + if (userDTO.getManagedId() != null && !userDTO.getManagedId().isEmpty()) { + stmt.setString(++x, userDTO.getManagedId()); + } + if (userDTO.getTmpPassword() != null && !userDTO.getTmpPassword().isEmpty()) { + stmt.setString(++x, userDTO.getTmpPassword()); + } + stmt.setInt(++x, tenantId); + stmt.setLong(++x, updatedTime); + stmt.setInt(++x, userDTO.getId()); + if (stmt.executeUpdate() == 1) { + return userDTO; + } + return null; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when updating the vpp user"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to updating the vpp user."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public VppUserDTO getUserByDMUsername(String emmUsername, int tenantId) + throws ApplicationManagementDAOException { + String sql = "SELECT " + + "ID, " + + "CLIENT_USER_ID, " + + "TENANT_ID, " + + "EMAIL, " + + "INVITE_CODE, " + + "STATUS, " + + "CREATED_TIME, " + + "LAST_UPDATED_TIME, " + + "MANAGED_ID, " + + "TEMP_PASSWORD, " + + "DM_USERNAME " + + "FROM AP_VPP_USER " + + "WHERE DM_USERNAME = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, emmUsername); + stmt.setInt(2, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + return DAOUtil.loadVppUser(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when retrieving vpp user by EMM Username."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to retrieve vpp user by EMM Username."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "Found more than one user for: " + emmUsername; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public VppAssetDTO getAssetByAppId(int appId, int tenantId) + throws ApplicationManagementDAOException { + String sql = "SELECT " + + "ID, " + + "APP_ID, " + + "TENANT_ID, " + + "CREATED_TIME, " + + "LAST_UPDATED_TIME, " + + "ADAM_ID, " + + "ASSIGNED_COUNT, " + + "DEVICE_ASSIGNABLE, " + + "PRICING_PARAMS, " + + "PRODUCT_TYPE, " + + "RETIRED_COUNT, " + + "REVOCABLE " +// + "SUPPORTED_PLATFORMS " + + "FROM AP_ASSETS " + + "WHERE APP_ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, appId); + stmt.setInt(2, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + return DAOUtil.loadAsset(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when retrieving asset data of app id "+ appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to retrieve asset by app id."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "Found more than one app for app id: " + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public int addAsset(VppAssetDTO vppAssetDTO, int tenantId) + throws ApplicationManagementDAOException { + int assetId = -1; + String sql = "INSERT INTO " + + "AP_ASSETS(" + + "APP_ID, " + + "TENANT_ID, " + + "CREATED_TIME," + + "LAST_UPDATED_TIME," + + "ADAM_ID," + + "ASSIGNED_COUNT," + + "DEVICE_ASSIGNABLE," + + "PRICING_PARAMS," + + "PRODUCT_TYPE," + + "RETIRED_COUNT," + + "REVOCABLE, " + + "SUPPORTED_PLATFORMS) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + long currentTime = System.currentTimeMillis(); + stmt.setInt(1, vppAssetDTO.getAppId()); + stmt.setInt(2, tenantId); + stmt.setLong(3, currentTime); + stmt.setLong(4, currentTime); + stmt.setString(5, vppAssetDTO.getAdamId()); + stmt.setString(6, vppAssetDTO.getAssignedCount()); + stmt.setString(7, vppAssetDTO.getDeviceAssignable()); + stmt.setString(8, vppAssetDTO.getPricingParam()); + stmt.setString(9, vppAssetDTO.getProductType()); + stmt.setString(10, vppAssetDTO.getRetiredCount()); + stmt.setString(11, vppAssetDTO.getRevocable()); + List platformList = vppAssetDTO.getSupportedPlatforms(); + String platformString = String.join(",", platformList); + stmt.setString(12, platformString); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + assetId = rs.getInt(1); + } + } + return assetId; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when adding the asset."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to add the asset."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public VppAssetDTO updateAsset(VppAssetDTO vppAssetDTO, int tenantId) + throws ApplicationManagementDAOException { + + String sql = "UPDATE AP_ASSETS SET "; + + if (vppAssetDTO.getAdamId() != null && !vppAssetDTO.getAdamId().isEmpty()) { + sql += "ADAM_ID = ?, "; + } + if (vppAssetDTO.getAssignedCount() != null && !vppAssetDTO.getAssignedCount().isEmpty()) { + sql += "ASSIGNED_COUNT = ?, "; + } + if (vppAssetDTO.getDeviceAssignable() != null && !vppAssetDTO.getDeviceAssignable().isEmpty()) { + sql += "DEVICE_ASSIGNABLE = ?, "; + } + if (vppAssetDTO.getPricingParam() != null && !vppAssetDTO.getPricingParam().isEmpty()) { + sql += "PRICING_PARAMS = ?, "; + } + if (vppAssetDTO.getProductType() != null && !vppAssetDTO.getProductType().isEmpty()) { + sql += "PRODUCT_TYPE = ?, "; + } + if (vppAssetDTO.getRetiredCount() != null && !vppAssetDTO.getRetiredCount().isEmpty()) { + sql += "RETIRED_COUNT = ?, "; + } + if (vppAssetDTO.getRevocable() != null && !vppAssetDTO.getRevocable().isEmpty()) { + sql += "REVOCABLE = ?, "; + } + if (vppAssetDTO.getSupportedPlatforms() != null && !vppAssetDTO.getSupportedPlatforms().isEmpty()) { + sql += "SUPPORTED_PLATFORMS = ?,"; + } + sql += "APP_ID = ?, LAST_UPDATED_TIME = ? WHERE ID = ? AND TENANT_ID = ?"; + + try { + Connection conn = this.getDBConnection(); + long updatedTime = System.currentTimeMillis(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int x = 0; + + if (vppAssetDTO.getAdamId() != null && !vppAssetDTO.getAdamId().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getAdamId()); + } + if (vppAssetDTO.getAssignedCount() != null && !vppAssetDTO.getAssignedCount().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getAssignedCount()); + } + if (vppAssetDTO.getDeviceAssignable() != null && !vppAssetDTO.getDeviceAssignable().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getDeviceAssignable()); + } + if (vppAssetDTO.getPricingParam() != null && !vppAssetDTO.getPricingParam().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getPricingParam()); + } + if (vppAssetDTO.getProductType() != null && !vppAssetDTO.getProductType().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getProductType()); + } + if (vppAssetDTO.getRetiredCount() != null && !vppAssetDTO.getRetiredCount().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getRetiredCount()); + } + if (vppAssetDTO.getRevocable() != null && !vppAssetDTO.getRevocable().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getRevocable()); + } + if (vppAssetDTO.getSupportedPlatforms() != null && !vppAssetDTO.getSupportedPlatforms().isEmpty()) { + List platformList = vppAssetDTO.getSupportedPlatforms(); + String platformString = String.join(",", platformList); + stmt.setString(++x, platformString); + } + + stmt.setInt(++x, vppAssetDTO.getAppId()); + stmt.setLong(++x, updatedTime); + stmt.setInt(++x, vppAssetDTO.getId()); + stmt.setLong(++x, tenantId); + if (stmt.executeUpdate() == 1) { + return vppAssetDTO; + } + return null; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when updating the vpp user"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to updating the vpp user."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public VppAssociationDTO getAssociation(int assetId, int userId, int tenantId) + throws ApplicationManagementDAOException { + String sql = "SELECT " + + "ID, " + + "ASSOCIATION_TYPE, " + + "CREATED_TIME, " + + "LAST_UPDATED_TIME, " + + "PRICING_PARAMS " + + "FROM AP_VPP_ASSOCIATION " + + "WHERE ASSET_ID = ? AND USER_ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, assetId); + stmt.setInt(2, userId); + stmt.setInt(3, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + return DAOUtil.loadAssignment(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when retrieving assignment data of user with id "+ userId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to retrieve assignment by asset id and user id."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "Found more than one assignment for user id: " + userId + " and asset id: " + assetId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public int addAssociation(VppAssociationDTO vppAssociationDTO, int tenantId) + throws ApplicationManagementDAOException { + int associationId = -1; + String sql = "INSERT INTO " + + "AP_VPP_ASSOCIATION(" + + "ASSET_ID, " + + "USER_ID, " + + "TENANT_ID, " + + "ASSOCIATION_TYPE," + + "CREATED_TIME," + + "LAST_UPDATED_TIME," + + "PRICING_PARAMS) " + + "VALUES (?, ?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + long currentTime = System.currentTimeMillis(); + stmt.setInt(1, vppAssociationDTO.getAssetId()); + stmt.setInt(2, vppAssociationDTO.getClientId()); + stmt.setInt(3, tenantId); + stmt.setString(4, vppAssociationDTO.getAssociationType()); + stmt.setLong(5, currentTime); + stmt.setLong(6, currentTime); + stmt.setString(7, vppAssociationDTO.getPricingParam()); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + associationId = rs.getInt(1); + } + } + return associationId; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when adding the asset."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to add the asset."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public VppAssociationDTO updateAssociation(VppAssociationDTO vppAssociationDTO, int tenantId) + throws ApplicationManagementDAOException { + + String sql = "UPDATE " + + "AP_VPP_ASSOCIATION " + + "SET " + + "ASSET_ID = ?," + + "USER_ID = ?, " + + "ASSOCIATION_TYPE = ?, " + + "LAST_UPDATED_TIME = ?, " + + "PRICING_PARAMS = ? " + + "WHERE ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + long updatedTime = System.currentTimeMillis(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, vppAssociationDTO.getAssetId()); + stmt.setInt(2, vppAssociationDTO.getClientId()); + stmt.setString(3, vppAssociationDTO.getAssociationType()); + stmt.setLong(4, updatedTime); + stmt.setString(5, vppAssociationDTO.getPricingParam()); + stmt.setInt(6, vppAssociationDTO.getId()); + stmt.setLong(7, tenantId); + if (stmt.executeUpdate() == 1) { + return vppAssociationDTO; + } + return null; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when updating the vpp user"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to updating the vpp user."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/OracleVppApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/OracleVppApplicationDAOImpl.java new file mode 100644 index 0000000000..480f18006e --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/OracleVppApplicationDAOImpl.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.*; + +public class OracleVppApplicationDAOImpl extends GenericVppApplicationDAOImpl { + + private static final Log log = LogFactory.getLog(GenericVppApplicationDAOImpl.class); + + @Override + public int addVppUser(VppUserDTO userDTO, int tenantId) + throws ApplicationManagementDAOException { + int vppUserId = -1; + String sql = "INSERT INTO " + + "AP_VPP_USER(" + + "CLIENT_USER_ID, " + + "DM_USERNAME, " + + "TENANT_ID, " + + "EMAIL, " + + "INVITE_CODE, " + + "STATUS," + + "CREATED_TIME," + + "LAST_UPDATED_TIME," + + "MANAGED_ID," + + "TEMP_PASSWORD) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, new String[] {"ID"})) { + long currentTime = System.currentTimeMillis(); + stmt.setString(1, userDTO.getClientUserId()); + stmt.setString(2, userDTO.getDmUsername()); + stmt.setInt(3, tenantId); + stmt.setString(4, userDTO.getEmail()); + stmt.setString(5, userDTO.getInviteCode()); + stmt.setString(6, userDTO.getStatus()); + stmt.setLong(7, currentTime); + stmt.setLong(8, currentTime); + stmt.setString(9, userDTO.getManagedId()); + stmt.setString(10, userDTO.getTmpPassword()); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + vppUserId = rs.getInt(1); + } + } + return vppUserId; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when adding the vpp user"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to add the vpp user."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/PostgreSQLVppApplicationDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/PostgreSQLVppApplicationDAO.java new file mode 100644 index 0000000000..5d9fe7a8f6 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/PostgreSQLVppApplicationDAO.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.*; + +public class PostgreSQLVppApplicationDAO extends GenericVppApplicationDAOImpl { + + private static final Log log = LogFactory.getLog(GenericVppApplicationDAOImpl.class); + + public int addVppUser(VppUserDTO userDTO, int tenantId) + throws ApplicationManagementDAOException { + int vppUserId = -1; + String sql = "INSERT INTO " + + "AP_VPP_USER(" + + "CLIENT_USER_ID, " + + "DM_USERNAME, " + + "TENANT_ID, " + + "EMAIL, " + + "INVITE_CODE, " + + "STATUS," + + "CREATED_TIME," + + "LAST_UPDATED_TIME," + + "MANAGED_ID," + + "TEMP_PASSWORD) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, new String[]{"ID"})) { + long currentTime = System.currentTimeMillis(); + stmt.setString(1, userDTO.getClientUserId()); + stmt.setString(2, userDTO.getDmUsername()); + stmt.setInt(3, tenantId); + stmt.setString(4, userDTO.getEmail()); + stmt.setString(5, userDTO.getInviteCode()); + stmt.setString(6, userDTO.getStatus()); + stmt.setLong(7, currentTime); + stmt.setLong(8, currentTime); + stmt.setString(9, userDTO.getManagedId()); + stmt.setString(10, userDTO.getTmpPassword()); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + vppUserId = rs.getInt(1); + } + } + return vppUserId; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when adding the vpp user"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to add the vpp user."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/SQLServerVppApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/SQLServerVppApplicationDAOImpl.java new file mode 100644 index 0000000000..da4e4828da --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/SQLServerVppApplicationDAOImpl.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; + +public class SQLServerVppApplicationDAOImpl extends GenericVppApplicationDAOImpl { +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java index ddbf68b2e7..0d65bdbd6d 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java @@ -18,6 +18,24 @@ package io.entgra.device.mgt.core.application.mgt.core.impl; +import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; +import io.entgra.device.mgt.core.device.mgt.common.Base64File; +import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; +import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagementUtil; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.validator.routines.UrlValidator; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.application.mgt.common.ApplicationArtifact; import io.entgra.device.mgt.core.application.mgt.common.ApplicationInstaller; import io.entgra.device.mgt.core.application.mgt.common.ApplicationList; @@ -60,12 +78,10 @@ import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManage import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationReleaseDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.LifecycleStateDAO; -import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.SubscriptionDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.VisibilityDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.common.ApplicationManagementDAOFactory; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; -import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; import io.entgra.device.mgt.core.application.mgt.core.exception.ForbiddenException; import io.entgra.device.mgt.core.application.mgt.core.exception.LifeCycleManagementDAOException; import io.entgra.device.mgt.core.application.mgt.core.exception.NotFoundException; @@ -73,27 +89,12 @@ import io.entgra.device.mgt.core.application.mgt.core.exception.VisibilityManage import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; import io.entgra.device.mgt.core.application.mgt.core.util.APIUtil; -import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagementUtil; import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; -import io.entgra.device.mgt.core.device.mgt.common.Base64File; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import io.entgra.device.mgt.core.device.mgt.core.common.exception.StorageManagementException; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.validator.routines.UrlValidator; -import org.apache.cxf.jaxrs.ext.multipart.Attachment; -import org.json.JSONObject; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; @@ -1443,6 +1444,43 @@ public class ApplicationManagerImpl implements ApplicationManager { } } + @Override + public ApplicationList getSubscribedAppsOfDevice(int deviceId, PaginationRequest request) throws ApplicationManagementException { + ApplicationList applicationList = new ApplicationList(); + List applications = new ArrayList<>(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + try { + ConnectionManagerUtil.openDBConnection(); + List applicationDTOS = this.applicationDAO.getSubscribedAppsOfDevice(deviceId, tenantId, request); + for (ApplicationDTO applicationDTO: applicationDTOS) { + applicationDTO.setTags(this.applicationDAO.getAppTags(applicationDTO.getId(), tenantId)); + applicationDTO.setAppCategories(this.applicationDAO.getAppCategories(applicationDTO.getId(), tenantId)); + applications.add(APIUtil.appDtoToAppResponse(applicationDTO)); + } + + List totalApplications = this.applicationDAO.getSubscribedAppsOfDevice(deviceId, tenantId, null); + Pagination pagination = new Pagination(); + pagination.setCount(totalApplications.size()); + pagination.setSize(applications.size()); + pagination.setOffset(request.getStartIndex()); + pagination.setLimit(request.getRowCount()); + applicationList.setApplications(applications); + applicationList.setPagination(pagination); + return applicationList; + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred when getting installed apps of device with device id: " + + deviceId; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "DB Connection error occurred while getting installed apps of device with device id: " + deviceId; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + /** * Check whether given OS range is valid or invalid * diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java index 7c3ee9694e..5dea673b5e 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java @@ -19,6 +19,29 @@ package io.entgra.device.mgt.core.application.mgt.core.impl; import com.google.gson.Gson; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; +import io.entgra.device.mgt.core.application.mgt.core.dao.VppApplicationDAO; +import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; +import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; +import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; +import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; +import io.entgra.device.mgt.core.notification.logger.AppInstallLogContext; +import io.entgra.device.mgt.core.notification.logger.impl.EntgraAppInstallLoggerImpl; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.lang.StringUtils; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.json.JSONArray; +import org.json.JSONObject; import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplicationKey; import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; import io.entgra.device.mgt.core.application.mgt.common.ApplicationInstallResponse; @@ -46,7 +69,6 @@ import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.SubscriptionDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.common.ApplicationManagementDAOFactory; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; -import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; import io.entgra.device.mgt.core.application.mgt.core.exception.ForbiddenException; import io.entgra.device.mgt.core.application.mgt.core.exception.NotFoundException; import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder; @@ -60,10 +82,7 @@ import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.MDMAppConstants; -import io.entgra.device.mgt.core.device.mgt.common.MDMAppConstants; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.MobileAppTypes; @@ -82,18 +101,11 @@ import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProvider import io.entgra.device.mgt.core.device.mgt.core.util.MDMAndroidOperationUtil; import io.entgra.device.mgt.core.device.mgt.core.util.MDMIOSOperationUtil; import io.entgra.device.mgt.core.device.mgt.core.util.MDMWindowsOperationUtil; -import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; -import io.entgra.device.mgt.core.notification.logger.AppInstallLogContext; -import io.entgra.device.mgt.core.notification.logger.impl.EntgraAppInstallLoggerImpl; -import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; -import org.apache.commons.lang.StringUtils; -import org.json.JSONArray; -import org.json.JSONObject; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserStoreException; @@ -105,6 +117,9 @@ import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -124,12 +139,14 @@ public class SubscriptionManagerImpl implements SubscriptionManager { private static final EntgraLogger log = new EntgraAppInstallLoggerImpl(SubscriptionManagerImpl.class); private SubscriptionDAO subscriptionDAO; private ApplicationDAO applicationDAO; + private VppApplicationDAO vppApplicationDAO; private LifecycleStateManager lifecycleStateManager; public SubscriptionManagerImpl() { this.lifecycleStateManager = DataHolder.getInstance().getLifecycleStateManager(); this.subscriptionDAO = ApplicationManagementDAOFactory.getSubscriptionDAO(); this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO(); + this.vppApplicationDAO = ApplicationManagementDAOFactory.getVppApplicationDAO(); } @Override @@ -154,6 +171,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { ApplicationDTO applicationDTO = getApplicationDTO(applicationUUID); ApplicationSubscriptionInfo applicationSubscriptionInfo = getAppSubscriptionInfo(applicationDTO, subType, params); + performExternalStoreSubscription(applicationDTO, applicationSubscriptionInfo); ApplicationInstallResponse applicationInstallResponse = performActionOnDevices( applicationSubscriptionInfo.getAppSupportingDeviceTypeName(), applicationSubscriptionInfo.getDevices(), applicationDTO, subType, applicationSubscriptionInfo.getSubscribers(), action, properties, isOperationReExecutingDisabled); @@ -162,6 +180,51 @@ public class SubscriptionManagerImpl implements SubscriptionManager { return applicationInstallResponse; } + private void performExternalStoreSubscription(ApplicationDTO applicationDTO, + ApplicationSubscriptionInfo + applicationSubscriptionInfo) throws ApplicationManagementException { + try { + // Only for iOS devices + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + if (DeviceTypes.IOS.toString().equalsIgnoreCase(APIUtil.getDeviceTypeData(applicationDTO + .getDeviceTypeId()).getName())) { + // TODO: replace getAssetByAppId with the correct one in DAO + // Check if the app trying to subscribe is a VPP asset. + VppAssetDTO storedAsset = vppApplicationDAO.getAssetByAppId(applicationDTO.getId(), tenantId); + if (storedAsset != null) { // This is a VPP asset + List users = new ArrayList<>(); + List devices = applicationSubscriptionInfo.getDevices();// get + // subscribed device list, so that we can extract the users of those devices. + for (Device device : devices) { + VppUserDTO user = vppApplicationDAO.getUserByDMUsername(device.getEnrolmentInfo() + .getOwner(), PrivilegedCarbonContext.getThreadLocalCarbonContext() + .getTenantId(true)); + users.add(user); + } + VPPApplicationManager vppManager = APIUtil.getVPPManager(); + vppManager.addAssociation(storedAsset, users); + } + } + } catch (BadRequestException e) { + String msg = "Device Type not found"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "Unexpected error while getting device type"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + String msg = "Error while getting the device user"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementException e) { + String msg = "Error while associating user"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + + } + @Override public void createScheduledSubscription(ScheduledSubscriptionDTO subscriptionDTO) throws SubscriptionManagementException { @@ -1268,38 +1331,37 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } } - private int invokeIOTCoreAPI(HttpMethodBase request) throws UserStoreException, APIManagerException, IOException { - HttpClient httpClient; + private int invokeIOTCoreAPI(HttpPost request) throws UserStoreException, APIManagerException, IOException, + ApplicationManagementException { + CloseableHttpClient httpClient = getHttpClient(); String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); ApiApplicationKey apiApplicationKey = OAuthUtils.getClientCredentials(tenantDomain); String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration() .getAdminUserName() + Constants.ApplicationInstall.AT + tenantDomain; AccessTokenInfo tokenInfo = OAuthUtils.getOAuthCredentials(apiApplicationKey, username); - request.addRequestHeader(Constants.ApplicationInstall.AUTHORIZATION, + request.addHeader(Constants.ApplicationInstall.AUTHORIZATION, Constants.ApplicationInstall.AUTHORIZATION_HEADER_VALUE + tokenInfo.getAccessToken()); - httpClient = new HttpClient(); - httpClient.executeMethod(request); - return request.getStatusCode(); + HttpResponse response = httpClient.execute(request); + return response.getStatusLine().getStatusCode(); } public int installEnrollmentApplications(ApplicationPolicyDTO applicationPolicyDTO) throws ApplicationManagementException { - - PostMethod request; + String requestUrl =null; try { - String requestUrl = Constants.ApplicationInstall.ENROLLMENT_APP_INSTALL_PROTOCOL + System - .getProperty(Constants.ApplicationInstall.IOT_CORE_HOST) + Constants.ApplicationInstall.COLON + requestUrl = Constants.ApplicationInstall.ENROLLMENT_APP_INSTALL_PROTOCOL + System + .getProperty(Constants.ApplicationInstall.IOT_GATEWAY_HOST) + Constants.ApplicationInstall.COLON + System.getProperty(Constants.ApplicationInstall.IOT_CORE_PORT) + Constants.ApplicationInstall.GOOGLE_APP_INSTALL_URL; Gson gson = new Gson(); String payload = gson.toJson(applicationPolicyDTO); + HttpPost httpPost = new HttpPost(requestUrl); - StringRequestEntity requestEntity = new StringRequestEntity(payload, MediaType.APPLICATION_JSON, - Constants.ApplicationInstall.ENCODING); - request = new PostMethod(requestUrl); - request.setRequestEntity(requestEntity); - return invokeIOTCoreAPI(request); + StringEntity stringEntity = new StringEntity(payload, Constants.ApplicationInstall.ENCODING); + httpPost.addHeader("Content-Type",MediaType.APPLICATION_JSON); + httpPost.setEntity(stringEntity); + return invokeIOTCoreAPI(httpPost); } catch (UserStoreException e) { String msg = "Error while accessing user store for user with Android device."; log.error(msg, e); @@ -1308,18 +1370,38 @@ public class SubscriptionManagerImpl implements SubscriptionManager { String msg = "Error while retrieving access token for Android device"; log.error(msg, e); throw new ApplicationManagementException(msg, e); - } catch (HttpException e) { - String msg = "Error while calling the app store to install enrollment app with id: " + applicationPolicyDTO - .getApplicationDTO().getId() + " on device"; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); } catch (IOException e) { String msg = "Error while installing the enrollment with id: " + applicationPolicyDTO.getApplicationDTO().getId() - + " on device"; + + " on device: request URL: " + requestUrl; + log.error(msg + "request url: " + requestUrl, e); + throw new ApplicationManagementException(msg, e); + } + } + + private CloseableHttpClient getHttpClient() throws ApplicationManagementException { + try { + SSLContextBuilder builder = new SSLContextBuilder(); + builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); + return HttpClients.custom().setSSLSocketFactory(sslsf).useSystemProperties().build(); + } catch (NoSuchAlgorithmException e) { + String msg = "Failed while building the http client for EntApp installation. " + + "Used SSL algorithm not available"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (KeyStoreException e) { + String msg = "Failed while building the http client for EntApp installation. " + + "Failed to load required key stores"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (KeyManagementException e) { + String msg = "Failed while building the http client for EntApp installation. " + + "Failed while building SSL context"; log.error(msg, e); throw new ApplicationManagementException(msg, e); } + } private String getIOTCoreBaseUrl() { @@ -1594,4 +1676,29 @@ public class SubscriptionManagerImpl implements SubscriptionManager { ConnectionManagerUtil.closeDBConnection(); } } + + @Override + public Activity getOperationAppDetails(String id) throws SubscriptionManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + int operationId = Integer.parseInt( + id.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, "")); + if (operationId == 0) { + throw new IllegalArgumentException("Operation ID cannot be null or zero (0)."); + } + try { + ConnectionManagerUtil.openDBConnection(); + return subscriptionDAO.getOperationAppDetails(operationId, tenantId); + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while retrieving app details of operation: " + operationId; + log.error(msg, e); + throw new SubscriptionManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection"; + log.error(msg, e); + throw new SubscriptionManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/VppApplicationManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/VppApplicationManagerImpl.java new file mode 100644 index 0000000000..dc9b34e40d --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/VppApplicationManagerImpl.java @@ -0,0 +1,610 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.core.impl; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import io.entgra.device.mgt.core.application.mgt.common.DepConfig; +import io.entgra.device.mgt.core.application.mgt.common.dto.ItuneAppDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssociationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.response.Application; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; +import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; +import io.entgra.device.mgt.core.application.mgt.common.exception.TransactionManagementException; +import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppAssociateRequestWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneAssetResponseWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserRequestWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserResponseWrapper; +import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationDAO; +import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; +import io.entgra.device.mgt.core.application.mgt.core.dao.VisibilityDAO; +import io.entgra.device.mgt.core.application.mgt.core.dao.VppApplicationDAO; +import io.entgra.device.mgt.core.application.mgt.core.dao.common.ApplicationManagementDAOFactory; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder; +import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; +import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagementUtil; +import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil; +import io.entgra.device.mgt.core.application.mgt.core.util.Constants; +import io.entgra.device.mgt.core.application.mgt.core.util.VppHttpUtil; +import io.entgra.device.mgt.core.application.mgt.core.util.APIUtil; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; +import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; +import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpStatus; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class VppApplicationManagerImpl implements VPPApplicationManager { + private static final String APP_API = "https://vpp.itunes.apple.com/mdm/v2"; + private static final String ASSETS = APP_API + "/assets"; + private static final String USER_CREATE = APP_API + "/users/create"; + private static final String USER_UPDATE = APP_API + "/users/update"; + private static final String USER_GET = APP_API + "/users"; + private static final String ASSIGNMENTS_POST = APP_API + "/assets/associate"; + private static final String ASSIGNMENTS_GET = APP_API + "/assignments"; + private static final String TOKEN = ""; + private static final String LOOKUP_API = "https://uclient-api.itunes.apple" + + ".com/WebObjects/MZStorePlatform.woa/wa/lookup?version=2&id="; + private static final String LOOKUP_API_PREFIX = + "&p=mdm-lockup&caller=MDM&platform=enterprisestore&cc=us&l=en"; + + + private static final Log log = LogFactory.getLog(VppApplicationManagerImpl.class); + + private ApplicationDAO applicationDAO; + private SPApplicationDAO spApplicationDAO; + private VisibilityDAO visibilityDAO; + private final LifecycleStateManager lifecycleStateManager; + private VppApplicationDAO vppApplicationDAO; + + public VppApplicationManagerImpl() { + initDataAccessObjects(); + lifecycleStateManager = DataHolder.getInstance().getLifecycleStateManager(); + } + + private void initDataAccessObjects() { + this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO(); + this.visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO(); + this.spApplicationDAO = ApplicationManagementDAOFactory.getSPApplicationDAO(); + this.vppApplicationDAO = ApplicationManagementDAOFactory.getVppApplicationDAO(); + } + + @Override + public VppUserDTO addUser(VppUserDTO userDTO) throws ApplicationManagementException { + + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + + // Call the API to add + try { + VppItuneUserDTO ituneUserDTO = userDTO; + VppItuneUserRequestWrapper wrapper = new VppItuneUserRequestWrapper(); + wrapper.getUser().add(ituneUserDTO); + + Gson gson = new Gson(); + String userPayload = gson.toJson(wrapper); + + ProxyResponse proxyResponse = callVPPBackend(USER_CREATE, userPayload, getVppToken(), Constants.VPP.POST); + if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == + HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.EVENT_ID)) { + // Create user does not return any useful data. Its needed to call the backend again + ProxyResponse getUserResponse = callVPPBackend(USER_GET + Constants.VPP.CLIENT_USER_ID_PARAM + + userDTO.getClientUserId(), userPayload, getVppToken(), Constants.VPP.GET); + if ((getUserResponse.getCode() == HttpStatus.SC_OK || getUserResponse.getCode() == + HttpStatus.SC_CREATED) && getUserResponse.getData().contains(Constants.VPP.TOTAL_PAGES)) { + VppItuneUserResponseWrapper vppItuneUserResponseWrapper = gson.fromJson + (getUserResponse.getData(), VppItuneUserResponseWrapper.class); + userDTO.setInviteCode(vppItuneUserResponseWrapper.getUser().get(0) + .getInviteCode()); + userDTO.setStatus(vppItuneUserResponseWrapper.getUser().get(0).getStatus()); + log.error("userDTO " + userDTO.toString()); + try { + ConnectionManagerUtil.beginDBTransaction(); + int id = vppApplicationDAO.addVppUser(userDTO, tenantId); + if (id != -1) { + ConnectionManagerUtil.commitDBTransaction(); + userDTO.setId(id); + userDTO.setTenantId(PrivilegedCarbonContext + .getThreadLocalCarbonContext().getTenantId()); + return userDTO; + } + ConnectionManagerUtil.rollbackDBTransaction(); + return null; + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while adding the Vpp User."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while executing database transaction for adding Vpp User."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection for adding Vpp User."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + } + } catch (IOException e) { + String msg = "Error while calling VPP backend to add user"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + return null; + } + + @Override + public VppUserDTO getUserByDMUsername(String emmUsername) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + try { + ConnectionManagerUtil.openDBConnection(); + return vppApplicationDAO.getUserByDMUsername(emmUsername, tenantId); + } catch (DBConnectionException e) { + String msg = "DB Connection error occurs while getting vpp User data related to EMM user " + emmUsername + "."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while getting vpp User data related to EMM user " + emmUsername + "."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public void updateUser(VppUserDTO userDTO) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + VppItuneUserDTO ituneUserDTO = userDTO; + VppItuneUserRequestWrapper wrapper = new VppItuneUserRequestWrapper(); + wrapper.getUser().add(ituneUserDTO); + + Gson gson = new Gson(); + String userPayload = gson.toJson(wrapper); + try { + ProxyResponse proxyResponse = callVPPBackend(USER_UPDATE, userPayload, getVppToken(), Constants.VPP.POST); + if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == + HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.EVENT_ID)) { + VppUserDTO currentUserDTO = getUserByDMUsername(userDTO.getDmUsername()); + if (currentUserDTO != null) { + userDTO.setId(currentUserDTO.getId()); + } + try { + ConnectionManagerUtil.beginDBTransaction(); + if (vppApplicationDAO.updateVppUser(userDTO, tenantId) == null) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Unable to update the Vpp user " +userDTO.getId(); + log.error(msg); + throw new ApplicationManagementException(msg); + } + ConnectionManagerUtil.commitDBTransaction(); + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while updating the Vpp User."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while executing database transaction for Vpp User update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection for Vpp User update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + } catch (IOException e) { + String msg = "Error while calling VPP backend to update"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + } + + @Override + public void syncUsers(String clientId) throws ApplicationManagementException { + ProxyResponse proxyResponse = null; + try { + proxyResponse = callVPPBackend(USER_GET, null, getVppToken(), Constants + .VPP.GET); + if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == + HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.TOTAL_PAGES)) { + log.error("proxyResponse " + proxyResponse.getData()); + Gson gson = new Gson(); + VppItuneUserResponseWrapper vppUserResponseWrapper = gson.fromJson + (proxyResponse.getData(), VppItuneUserResponseWrapper.class); + // TODO: to implement later + } + } catch (IOException e) { + String msg = "Error while syncing VPP users with backend"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + + } + + @Override + public void syncAssets(int nextPageIndex) throws ApplicationManagementException { + ProxyResponse proxyResponse = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + try { + String url = ASSETS; + if (nextPageIndex > 0) { // Not the first page + url += "?pageIndex=" + nextPageIndex; + } + proxyResponse = callVPPBackend(url, null, getVppToken(), Constants.VPP.GET); + if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == + HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.TOTAL_PAGES)) { + Gson gson = new Gson(); + VppItuneAssetResponseWrapper vppItuneAssetResponse = gson.fromJson + (proxyResponse.getData(), VppItuneAssetResponseWrapper.class); + if (vppItuneAssetResponse.getSize() > 0) { + for (VppAssetDTO vppAssetDTO : vppItuneAssetResponse.getAssets()) { + vppAssetDTO.setTenantId(PrivilegedCarbonContext + .getThreadLocalCarbonContext().getTenantId()); + vppAssetDTO.setCreatedTime(String.valueOf(System.currentTimeMillis())); + vppAssetDTO.setLastUpdatedTime(String.valueOf(System.currentTimeMillis())); + } + + for (VppAssetDTO vppAssetDTO : vppItuneAssetResponse.getAssets()) { + ItuneAppDTO ituneAppDTO = lookupAsset(vppAssetDTO.getAdamId()); + ApplicationManagementUtil.persistApp(ituneAppDTO); + List applications = ApplicationManagementUtil.getAppDetails(vppAssetDTO.getAdamId()); + for (Application application :applications) { + VppAssetDTO vppAssetDTOs = getAssetByAppId(application.getId()); + if (vppAssetDTOs == null) { + vppAssetDTOs = new VppAssetDTO(); + vppAssetDTO.setAppId(application.getId()); + try { + ConnectionManagerUtil.beginDBTransaction(); + if (vppApplicationDAO.addAsset(vppAssetDTO, tenantId) != -1) { + ConnectionManagerUtil.commitDBTransaction(); + } + ConnectionManagerUtil.rollbackDBTransaction(); + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while adding the Asset."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while executing database transaction for adding Asset."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection for adding Asset."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } else { + vppAssetDTOs.setAppId(application.getId()); + vppAssetDTOs.setSupportedPlatforms(vppAssetDTO.getSupportedPlatforms()); + try { + ConnectionManagerUtil.beginDBTransaction(); + if (vppApplicationDAO.updateAsset(vppAssetDTOs, tenantId) == null) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Unable to update the asset: " +vppAssetDTOs.getAdamId(); + log.error(msg); + throw new ApplicationManagementException(msg); + } + ConnectionManagerUtil.commitDBTransaction(); + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while updating the Asset."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while executing database transaction for Asset update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection for Asset update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + } + } + } + + if (vppItuneAssetResponse.getCurrentPageIndex() == (vppItuneAssetResponse + .getTotalPages() - 1)) { + return; + } else { + syncAssets(vppItuneAssetResponse.getNextPageIndex()); + } + } + } catch (IOException e) { + String msg = "Error while syncing VPP users with backend"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + } + + private ItuneAppDTO lookupAsset(String packageName) throws ApplicationManagementException { + String lookupURL = LOOKUP_API + packageName + LOOKUP_API_PREFIX; + try { + ProxyResponse proxyResponse = callVPPBackend(lookupURL, null, getVppToken(), Constants.VPP.GET); + if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == + HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.GET_APP_DATA_RESPONSE_START)) { + String responseData = proxyResponse.getData(); + JsonObject responseJson = new JsonParser().parse(responseData) + .getAsJsonObject(); + + JsonObject results = responseJson.getAsJsonObject(Constants.ApplicationProperties.RESULTS); + JsonObject result = results.getAsJsonObject(packageName); + + String iconUrl = result.getAsJsonObject(Constants.ApplicationProperties.ARTWORK) + .get(Constants.ApplicationProperties.URL).getAsString(); + int lastSlashIndex = iconUrl.lastIndexOf("/"); + if (lastSlashIndex != -1) { + iconUrl = iconUrl.substring(0, lastSlashIndex + 1) + Constants.VPP.REMOTE_FILE_NAME; + } + + String descriptionStandard = result.getAsJsonObject(Constants.ApplicationProperties.DESCRIPTION) + .get(Constants.ApplicationProperties.STANDARD).getAsString(); + if (descriptionStandard != null && !descriptionStandard.isEmpty()) { + descriptionStandard = descriptionStandard.substring(0, 199); + } + String name = result.get(Constants.ApplicationProperties.NAME).getAsString(); + double price = result.getAsJsonArray(Constants.ApplicationProperties.OFFERS).get(0) + .getAsJsonObject().get(Constants.ApplicationProperties.PRICE).getAsDouble(); + String version = result.getAsJsonArray(Constants.ApplicationProperties.OFFERS) + .get(0).getAsJsonObject().get(Constants.ApplicationProperties.VERSION) + .getAsJsonObject().get(Constants.ApplicationProperties.DISPLAY).getAsString(); + + String[] genreNames = new Gson().fromJson(result.getAsJsonArray(Constants.ApplicationProperties.GENRE_NAMES), + String[].class); + + ItuneAppDTO ituneAppDTO = new ItuneAppDTO(); + ituneAppDTO.setPackageName(packageName); + ituneAppDTO.setVersion(version); + ituneAppDTO.setDescription(descriptionStandard); + ituneAppDTO.setTitle(name); + + if (Constants.ApplicationProperties.PRICE_ZERO.equalsIgnoreCase(String.valueOf(price))) { + ituneAppDTO.setPaymentMethod(Constants.ApplicationProperties.FREE_SUB_METHOD); + } else { + ituneAppDTO.setPaymentMethod(Constants.ApplicationProperties.PAID_SUB_METHOD); + } + ituneAppDTO.setIconURL(iconUrl); + ituneAppDTO.setCategory(genreNames[0]); + + return ituneAppDTO; + } + } catch (IOException e) { + String msg = "Error while looking up the app details"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + return null; + } + + @Override + public VppAssetDTO getAssetByAppId(int appId) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + try { + ConnectionManagerUtil.openDBConnection(); + return vppApplicationDAO.getAssetByAppId(appId, tenantId); + } catch (DBConnectionException e) { + String msg = "DB Connection error occurs while getting asset related to app with app id " + appId + "."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while getting asset data related to app with app id " + appId + "."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public boolean addAssociation(VppAssetDTO asset, List vppUsers) throws + ApplicationManagementException { + + List associations = new ArrayList<>(); // To save to UEM DBs + List clientUserIds = new ArrayList<>(); // Need this to send to vpp backend. + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + if (asset != null) { + for (VppUserDTO vppUserDTO : vppUsers) { + VppAssociationDTO associationDTO = VppHttpUtil.getAssociation(vppUserDTO, asset); + associations.add(associationDTO); + clientUserIds.add(vppUserDTO.getClientUserId()); + } + + if (associations.size() > 0) { + //TODO: Add or Update associations + try { + + // Create the VPP backend payload + List assets = new ArrayList<>(); + VppItuneAssetDTO assetDTO = new VppItuneAssetDTO(); + assetDTO.setAdamId(asset.getAdamId()); + assetDTO.setPricingParam(asset.getPricingParam()); + assets.add(assetDTO); + + VppAssociateRequestWrapper vppAssociate = new VppAssociateRequestWrapper(); + vppAssociate.setAssets(assets); + vppAssociate.setClientUserIds(clientUserIds); + + Gson gson = new Gson(); + String payload = gson.toJson(vppAssociate); + + ProxyResponse proxyResponse = callVPPBackend(ASSIGNMENTS_POST, payload, getVppToken(), + Constants.VPP.POST); + if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == + HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.EVENT_ID)) { + // Create assignment does not return any useful data. Its needed to call the backend again + ProxyResponse getAssignmentResponse = callVPPBackend(ASSIGNMENTS_GET, null, getVppToken(), Constants.VPP.GET); + if ((getAssignmentResponse.getCode() == HttpStatus.SC_OK || getAssignmentResponse.getCode() == + HttpStatus.SC_CREATED) && getAssignmentResponse.getData().contains(Constants.VPP.TOTAL_PAGES)) { +// VppAssociateResponseWrapper vppAssociateResponseWrapper = gson.fromJson +// (getAssignmentResponse.getData(), VppAssociateResponseWrapper.class); + for (VppAssociationDTO association : associations) { + + VppAssociationDTO vppAssociation = getAssociation(association.getAssetId(), association.getClientId()); + + if (vppAssociation == null) { + try { + ConnectionManagerUtil.beginDBTransaction(); + if (vppApplicationDAO.addAssociation(association, tenantId) != -1) { + ConnectionManagerUtil.commitDBTransaction(); + return true; + } + ConnectionManagerUtil.rollbackDBTransaction(); + return false; + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while adding the Assignment."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while executing database transaction for adding Assignment."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection for adding Assignment."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } else { + try { + ConnectionManagerUtil.beginDBTransaction(); + if (vppApplicationDAO.updateAssociation(association, tenantId) == null) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Unable to update the assignment: " +association.getAssetId(); + log.error(msg); + throw new ApplicationManagementException(msg); + } + ConnectionManagerUtil.commitDBTransaction(); + return true; + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while updating the Asset."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while executing database transaction for Asset update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection for Asset update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + } + } + + } + + } catch (IOException e) { + String msg = "Error while adding associations"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + } + + } + + return false; + } + + @Override + public VppAssociationDTO getAssociation(int assetId, int userId) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + try { + ConnectionManagerUtil.openDBConnection(); + return vppApplicationDAO.getAssociation(assetId, userId, tenantId); + } catch (DBConnectionException e) { + String msg = "DB Connection error occurs while getting assignment related to user of id " + userId + "."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while getting assignment data related to user of id " + userId + "."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public ProxyResponse callVPPBackend(String url, + String payload, + String accessToken, + String method) throws IOException { + return VppHttpUtil.execute(url, payload, accessToken, method); + } + + public String getVppToken() throws ApplicationManagementException { + String token = ""; + MetadataManagementService meta = APIUtil.getMetadataManager(); + Metadata metadata = null; + try { + metadata = meta.retrieveMetadata("DEP_META_KEY"); + if (metadata != null) { + + Gson g = new Gson(); + DepConfig depConfigs = g.fromJson(metadata.getMetaValue(), DepConfig.class); + token = depConfigs.getVppToken(); + return token; + } + }catch (MetadataManagementException e) { + String msg = "Error when retrieving metadata of vpp feature"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + return token; + } + + public VppAssociationDTO getUserAssociation(String adamId, String emmUsername) throws ApplicationManagementException { + // Todo: Join the 3 tables and find a matching association + return null; + } + +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java index 91ea87f66f..151240e3c0 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java @@ -18,6 +18,13 @@ package io.entgra.device.mgt.core.application.mgt.core.internal; import io.entgra.device.mgt.core.application.mgt.common.config.LifecycleState; +import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationStorageManager; +import io.entgra.device.mgt.core.application.mgt.common.services.AppmDataHandler; +import io.entgra.device.mgt.core.application.mgt.common.services.ReviewManager; +import io.entgra.device.mgt.core.application.mgt.common.services.SPApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; +import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.*; import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; import io.entgra.device.mgt.core.application.mgt.core.dao.common.ApplicationManagementDAOFactory; @@ -89,6 +96,12 @@ public class ApplicationManagementServiceComponent { DataHolder.getInstance().setConfigManager(configManager); bundleContext.registerService(AppmDataHandler.class.getName(), configManager, null); + // TODO: Get the new instance from extension like others + VPPApplicationManager vppApplicationManager = ApplicationManagementUtil + .getVPPManagerInstance(); + DataHolder.getInstance().setVppApplicationManager(vppApplicationManager); + bundleContext.registerService(VPPApplicationManager.class.getName(), vppApplicationManager, null); + ScheduledAppSubscriptionTaskManager taskManager = new ScheduledAppSubscriptionTaskManager(); // todo: taskManager.scheduleCleanupTask(); diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java index 2484822e7c..bc770ead5e 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java @@ -17,6 +17,13 @@ */ package io.entgra.device.mgt.core.application.mgt.core.internal; +import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationStorageManager; +import io.entgra.device.mgt.core.application.mgt.common.services.AppmDataHandler; +import io.entgra.device.mgt.core.application.mgt.common.services.SPApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.services.ReviewManager; +import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; +import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.*; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; @@ -34,6 +41,8 @@ public class DataHolder { private SPApplicationManager SPApplicationManager; + private VPPApplicationManager vppApplicationManager; + private ApplicationManager applicationManager; private ReviewManager reviewManager; @@ -137,4 +146,12 @@ public class DataHolder { public void setISApplicationManager(SPApplicationManager SPApplicationManager) { this.SPApplicationManager = SPApplicationManager; } + + public VPPApplicationManager getVppApplicationManager() { + return vppApplicationManager; + } + + public void setVppApplicationManager(VPPApplicationManager vppApplicationManager) { + this.vppApplicationManager = vppApplicationManager; + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/APIUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/APIUtil.java index bad2cc2926..67938483a0 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/APIUtil.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/APIUtil.java @@ -65,6 +65,7 @@ public class APIUtil { private static volatile SubscriptionManager subscriptionManager; private static volatile ReviewManager reviewManager; private static volatile AppmDataHandler appmDataHandler; + private static volatile VPPApplicationManager vppApplicationManager; private static volatile MetadataManagementService metadataManagementService; public static SPApplicationManager getSPApplicationManager() { @@ -107,6 +108,24 @@ public class APIUtil { return applicationManager; } + public static MetadataManagementService getMetadataManager() { + if (metadataManagementService == null) { + synchronized (APIUtil.class) { + if (metadataManagementService == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + metadataManagementService = + (MetadataManagementService) ctx.getOSGiService(MetadataManagementService.class, null); + if (metadataManagementService == null) { + String msg = "MetadataManagement Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + } + } + return metadataManagementService; + } + /** * To get the ApplicationDTO Storage Manager from the osgi context. * @return ApplicationStoreManager instance in the current osgi context. @@ -195,6 +214,29 @@ public class APIUtil { return reviewManager; } + public static VPPApplicationManager getVPPManager() { + try { + if (vppApplicationManager == null) { + synchronized (APIUtil.class) { + if (vppApplicationManager == null) { + vppApplicationManager = ApplicationManagementUtil.getVPPManagerInstance(); + if (vppApplicationManager == null) { + String msg = "Vpp Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + } + } + } catch (Exception e) { + String msg = "Error occurred while getting the vpp manager"; + log.error(msg); + throw new IllegalStateException(msg); + } + return vppApplicationManager; + } + + /** * To get the DataHandler from the osgi context. * @return AppmDataHandler instance in the current osgi context. @@ -419,9 +461,13 @@ public class APIUtil { } List applicationReleases = new ArrayList<>(); if (ApplicationType.PUBLIC.toString().equals(applicationDTO.getType()) && application.getCategories() - .contains("GooglePlaySyncedApp")) { + .contains(Constants.GOOGLE_PLAY_SYNCED_APP)) { application.setAndroidEnterpriseApp(true); } + if (ApplicationType.PUBLIC.toString().equals(applicationDTO.getType()) && application.getCategories() + .contains(Constants.ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY)) { + application.setExternalAppStoreApp(true); + } for (ApplicationReleaseDTO applicationReleaseDTO : applicationDTO.getApplicationReleaseDTOs()) { applicationReleases.add(releaseDtoToRelease(applicationReleaseDTO)); } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java index 4800743abc..671dfdf84f 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java @@ -19,24 +19,64 @@ package io.entgra.device.mgt.core.application.mgt.core.util; import io.entgra.device.mgt.core.application.mgt.common.ApplicationArtifact; import io.entgra.device.mgt.core.application.mgt.common.FileDataHolder; +import io.entgra.device.mgt.core.application.mgt.common.LifecycleChanger; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.ItuneAppDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.InvalidConfigurationException; import io.entgra.device.mgt.core.application.mgt.common.exception.RequestValidatingException; -import io.entgra.device.mgt.core.application.mgt.common.services.*; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.*; +import io.entgra.device.mgt.core.application.mgt.common.response.Application; +import io.entgra.device.mgt.core.application.mgt.common.response.Category; +import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationStorageManager; +import io.entgra.device.mgt.core.application.mgt.common.services.ReviewManager; +import io.entgra.device.mgt.core.application.mgt.common.services.SPApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; +import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationUpdateWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.CustomAppReleaseWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.CustomAppWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.EntAppReleaseWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.PublicAppReleaseWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.PublicAppWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.WebAppReleaseWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.WebAppWrapper; import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; import io.entgra.device.mgt.core.application.mgt.core.config.Extension; import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; +import io.entgra.device.mgt.core.application.mgt.core.impl.VppApplicationManagerImpl; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; import io.entgra.device.mgt.core.device.mgt.common.Base64File; +import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import io.entgra.device.mgt.core.device.mgt.core.common.util.FileUtil; +import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.MetadataManagementServiceImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import io.entgra.device.mgt.core.application.mgt.common.services.*; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.*; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; -import java.util.*; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; /** * This DAOUtil class is responsible for making sure single instance of each Extension Manager is used throughout for @@ -168,6 +208,10 @@ public class ApplicationManagementUtil { return getInstance(extension, LifecycleStateManager.class); } + public static VPPApplicationManager getVPPManagerInstance() { + // TODO: implement as an extension + return new VppApplicationManagerImpl(); + } /** * This is useful to delete application artifacts if any error occurred while creating release/application * after uploading the artifacts @@ -232,4 +276,265 @@ public class ApplicationManagementUtil { throw new InvalidConfigurationException(msg, e); } } + + public static void persistApp(ItuneAppDTO product) throws ApplicationManagementException { + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + List categories = applicationManager.getRegisteredCategories(); + if (product != null && product.getVersion() != null) { + // Generate artifacts + ApplicationArtifact applicationArtifact = generateArtifacts(product); + + List packageNamesOfApps = new ArrayList<>(); + packageNamesOfApps.add(product.getPackageName()); + + List existingApps = applicationManager.getApplications(packageNamesOfApps); + + if (existingApps != null && existingApps.size() > 0) { + Application app = existingApps.get(0); + if (product.getPackageName().equals(app.getPackageName())) { + ApplicationUpdateWrapper applicationUpdateWrapper = generatePubAppUpdateWrapper(product, categories); + applicationManager.updateApplication(app.getId(), applicationUpdateWrapper); + + PublicAppReleaseWrapper publicAppReleaseWrapper = new PublicAppReleaseWrapper(); + if (app.getSubMethod() + .equalsIgnoreCase(Constants.ApplicationProperties.FREE_SUB_METHOD)) { + publicAppReleaseWrapper.setPrice(0.0); + } else { + publicAppReleaseWrapper.setPrice(1.0); + } + + publicAppReleaseWrapper.setDescription(product.getDescription()); + publicAppReleaseWrapper.setReleaseType("ga"); + publicAppReleaseWrapper.setVersion(product.getVersion()); + publicAppReleaseWrapper.setSupportedOsVersions("4.0-12.3"); + applicationManager.updatePubAppRelease(app.getApplicationReleases().get(0).getUuid(), + publicAppReleaseWrapper, applicationArtifact); + return; + } + } else { + + // Generate App wrapper + PublicAppWrapper publicAppWrapper = generatePubAppWrapper(product, categories); + PublicAppReleaseWrapper appReleaseWrapper = new PublicAppReleaseWrapper(); + + if (publicAppWrapper.getSubMethod() + .equalsIgnoreCase(Constants.ApplicationProperties.FREE_SUB_METHOD)) { + appReleaseWrapper.setPrice(0.0); + } else { + appReleaseWrapper.setPrice(1.0); + } + + appReleaseWrapper.setDescription(product.getDescription()); + appReleaseWrapper.setReleaseType("ga"); + appReleaseWrapper.setVersion(product.getVersion()); + appReleaseWrapper.setPackageName(product.getPackageName()); + appReleaseWrapper.setSupportedOsVersions("4.0-12.3"); + + publicAppWrapper.setPublicAppReleaseWrappers( + Arrays.asList(new PublicAppReleaseWrapper[]{appReleaseWrapper})); + + try { + updateImages(appReleaseWrapper, applicationArtifact.getIconName(), + applicationArtifact.getIconStream(), applicationArtifact.getScreenshots()); + + Application application = applicationManager.createApplication(publicAppWrapper, false); + if (application != null && (application.getApplicationReleases().get(0).getCurrentStatus() == null + || application.getApplicationReleases().get(0).getCurrentStatus().equals("CREATED"))) { + String uuid = application.getApplicationReleases().get(0).getUuid(); + LifecycleChanger lifecycleChanger = new LifecycleChanger(); + lifecycleChanger.setAction("IN-REVIEW"); + applicationManager.changeLifecycleState(uuid, lifecycleChanger); + lifecycleChanger.setAction("APPROVED"); + applicationManager.changeLifecycleState(uuid, lifecycleChanger); + lifecycleChanger.setAction("PUBLISHED"); + applicationManager.changeLifecycleState(uuid, lifecycleChanger); + } + } catch (IOException e) { + String msg = "Error while downloading images of release."; + log.error(msg); + throw new ApplicationManagementException(msg, e); + } + } + } + } + + private static PublicAppWrapper generatePubAppWrapper(ItuneAppDTO product, List categories) { + PublicAppWrapper publicAppWrapper = new PublicAppWrapper(); + publicAppWrapper.setName(product.getTitle()); + publicAppWrapper.setDescription(product.getDescription()); + publicAppWrapper.setCategories( + Collections.singletonList(Constants.ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY));//Default category + for (Category category : categories) { + if (product.getCategory() == null) { + List pubAppCategories = new ArrayList<>(); + pubAppCategories.add(Constants.ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY); + publicAppWrapper.setCategories(pubAppCategories); + break; + } else if (product.getCategory().equalsIgnoreCase(category.getCategoryName())) { + List pubAppCategories = new ArrayList<>(); + pubAppCategories.add(category.getCategoryName()); + pubAppCategories.add(Constants.ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY); + publicAppWrapper.setCategories(pubAppCategories); + break; + } + } + if (product.getPaymentMethod().equalsIgnoreCase(Constants.ApplicationProperties.FREE_SUB_METHOD)) { + publicAppWrapper.setSubMethod(Constants.ApplicationProperties.FREE_SUB_METHOD); + } else { + publicAppWrapper.setSubMethod(Constants.ApplicationProperties.PAID_SUB_METHOD); + } + // TODO: purchase an app from app store and see how to capture the real value for price + // field. + publicAppWrapper.setPaymentCurrency("$"); + publicAppWrapper.setDeviceType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS); + return publicAppWrapper; + } + + private static ApplicationUpdateWrapper generatePubAppUpdateWrapper(ItuneAppDTO product, List categories) { + ApplicationUpdateWrapper applicationUpdateWrapper = new ApplicationUpdateWrapper(); + applicationUpdateWrapper.setName(product.getTitle()); + applicationUpdateWrapper.setDescription(product.getDescription()); + applicationUpdateWrapper.setCategories( + Collections.singletonList(Constants + .ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY));//Default + // add the default APPLE_STORE_SYNCED_APP_CATEGORY + for (Category category : categories) { + if (product.getCategory() == null) { + List pubAppCategories = new ArrayList<>(); + pubAppCategories.add(Constants.ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY); + applicationUpdateWrapper.setCategories(pubAppCategories); + break; + } else if (product.getCategory().equalsIgnoreCase(category.getCategoryName())) { + List pubAppCategories = new ArrayList<>(); + pubAppCategories.add(category.getCategoryName()); + pubAppCategories.add(Constants.ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY); + applicationUpdateWrapper.setCategories(pubAppCategories); + break; + } + } + if (product.getPaymentMethod().equalsIgnoreCase(Constants.ApplicationProperties.FREE_SUB_METHOD)) { + applicationUpdateWrapper.setSubMethod(Constants.ApplicationProperties.FREE_SUB_METHOD); + } else { + applicationUpdateWrapper.setSubMethod(Constants.ApplicationProperties.PAID_SUB_METHOD); + } + // TODO: purchase an app from Playstore and see how to capture the real value for price field. + applicationUpdateWrapper.setPaymentCurrency("$"); + return applicationUpdateWrapper; + } + + private static ApplicationArtifact generateArtifacts(ItuneAppDTO product) throws ApplicationManagementException { + ApplicationArtifact applicationArtifact = new ApplicationArtifact(); + String prefix = product.getPackageName(); + try { + String iconName = prefix + "_icon"; + applicationArtifact.setIconName(iconName); + InputStream iconInputStream = getInputStream(iconName, product.getIconURL()); + applicationArtifact.setIconStream(iconInputStream); + Map screenshotMap = new HashMap<>(); + // TODO: look for a way to get screenshots + + for (int a = 0; a < 3; a++) { + String screenshotName = product.getPackageName() + a; + InputStream screenshotInputStream = getInputStream(screenshotName, product.getIconURL()); + screenshotMap.put(screenshotName, screenshotInputStream); + } + + applicationArtifact.setScreenshots(screenshotMap); + return applicationArtifact; + } catch (ApplicationManagementException e) { + String msg = "Error occurred while generating Application artifact"; + log.error(msg); + throw new ApplicationManagementException(msg, e); + } + } + + private static InputStream getInputStream(String filename, String url) throws ApplicationManagementException { + URL website; + try { + website = new URL(url); + } catch (MalformedURLException e) { + String msg = "Error occurred while converting the url " + url; + log.error(msg); + throw new ApplicationManagementException(msg, e); + } + ReadableByteChannel rbc = null; + FileOutputStream fos = null; + try { + rbc = Channels.newChannel(website.openStream()); + fos = new FileOutputStream(System.getProperty("java.io.tmpdir") + + File.separator + filename); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + } catch (IOException e) { + String msg = "Error occurred while opening stream for url " + url; + log.error(msg); + throw new ApplicationManagementException(msg, e); + } finally { + try { + fos.close(); + rbc.close(); + } catch (IOException e) { + } + } + + File file = new File(System.getProperty("java.io.tmpdir") + File.separator + filename); + InputStream targetStream; + try { + targetStream = new FileInputStream(file); + } catch (FileNotFoundException e) { + String msg = "Error occurred while reading the tmp file " + System.getProperty("java.io.tmpdir") + + File.separator + filename; + log.error(msg); + throw new ApplicationManagementException(msg, e); + } + file.deleteOnExit(); + return targetStream; + } + + private static void updateImages(PublicAppReleaseWrapper appReleaseWrapper, String iconName, + InputStream iconStream, Map + screenshotsMaps) throws IOException { + List screenshots = new ArrayList<>(); + Base64File iconFile = new Base64File(iconName, + convertStreamToBase64(iconStream)); + appReleaseWrapper.setIcon(iconFile); + if (screenshotsMaps.size() > 0) { + for (Map.Entry screenshotEntry : screenshotsMaps.entrySet()) { + Base64File screenshot = new Base64File(screenshotEntry.getKey(), + convertStreamToBase64(screenshotEntry.getValue())); + screenshots.add(screenshot); + } + appReleaseWrapper.setScreenshots(screenshots); + } + } + + private static String convertStreamToBase64(InputStream inputStream) throws IOException { + final int bufLen = 4 * 0x400; // 4KB + byte[] buf = new byte[bufLen]; + int readLen; + + try { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + while ((readLen = inputStream.read(buf, 0, bufLen)) != -1) + outputStream.write(buf, 0, readLen); + + return Base64.getEncoder().encodeToString(outputStream.toByteArray()); + } + } catch (IOException e) { + String msg = "Error while converting image to base64"; + log.error(msg); + throw e; + } finally { + try { + inputStream.close(); + } catch (IOException e) { + } + } + } + + public static List getAppDetails(String adamId) throws ApplicationManagementException { + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + List packageNamesOfApps = new ArrayList<>(); + packageNamesOfApps.add(adamId); + return applicationManager.getApplications(packageNamesOfApps); + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java index c3e7c49160..40774c0486 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java @@ -74,6 +74,7 @@ public class Constants { public static final String IS_USER_ABLE_TO_VIEW_ALL_ROLES = "isUserAbleToViewAllRoles"; public static final String GOOGLE_PLAY_STORE_URL = "https://play.google.com/store/apps/details?id="; public static final String APPLE_STORE_URL = "https://itunes.apple.com/country/app/app-name/id"; + public static final String GOOGLE_PLAY_SYNCED_APP = "GooglePlaySyncedApp"; // Subscription task related constants public static final String SUBSCRIBERS = "SUBSCRIBERS"; @@ -104,6 +105,25 @@ public class Constants { } public static final Map AGENT_FILE_NAMES = Collections.unmodifiableMap(AGENT_DATA); + public static final class VPP { + public static final String GET = "GET"; + public static final String BEARER = "Bearer "; + public static final String EXECUTOR_EXCEPTION_PREFIX = "ExecutorException-"; + public static final String TOKEN_IS_EXPIRED = "ACCESS_TOKEN_IS_EXPIRED"; + public static final int INTERNAL_ERROR_CODE = 500; + public static final String POST = "POST"; + public static final String PUT = "PUT"; + public static final String DELETE = "DELETE"; + public static final String EVENT_ID = "eventId"; + public static final String CLIENT_USER_ID_PARAM = "?clientUserId="; + public static final String TOTAL_PAGES = "totalPages"; + public static final String GET_APP_DATA_RESPONSE_START = "results"; + public static final String REMOTE_FILE_NAME = "512x512w.png"; + + private VPP() { + } + } + /** * Database types supported by Application Management. @@ -161,6 +181,8 @@ public class Constants { public static final String DEVICE_TYPE_ANDROID = "android"; public static final String COLON = ":"; public static final String IOT_CORE_HOST = "iot.core.host"; + + public static final String IOT_GATEWAY_HOST = "iot.gateway.host"; public static final String IOT_CORE_PORT = "iot.core.https.port"; public static final String ENROLLMENT_APP_INSTALL_PROTOCOL = "https://"; public static final String GOOGLE_APP_INSTALL_URL = "/api/device-mgt/android/v1.0/enterprise/change-app"; @@ -168,4 +190,31 @@ public class Constants { public static final String AUTHORIZATION = "Authorization"; public static final String AUTHORIZATION_HEADER_VALUE = "Bearer "; } + + public final class ApplicationProperties { + private ApplicationProperties() { + throw new AssertionError(); + } + + public static final String NAME = "name"; + public static final String VERSION = "version"; + public static final String FREE_SUB_METHOD = "FREE"; + public static final String PAID_SUB_METHOD = "PAID"; + public static final String TYPE = "type";; + public static final String PACKAGE_NAME = "packageName"; + public static final String APPLE_STORE_SYNCED_APP_CATEGORY = "AppleStoreSyncedApp"; + + public static final String RESULTS = "results"; + public static final String ARTWORK = "artwork"; + public static final String URL = "url"; + public static final String DESCRIPTION = "description"; + public static final String STANDARD = "standard"; + public static final String OFFERS = "offers"; + public static final String PRICE = "price"; + public static final String DISPLAY = "display"; + public static final String GENRE_NAMES = "genreNames"; + public static final String PRICE_ZERO = "0.0"; + public static final String ASSOCIATION_DEVICE = "ASSOCIATION_DEVICE"; + public static final String ASSOCIATION_USER = "ASSOCIATION_USER"; + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/DAOUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/DAOUtil.java index 4f624f60c8..a41f48e1e9 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/DAOUtil.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/DAOUtil.java @@ -19,24 +19,28 @@ package io.entgra.device.mgt.core.application.mgt.core.util; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; -import io.entgra.device.mgt.core.application.mgt.common.ExecutionStatus; -import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; import io.entgra.device.mgt.core.application.mgt.common.dto.*; import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; +import io.entgra.device.mgt.core.application.mgt.common.ExecutionStatus; +import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; + +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; +import java.text.SimpleDateFormat; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Date; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -235,6 +239,26 @@ public class DAOUtil { return applicationDTOs.get(0); } + public static ApplicationDTO loadDeviceApp(ResultSet rs) throws SQLException { + ApplicationDTO application = new ApplicationDTO(); + application.setId( rs.getInt("APP_ID")); + application.setName(rs.getString("APP_NAME")); + application.setDescription(rs.getString("APP_DESCRIPTION")); + application.setType(rs.getString("APP_TYPE")); + application.setSubType(rs.getString("APP_SUB_TYPE")); + application.setPaymentCurrency(rs.getString("APP_CURRENCY")); + application.setStatus(rs.getString("APP_STATUS")); + application.setAppRating(rs.getDouble("APP_RATING")); + application.setDeviceTypeId(rs.getInt("APP_DEVICE_TYPE_ID")); + ApplicationReleaseDTO releaseDTO = constructAppReleaseDTO(rs); + List releaseDtoList = new ArrayList<>(); + if (releaseDTO != null) { + releaseDtoList.add(constructAppReleaseDTO(rs)); + application.setApplicationReleaseDTOs(releaseDtoList); + } + return application; + } + /** * Populates {@link ApplicationReleaseDTO} object with the result obtained from the database. * @@ -338,6 +362,185 @@ public class DAOUtil { return subscriptionDTOS; } + public static Activity loadOperationActivity(ResultSet rs) throws SQLException, UnexpectedServerErrorException { + List activity = loadOperationActivities(rs); + if (activity.isEmpty()) { + return null; + } + if (activity.size() > 1) { + String msg = "Internal server error. Found more than one app for operation"; + log.error(msg); + throw new UnexpectedServerErrorException(msg); + } + return activity.get(0); + } + + public static List loadOperationActivities (ResultSet rs) throws SQLException { + List activities = new ArrayList<>(); + while (rs.next()) { + Activity activity = new Activity(); + activity.setAppName(rs.getString("NAME")); + activity.setAppType(rs.getString("TYPE")); + activity.setUsername(rs.getString("SUBSCRIBED_BY")); + activity.setPackageName(rs.getString("PACKAGE_NAME")); + activity.setStatus(rs.getString("STATUS")); + activity.setVersion(rs.getString("VERSION")); + activity.setTriggeredBy(rs.getString("ACTION_TRIGGERED_FROM")); + activities.add(activity); + } + return activities; + } + + public static VppUserDTO loadVppUser(ResultSet rs) throws SQLException, UnexpectedServerErrorException { + List vppUserDTOS = loadVppUsers(rs); + if (vppUserDTOS.isEmpty()) { + return null; + } + if (vppUserDTOS.size() > 1) { + String msg = "Internal server error. Found more than one vpp user for requested emmUsername"; + log.error(msg); + throw new UnexpectedServerErrorException(msg); + } + return vppUserDTOS.get(0); + } + + public static List loadVppUsers (ResultSet rs) throws SQLException { + List vppUserDTOS = new ArrayList<>(); + while (rs.next()) { + VppUserDTO vppUserDTO = new VppUserDTO(); + vppUserDTO.setId(rs.getInt("ID")); + vppUserDTO.setClientUserId(rs.getString("CLIENT_USER_ID")); + vppUserDTO.setTenantId(rs.getInt("TENANT_ID")); + vppUserDTO.setEmail(rs.getString("EMAIL")); + vppUserDTO.setInviteCode(rs.getString("INVITE_CODE")); + if (columnExist(rs,"STATUS")) { + vppUserDTO.setStatus(rs.getString("STATUS")); + } + if (columnExist(rs,"MANAGED_ID")) { + vppUserDTO.setManagedId(rs.getString("MANAGED_ID")); + } + if (columnExist(rs,"TEMP_PASSWORD")) { + vppUserDTO.setTmpPassword(rs.getString("TEMP_PASSWORD")); + } + if (columnExist(rs,"DM_USERNAME")) { + vppUserDTO.setDmUsername(rs.getString("DM_USERNAME")); + } + if (rs.getLong("CREATED_TIME") != 0) { + Date date = new Date(rs.getLong("CREATED_TIME")); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateString = dateFormat.format(date); + vppUserDTO.setCreatedTime(dateString); + } + if (rs.getLong("LAST_UPDATED_TIME") != 0) { + Date date = new Date(rs.getLong("LAST_UPDATED_TIME")); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateString = dateFormat.format(date); + vppUserDTO.setLastUpdatedTime(dateString); + } + vppUserDTOS.add(vppUserDTO); + } + return vppUserDTOS; + } + + private static boolean columnExist(ResultSet rs, String column){ + try{ + rs.findColumn(column); + return true; + } catch (SQLException sqlex){ + } + + return false; + } + + public static VppAssetDTO loadAsset(ResultSet rs) throws SQLException, UnexpectedServerErrorException { + List vppAssetDTOS = loadAssets(rs); + if (vppAssetDTOS.isEmpty()) { + return null; + } + if (vppAssetDTOS.size() > 1) { + String msg = "Internal server error. Found more than one asset for given app id."; + log.error(msg); + throw new UnexpectedServerErrorException(msg); + } + return vppAssetDTOS.get(0); + } + + public static List loadAssets (ResultSet rs) throws SQLException { + List vppAssetDTOS = new ArrayList<>(); + while (rs.next()) { + VppAssetDTO vppAssetDTO = new VppAssetDTO(); + vppAssetDTO.setId(rs.getInt("ID")); + vppAssetDTO.setAppId(rs.getInt("APP_ID")); + vppAssetDTO.setTenantId(rs.getInt("TENANT_ID")); + if (rs.getLong("CREATED_TIME") != 0) { + Date date = new Date(rs.getLong("CREATED_TIME")); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateString = dateFormat.format(date); + vppAssetDTO.setCreatedTime(dateString); + } + if (rs.getLong("LAST_UPDATED_TIME") != 0) { + Date date = new Date(rs.getLong("LAST_UPDATED_TIME")); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateString = dateFormat.format(date); + vppAssetDTO.setLastUpdatedTime(dateString); + } + vppAssetDTO.setAdamId(rs.getString("ADAM_ID")); + vppAssetDTO.setAssignedCount(rs.getString("ASSIGNED_COUNT")); + vppAssetDTO.setDeviceAssignable(rs.getString("DEVICE_ASSIGNABLE")); + vppAssetDTO.setPricingParam(rs.getString("PRICING_PARAMS")); + vppAssetDTO.setProductType(rs.getString("PRODUCT_TYPE")); + vppAssetDTO.setRetiredCount(rs.getString("RETIRED_COUNT")); + vppAssetDTO.setRevocable(rs.getString("REVOCABLE")); +// String jsonString = rs.getString("SUPPORTED_PLATFORMS"); +// ObjectMapper objectMapper = new ObjectMapper(); +// try { +// List platformList = objectMapper.readValue(jsonString, new TypeReference>() {}); +// vppAssetDTO.setSupportedPlatforms(platformList); +// } catch (IOException e) { +// e.printStackTrace(); +// } + vppAssetDTOS.add(vppAssetDTO); + } + return vppAssetDTOS; + } + + public static VppAssociationDTO loadAssignment(ResultSet rs) throws SQLException, UnexpectedServerErrorException { + List vppAssociationDTOS = loadAssignments(rs); + if (vppAssociationDTOS.isEmpty()) { + return null; + } + if (vppAssociationDTOS.size() > 1) { + String msg = "Internal server error. Found more than one asset for given app id."; + log.error(msg); + throw new UnexpectedServerErrorException(msg); + } + return vppAssociationDTOS.get(0); + } + + public static List loadAssignments (ResultSet rs) throws SQLException { + List vppAssociationDTOS = new ArrayList<>(); + while (rs.next()) { + VppAssociationDTO vppAssociationDTO = new VppAssociationDTO(); + vppAssociationDTO.setId(rs.getInt("ID")); + vppAssociationDTO.setAssociationType(rs.getString("ASSOCIATION_TYPE")); + if (rs.getLong("CREATED_TIME") != 0) { + Date date = new Date(rs.getLong("CREATED_TIME")); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateString = dateFormat.format(date); + vppAssociationDTO.setCreatedTime(dateString); + } + if (rs.getLong("LAST_UPDATED_TIME") != 0) { + Date date = new Date(rs.getLong("LAST_UPDATED_TIME")); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateString = dateFormat.format(date); + vppAssociationDTO.setLastUpdatedTime(dateString); + } + vppAssociationDTO.setPricingParam(rs.getString("PRICING_PARAMS")); + vppAssociationDTOS.add(vppAssociationDTO); + } + return vppAssociationDTOS; + } + /** * Cleans up the statement and resultset after executing the query * diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/VppHttpUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/VppHttpUtil.java new file mode 100644 index 0000000000..c915b8407d --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/VppHttpUtil.java @@ -0,0 +1,305 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.application.mgt.core.util; + +import com.google.gson.Gson; +import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssociationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.Consts; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; + +public class VppHttpUtil { + private static final Log log = LogFactory.getLog(VppHttpUtil.class); + + public static ProxyResponse execute(String url, + String payload, + String accessToken, + String method) throws IOException { + + HttpRequestBase endpoint = null; + if (Constants.VPP.GET.equalsIgnoreCase(method) || Constants.VPP.DELETE.equalsIgnoreCase(method)) { + endpoint = new HttpGet(url); + addHeaders(endpoint, accessToken); + return VppHttpUtil.execute(endpoint); + } else if (Constants.VPP.POST.equalsIgnoreCase(method)) { + endpoint = new HttpPost(url); + } else if (Constants.VPP.PUT.equalsIgnoreCase(method)) { + endpoint = new HttpPut(url); + } + addHeaders(endpoint, accessToken); + + + if (payload != null) { + HttpEntity forwardRequestBody = new StringEntity(payload, ContentType.APPLICATION_JSON.toString(), "utf-8"); + if (Constants.VPP.POST.equalsIgnoreCase(method)) { + ((HttpPost) endpoint).setEntity(forwardRequestBody); + } else if (Constants.VPP.PUT.equalsIgnoreCase(method)) { + ((HttpPut) endpoint).setEntity(forwardRequestBody); + } + + } + if (log.isDebugEnabled()) { + log.info("Forwarding request to " + url); + } + return VppHttpUtil.execute(endpoint); + } + + private static void addHeaders(HttpRequestBase endpoint, String accessToken) { + endpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); + endpoint.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString()); + endpoint.setHeader(HttpHeaders.AUTHORIZATION, Constants.VPP.BEARER + accessToken); + } + + + /*** + * + * @param httpRequest - httpMethod e.g:- HttpPost, HttpGet + * @return response as string + * @throws IOException IO exception returns if error occurs when executing the httpMethod + */ + private static ProxyResponse execute(HttpRequestBase httpRequest) throws IOException { + try (CloseableHttpClient client = getHttpClient()) { + HttpResponse response = client.execute(httpRequest); + ProxyResponse proxyResponse = new ProxyResponse(); + + if (response == null) { + log.error("Received null response for http request : " + httpRequest.getMethod() + " " + httpRequest + .getURI().toString()); + proxyResponse.setCode(Constants.VPP.INTERNAL_ERROR_CODE); + proxyResponse.setExecutorResponse(Constants.VPP.EXECUTOR_EXCEPTION_PREFIX + getStatusKey( + Constants.VPP.INTERNAL_ERROR_CODE)); + return proxyResponse; + } else { + int statusCode = response.getStatusLine().getStatusCode(); + try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { + StringBuilder result = new StringBuilder(); + String line; + while ((line = rd.readLine()) != null) { + result.append(line); + } + + String jsonString = result.toString(); + if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) { + proxyResponse.setCode(statusCode); + proxyResponse.setData(jsonString); + proxyResponse.setExecutorResponse("SUCCESS"); + return proxyResponse; + } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { + if (jsonString.contains("Access token expired") || jsonString + .contains("Invalid input. Access token validation failed")) { + proxyResponse.setCode(statusCode); + proxyResponse.setExecutorResponse(Constants.VPP.TOKEN_IS_EXPIRED); + return proxyResponse; + } else { + log.error( + "Received " + statusCode + " response for http request : " + httpRequest.getMethod() + + " " + httpRequest.getURI().toString() + ". Error message: " + jsonString); + proxyResponse.setCode(statusCode); + proxyResponse.setData(jsonString); + proxyResponse.setExecutorResponse( + Constants.VPP.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); + return proxyResponse; + } + } + log.error("Received " + statusCode + + " response for http request : " + httpRequest.getMethod() + " " + httpRequest.getURI() + .toString() + ". Error message: " + jsonString); + proxyResponse.setCode(statusCode); + proxyResponse.setData(jsonString); + proxyResponse + .setExecutorResponse(Constants.VPP.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); + return proxyResponse; + } + } + } + } + + /*** + * + * @param statusCode Provide status code, e.g:- 400, 401, 500 etc + * @return relative status code key for given status code. + */ + public static String getStatusKey(int statusCode) { + String statusCodeKey; + + switch (statusCode) { + case HttpStatus.SC_INTERNAL_SERVER_ERROR: + statusCodeKey = "internalServerError"; + break; + case HttpStatus.SC_BAD_REQUEST: + statusCodeKey = "badRequest"; + break; + case HttpStatus.SC_UNAUTHORIZED: + statusCodeKey = "unauthorized"; + break; + case HttpStatus.SC_FORBIDDEN: + statusCodeKey = "forbidden"; + break; + case HttpStatus.SC_NOT_FOUND: + statusCodeKey = "notFound"; + break; + case HttpStatus.SC_METHOD_NOT_ALLOWED: + statusCodeKey = "methodNotAllowed"; + break; + case HttpStatus.SC_NOT_ACCEPTABLE: + statusCodeKey = "notAcceptable"; + break; + case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE: + statusCodeKey = "unsupportedMediaType"; + break; + default: + statusCodeKey = "defaultPage"; + break; + } + return statusCodeKey; + } + + + /*** + * Handle error requests. + * + * @param resp {@link HttpServletResponse} + * @param proxyResponse {@link ProxyResponse} + * @throws IOException If error occurred when trying to send the error response. + */ + public static void handleError(HttpServletResponse resp, ProxyResponse proxyResponse) throws IOException { + Gson gson = new Gson(); + if (proxyResponse == null) { + proxyResponse = new ProxyResponse(); + proxyResponse.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); + proxyResponse.setExecutorResponse(Constants.VPP.EXECUTOR_EXCEPTION_PREFIX + VppHttpUtil + .getStatusKey(Constants.VPP.INTERNAL_ERROR_CODE)); + } + resp.setStatus(proxyResponse.getCode()); + resp.setContentType(ContentType.APPLICATION_JSON.getMimeType()); + resp.setCharacterEncoding(Consts.UTF_8.name()); + + proxyResponse.setExecutorResponse(null); + try (PrintWriter writer = resp.getWriter()) { + writer.write(gson.toJson(proxyResponse)); + } + } + + /** + * Handle error requests with custom error codes. + * + * @param resp {@link HttpServletResponse} + * @param errorCode HTTP error status code + * @throws IOException If error occurred when trying to send the error response. + */ + public static void handleError(HttpServletResponse resp, int errorCode) + throws IOException { + ProxyResponse proxyResponse = new ProxyResponse(); + proxyResponse.setCode(errorCode); + proxyResponse.setExecutorResponse( + Constants.VPP.EXECUTOR_EXCEPTION_PREFIX + VppHttpUtil.getStatusKey(errorCode)); + VppHttpUtil.handleError(resp, proxyResponse); + } + + /*** + * + * @param resp {@link HttpServletResponse} + * Return Success Response. + */ + public static void handleSuccess(HttpServletResponse resp, ProxyResponse proxyResponse) throws IOException { + if (proxyResponse == null) { + handleError(resp, null); + return; + } + resp.setStatus(proxyResponse.getCode()); + resp.setContentType(ContentType.APPLICATION_JSON.getMimeType()); + resp.setCharacterEncoding(Consts.UTF_8.name()); + JSONObject response = new JSONObject(); + String responseData = proxyResponse.getData(); + + if (!StringUtils.isEmpty(responseData)) { + try { + if (responseData.startsWith("{")) { + JSONObject responseDataJsonObj = new JSONObject(responseData); + response.put("data", responseDataJsonObj); + } else if (responseData.startsWith("[")) { + JSONArray responseDataJsonArr = new JSONArray(responseData); + response.put("data", responseDataJsonArr); + } else { + log.warn("Response data is not valid json string >> " + responseData); + response.put("data", responseData); + } + } catch (JSONException e) { + log.error("Response data is not passable"); + response.put("data", responseData); + } + } + + try (PrintWriter writer = resp.getWriter()) { + writer.write(response.toString()); + } + } + + /** + * Retrieve Http client based on hostname verification. + * + * @return {@link CloseableHttpClient} http client + */ + public static CloseableHttpClient getHttpClient() { + return HttpClients.custom().setMaxConnTotal(1).setMaxConnPerRoute(1).build(); + } + + public static VppAssociationDTO getAssociation(VppUserDTO user, VppAssetDTO asset) { + VppAssociationDTO associationDTO = new VppAssociationDTO(); + associationDTO.setAdamId(asset.getAdamId()); + associationDTO.setClientUserId(user.getClientUserId()); + associationDTO.setPricingParam(asset.getPricingParam()); + associationDTO.setAssociationType(Constants.ApplicationProperties.ASSOCIATION_USER); + + associationDTO.setAssetId(asset.getId()); + associationDTO.setClientId(user.getId()); + associationDTO.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext() + .getTenantId(true)); + associationDTO.setCreatedTime(String.valueOf(System.currentTimeMillis())); + associationDTO.setLastUpdatedTime(String.valueOf(System.currentTimeMillis())); + return associationDTO; + } + +} diff --git a/components/application-mgt/pom.xml b/components/application-mgt/pom.xml index 064f9eddb9..005789d0a6 100644 --- a/components/application-mgt/pom.xml +++ b/components/application-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml index d4f1cf59f2..ad742cd285 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml @@ -22,7 +22,7 @@ certificate-mgt io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/api/CertificateMgtService.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/api/CertificateMgtService.java index db14d6f072..f2bdb8fafd 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/api/CertificateMgtService.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/api/CertificateMgtService.java @@ -58,7 +58,7 @@ import javax.ws.rs.core.Response; @Scope( name = "Sign CSR", description = "Sign CSR", - key = "perm:sign-csr", + key = "dm:sign-csr", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/certificates/manage"} ) @@ -87,7 +87,7 @@ public interface CertificateMgtService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:sign-csr") + @ExtensionProperty(name = SCOPE, value = "dm:sign-csr") }) } ) diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml index 76f70e08f2..0b0f530259 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml @@ -22,7 +22,7 @@ certificate-mgt io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java index 18207be106..34ddbd193a 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java @@ -62,35 +62,35 @@ import javax.ws.rs.core.Response; @Scope( name = "Adding a new SSL certificate", description = "Adding a new SSL certificate", - key = "perm:admin:certificates:add", + key = "cm:cert:add", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/certificates/add"} ), @Scope( name = "Getting Details of an SSL Certificate", description = "Getting Details of an SSL Certificate", - key = "perm:admin:certificates:details", + key = "cm:cert:details:get", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/certificates/details"} ), @Scope( name = "Getting Details of Certificates", description = "Getting Details of Certificates", - key = "perm:admin:certificates:view", + key = "cm:cert:view", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/certificates/view"} ), @Scope( name = "Deleting an SSL Certificate", description = "Deleting an SSL Certificate", - key = "perm:admin:certificates:delete", + key = "cm:cert:delete", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/certificates/delete"} ), @Scope( name = "Verify SSL certificate", description = "Verify SSL certificate", - key = "perm:admin:certificates:verify", + key = "cm:cert:verify", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/certificates/verify"} ) @@ -119,7 +119,7 @@ public interface CertificateManagementAdminService { tags = "Certificate Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:admin:certificates:add") + @ExtensionProperty(name = SCOPE, value = "cm:cert:add") }) } ) @@ -188,7 +188,7 @@ public interface CertificateManagementAdminService { tags = "Certificate Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:admin:certificates:details") + @ExtensionProperty(name = SCOPE, value = "cm:cert:details:get") }) } ) @@ -247,19 +247,20 @@ public interface CertificateManagementAdminService { * * @return paginated result of certificate. */ + @GET @ApiOperation( consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, httpMethod = "GET", - value = "Getting Details of Certificates", - notes = "Get all the details of the certificates you have used for mutual SSL. In a situation where you wish to " - + "view all the certificate details, it is not feasible to show all the details on one " + value = "Getting Details of search Certificates", + notes = "Get all the details of the search certificates you have used for mutual SSL. In a situation where you wish to " + + "view all the search certificate details, it is not feasible to show all the details on one " + "page. Therefore, the details are paginated.", tags = "Certificate Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:admin:certificates:view") + @ExtensionProperty(name = SCOPE, value = "cm:cert:view") }) } ) @@ -307,6 +308,28 @@ public interface CertificateManagementAdminService { response = ErrorResponse.class) }) Response getAllCertificates( + @ApiParam( + name = "serialNumber", + value = "The serial number of the certificates", + required = false) + @QueryParam("serialNumber") String serialNumber, + @ApiParam( + name = "deviceIdentifier", + value = "The device identifier of the certificates", + required = false) + @QueryParam("deviceIdentifier") String deviceIdentifier, + @ApiParam( + name = "username", + value = "User name of the certificate added user", + required = false) + @QueryParam("username") String username, + @ApiParam( + name = "If-Modified-Since", + value = "Checks if the requested variant was modified, since the specified date-time. \n" + + "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" + + "Example: Mon, 05 Jan 2014 15:10:00 +0200", + required = false) + @HeaderParam("If-Modified-Since") String ifModifiedSince, @ApiParam( name = "offset", value = "The starting pagination index for the complete list of qualified items.", @@ -318,14 +341,7 @@ public interface CertificateManagementAdminService { value = "Provide how many certificate details you require from the starting pagination index/offset.", required = false, defaultValue = "5") - @QueryParam("limit") int limit, - @ApiParam( - name = "If-Modified-Since", - value = "Checks if the requested variant was modified, since the specified date-time. \n" + - "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" + - "Example: Mon, 05 Jan 2014 15:10:00 +0200", - required = false) - @HeaderParam("If-Modified-Since") String ifModifiedSince); + @QueryParam("limit") int limit); @DELETE @ApiOperation( @@ -337,7 +353,7 @@ public interface CertificateManagementAdminService { tags = "Certificate Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:admin:certificates:delete") + @ExtensionProperty(name = SCOPE, value = "cm:cert:delete") }) } ) @@ -383,7 +399,7 @@ public interface CertificateManagementAdminService { tags = "Certificate Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:admin:certificates:verify") + @ExtensionProperty(name = SCOPE, value = "cm:cert:verify") }) } ) diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java index 85b361d33d..4b62253156 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java @@ -18,7 +18,6 @@ package io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.impl; -import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; @@ -26,7 +25,9 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; + +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.CertificateManagementAdminService; @@ -87,6 +88,13 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); certificate.setSerial(enrollmentCertificate.getSerial()); certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem())); + CertificateResponse existingCertificate = certificateService.getCertificateBySerial(enrollmentCertificate.getSerial()); + if (existingCertificate != null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity("Certificate with serial number " + enrollmentCertificate.getSerial() + " already exists.") + .build(); + } + certificates.add(certificate); } certificateService.saveCertificate(certificates); @@ -134,13 +142,27 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem */ @GET public Response getAllCertificates( + @QueryParam("serialNumber") String serialNumber, + @QueryParam("deviceIdentifier") String deviceIdentifier, + @QueryParam("username") String username, + @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, - @QueryParam("limit") int limit, - @HeaderParam("If-Modified-Since") String ifModifiedSince) { + @QueryParam("limit") int limit) { RequestValidationUtil.validatePaginationInfo(offset, limit); CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); + CertificatePaginationRequest request = new CertificatePaginationRequest(offset, limit); + + if (StringUtils.isNotEmpty(serialNumber)) { + request.setSerialNumber(serialNumber); + } + if (StringUtils.isNotEmpty(deviceIdentifier)){ + request.setDeviceIdentifier(deviceIdentifier); + } + if (StringUtils.isNotEmpty(username)){ + request.setUsername(username); + } try { - PaginationResult result = certificateService.getAllCertificates(offset, limit); + PaginationResult result = certificateService.getAllCertificates(request); CertificateList certificates = new CertificateList(); certificates.setCount(result.getRecordsTotal()); certificates.setList((List) result.getData()); @@ -159,18 +181,33 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); try { - boolean status = certificateService.removeCertificate(serialNumber); - if (!status) { - return Response.status(Response.Status.NOT_FOUND).entity( - "No certificate is found with the given " + - "serial number '" + serialNumber + "'").build(); + boolean decision = certificateService.getValidateMetaValue(); + if (decision) { + try { + boolean status = certificateService.removeCertificate(serialNumber); + if (!status) { + return Response.status(Response.Status.NOT_FOUND).entity( + "No certificate is found with the given " + + "serial number '" + serialNumber + "'").build(); + } else { + return Response.status(Response.Status.OK).entity( + "Certificate that carries the serial number '" + + serialNumber + "' has been removed").build(); + } + } catch (CertificateManagementException e) { + String msg = "Error occurred while removing certificate with the given " + + "serial number '" + serialNumber + "'"; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } } else { - return Response.status(Response.Status.OK).entity( - "Certificate that carries the serial number '" + - serialNumber + "' has been removed").build(); + return Response.status(Response.Status.UNAUTHORIZED).entity( + "User unauthorized to delete certificate with " + + "serial number '" + serialNumber + "'").build(); } } catch (CertificateManagementException e) { - String msg = "Error occurred while converting PEM file to X509Certificate"; + String msg = "Error occurred while getting the metadata entry for certificate deletion."; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml index dcccd215b1..2c61971793 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core certificate-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml @@ -57,6 +57,11 @@ io.entgra.device.mgt.core.certificate.mgt.core.util + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.apache.commons.lang, + org.apache.commons.logging, + org.apache.commons.collections.map, io.entgra.device.mgt.core.certificate.mgt.core.*, io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", @@ -90,6 +95,22 @@ org.bouncycastle.util;version="[1.70,2)", org.jscep.message, org.jscep.transaction, + org.w3c.dom, + org.xml.sax, + javax.sql, + + javax.naming, + javax.xml.bind.annotation, + javax.xml.bind, + org.wso2.carbon.utils.*, + io.entgra.device.mgt.core.device.mgt.common.*, + io.swagger.annotations.*;resolution:=optional, + io.entgra.device.mgt.core.device.mgt.core.*, + org.wso2.carbon.registry.indexing.*, + javax.cache.*, + javax.naming.ldap, + com.google.gson.*, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", org.w3c.dom,org.wso2.carbon.context;version="[4.8,5)", @@ -253,6 +274,10 @@ org.wso2.orbit.javax.xml.bind jaxb-api + + com.googlecode.json-simple.wso2 + json-simple + diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java index 779251761e..068766f3b9 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java @@ -18,8 +18,10 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; +import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import java.util.List; @@ -75,13 +77,12 @@ public interface CertificateDAO { /** * Get all the certificates in a paginated manner. * - * @param rowNum Stating index of the paginated result. - * @param limit Number of records to return. + * @param request index of the paginated result. * @return Pagination result with data and the count of results. * @throws CertificateManagementDAOException * */ - PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException; + PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException; /** * Get all the certificates. @@ -95,7 +96,7 @@ public interface CertificateDAO { /** * Delete a certificate identified by a serial number() * - * @param serialNumber serial number + * @param serialNumber number * @return whether the certificate was removed or not. */ boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java index 0a8e9e3066..a5ec99203e 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java @@ -279,7 +279,7 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ return stmt.executeUpdate() > 0; } catch (SQLException e) { - String msg = "Unable to get the read the certificate with serial" + serialNumber; + String msg = "Unable to get the read the certificate with serialNumber" + serialNumber; log.error(msg, e); throw new CertificateManagementDAOException(msg, e); } finally { diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java index fa5d028afe..455942b305 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java @@ -18,14 +18,16 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; +import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; +import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; -import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; -import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.Connection; @@ -48,45 +50,133 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { return CertificateManagementDAOFactory.getConnection(); } + private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException { + int certificateCount = 0; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + + try { + Connection conn = this.getConnection(); + String sql = "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ?"; + + if (StringUtils.isNotEmpty(serialNumber)) { + sql += " AND SERIAL_NUMBER = ?"; + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + sql += " AND DEVICE_IDENTIFIER = ?"; + } + + if (StringUtils.isNotEmpty(username)) { + sql += " AND USERNAME LIKE ?"; + } + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + + int paramIdx = 2; + if (StringUtils.isNotEmpty(serialNumber)) { + stmt.setString(paramIdx++, serialNumber); + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + stmt.setString(paramIdx++, deviceIdentifier); + } + + if (StringUtils.isNotEmpty(username)) { + stmt.setString(paramIdx, "%" + username + "%"); + } + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } + } + } catch (SQLException e) { + String errorMsg = "SQL error occurred while retrieving the certificate count."; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } + return certificateCount; + } + + @Override - public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { - PreparedStatement stmt = null; - ResultSet resultSet = null; + public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + boolean isCertificateSerialNumberProvided = false; + boolean isCertificateDeviceIdentifierProvided = false; + boolean isCertificateUsernameProvided = false; + try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM " - + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ?,?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, rowNum); - stmt.setInt(3, limit); - resultSet = stmt.executeQuery(); + String query = "SELECT * " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ? "; - int resultCount = 0; - while (resultSet.next()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - resultCount++; + if (StringUtils.isNotEmpty(serialNumber)) { + query += "AND SERIAL_NUMBER = ? "; + isCertificateSerialNumberProvided = true; + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + query += "AND DEVICE_IDENTIFIER = ? "; + isCertificateDeviceIdentifierProvided = true; + } + + if (StringUtils.isNotEmpty(username)) { + query += "AND USERNAME LIKE ? "; + isCertificateUsernameProvided = true; + } + + query += "ORDER BY ID LIMIT ?,?"; + + try (PreparedStatement stmt = conn.prepareStatement(query)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isCertificateSerialNumberProvided) { + stmt.setString(paramIdx++, serialNumber); + } + if (isCertificateDeviceIdentifierProvided) { + stmt.setString(paramIdx++, deviceIdentifier); + } + if (isCertificateUsernameProvided) { + stmt.setString(paramIdx++, "%" + username + "%"); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx++, request.getRowCount()); + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } } - paginationResult = new PaginationResult(); - paginationResult.setData(certificates); - paginationResult.setRecordsTotal(resultCount); } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); } return paginationResult; } -} +} \ No newline at end of file diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java index 78a0fada50..cbb689977b 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java @@ -18,14 +18,16 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; +import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; +import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; -import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; -import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.Connection; @@ -44,43 +46,75 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { private static final Log log = LogFactory.getLog(OracleCertificateDAOImpl.class); @Override - public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { - PreparedStatement stmt = null; - ResultSet resultSet = null; + public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + boolean isCertificateSerialNumberProvided = false; + boolean isCertificateDeviceIdentifierProvided = false; + boolean isCertificateUsernameProvided = false; + try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM " - + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, rowNum); - stmt.setInt(3, limit); - resultSet = stmt.executeQuery(); - - int resultCount = 0; - while (resultSet.next()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - resultCount++; + String query = "SELECT * " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ? "; + if (StringUtils.isNotEmpty(serialNumber)) { + query += "AND SERIAL_NUMBER = ? "; + isCertificateSerialNumberProvided = true; + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + query += "AND DEVICE_IDENTIFIER = ? "; + isCertificateDeviceIdentifierProvided = true; + } + + if (StringUtils.isNotEmpty(username)) { + query += "AND USERNAME LIKE ? "; + isCertificateUsernameProvided = true; + } + + query += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + try (PreparedStatement stmt = conn.prepareStatement(query)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isCertificateSerialNumberProvided) { + stmt.setString(paramIdx++, serialNumber); + } + if (isCertificateDeviceIdentifierProvided) { + stmt.setString(paramIdx++, deviceIdentifier); + } + if (isCertificateUsernameProvided) { + stmt.setString(paramIdx++, "%" + username + "%"); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx++, request.getRowCount()); + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } } - paginationResult = new PaginationResult(); - paginationResult.setData(certificates); - paginationResult.setRecordsTotal(resultCount); } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); } return paginationResult; } @@ -88,4 +122,60 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { private Connection getConnection() throws SQLException { return CertificateManagementDAOFactory.getConnection(); } + + private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException { + int certificateCount = 0; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + + try { + Connection conn = this.getConnection(); + String sql = "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ?"; + + if (StringUtils.isNotEmpty(serialNumber)) { + sql += " AND SERIAL_NUMBER = ?"; + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + sql += " AND DEVICE_IDENTIFIER = ?"; + } + + if (StringUtils.isNotEmpty(username)) { + sql += " AND USERNAME LIKE ?"; + } + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + + int paramIdx = 2; + if (StringUtils.isNotEmpty(serialNumber)) { + stmt.setString(paramIdx++, serialNumber); + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + stmt.setString(paramIdx++, deviceIdentifier); + } + + if (StringUtils.isNotEmpty(username)) { + stmt.setString(paramIdx, "%" + username + "%"); + } + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } + } + } catch (SQLException e) { + String errorMsg = "SQL error occurred while retrieving the certificate count."; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } + return certificateCount; + } + } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java index e331402ce1..92b5720102 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java @@ -18,14 +18,16 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; +import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; +import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; -import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; -import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.Connection; @@ -44,43 +46,75 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { private static final Log log = LogFactory.getLog(PostgreSQLCertificateDAOImpl.class); @Override - public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { - PreparedStatement stmt = null; - ResultSet resultSet = null; + public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + boolean isCertificateSerialNumberProvided = false; + boolean isCertificateDeviceIdentifierProvided = false; + boolean isCertificateUsernameProvided = false; + try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM " - + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ? OFFSET ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, limit); - stmt.setInt(3, rowNum); - resultSet = stmt.executeQuery(); - - int resultCount = 0; - while (resultSet.next()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - resultCount++; + String query = "SELECT * " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ? "; + if (StringUtils.isNotEmpty(serialNumber)) { + query += "AND SERIAL_NUMBER = ? "; + isCertificateSerialNumberProvided = true; + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + query += "AND DEVICE_IDENTIFIER = ? "; + isCertificateDeviceIdentifierProvided = true; + } + + if (StringUtils.isNotEmpty(username)) { + query += "AND USERNAME LIKE ? "; + isCertificateUsernameProvided = true; + } + + query += "ORDER BY ID LIMIT ? OFFSET ?"; + + try (PreparedStatement stmt = conn.prepareStatement(query)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isCertificateSerialNumberProvided) { + stmt.setString(paramIdx++, serialNumber); + } + if (isCertificateDeviceIdentifierProvided) { + stmt.setString(paramIdx++, deviceIdentifier); + } + if (isCertificateUsernameProvided) { + stmt.setString(paramIdx++, "%" + username + "%"); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx++, request.getRowCount()); + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } } - paginationResult = new PaginationResult(); - paginationResult.setData(certificates); - paginationResult.setRecordsTotal(resultCount); } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); } return paginationResult; } @@ -88,4 +122,60 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { private Connection getConnection() throws SQLException { return CertificateManagementDAOFactory.getConnection(); } + + private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException { + int certificateCount = 0; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + + try { + Connection conn = this.getConnection(); + String sql = "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ?"; + + if (StringUtils.isNotEmpty(serialNumber)) { + sql += " AND SERIAL_NUMBER = ?"; + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + sql += " AND DEVICE_IDENTIFIER = ?"; + } + + if (StringUtils.isNotEmpty(username)) { + sql += " AND USERNAME ILIKE ?"; + } + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + + int paramIdx = 2; + if (StringUtils.isNotEmpty(serialNumber)) { + stmt.setString(paramIdx++, serialNumber); + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + stmt.setString(paramIdx++, deviceIdentifier); + } + + if (StringUtils.isNotEmpty(username)) { + stmt.setString(paramIdx, "%" + username + "%"); + } + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } + } + } catch (SQLException e) { + String errorMsg = "SQL error occurred while retrieving the certificate count."; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } + return certificateCount; + } + } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java index 084ab9a1c1..80f902614d 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java @@ -18,14 +18,16 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; +import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; +import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; -import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; -import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.Connection; @@ -44,43 +46,75 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { private static final Log log = LogFactory.getLog(SQLServerCertificateDAOImpl.class); @Override - public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { - PreparedStatement stmt = null; - ResultSet resultSet = null; + public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + boolean isCertificateSerialNumberProvided = false; + boolean isCertificateDeviceIdentifierProvided = false; + boolean isCertificateUsernameProvided = false; + try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM " - + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, rowNum); - stmt.setInt(3, limit); - resultSet = stmt.executeQuery(); - - int resultCount = 0; - while (resultSet.next()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - resultCount++; + String query = "SELECT * " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ? "; + if (StringUtils.isNotEmpty(serialNumber)) { + query += "AND SERIAL_NUMBER = ? "; + isCertificateSerialNumberProvided = true; + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + query += "AND DEVICE_IDENTIFIER = ? "; + isCertificateDeviceIdentifierProvided = true; + } + + if (StringUtils.isNotEmpty(username)) { + query += "AND USERNAME LIKE ? "; + isCertificateUsernameProvided = true; + } + + query += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + try (PreparedStatement stmt = conn.prepareStatement(query)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isCertificateSerialNumberProvided) { + stmt.setString(paramIdx++, serialNumber); + } + if (isCertificateDeviceIdentifierProvided) { + stmt.setString(paramIdx++, deviceIdentifier); + } + if (isCertificateUsernameProvided) { + stmt.setString(paramIdx++, "%" + username + "%"); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx++, request.getRowCount()); + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } } - paginationResult = new PaginationResult(); - paginationResult.setData(certificates); - paginationResult.setRecordsTotal(resultCount); } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); } return paginationResult; } @@ -88,4 +122,60 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { private Connection getConnection() throws SQLException { return CertificateManagementDAOFactory.getConnection(); } + + private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException { + int certificateCount = 0; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + + try { + Connection conn = this.getConnection(); + String sql = "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ?"; + + if (StringUtils.isNotEmpty(serialNumber)) { + sql += " AND SERIAL_NUMBER = ?"; + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + sql += " AND DEVICE_IDENTIFIER = ?"; + } + + if (StringUtils.isNotEmpty(username)) { + sql += " AND USERNAME LIKE ?"; + } + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + + int paramIdx = 2; + if (StringUtils.isNotEmpty(serialNumber)) { + stmt.setString(paramIdx++, serialNumber); + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + stmt.setString(paramIdx++, deviceIdentifier); + } + + if (StringUtils.isNotEmpty(username)) { + stmt.setString(paramIdx, "%" + username + "%"); + } + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } + } + } catch (SQLException e) { + String errorMsg = "SQL error occurred while retrieving the certificate count."; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } + return certificateCount; + } + } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dto/CertificateResponse.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dto/CertificateResponse.java index 44b0df5193..23f37a0efa 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dto/CertificateResponse.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dto/CertificateResponse.java @@ -32,6 +32,12 @@ public class CertificateResponse { @ApiModelProperty(name = "serialNumber", value = "It is the unique ID that is used to identify a certificate", required = true) String serialNumber; + @ApiModelProperty(name = "deviceIdentifier", value = "It is use to identify a certificate list", required = true) + String deviceIdentifier; + + @ApiModelProperty(name = "certificateId", value = "It is the unique ID that is used to identify a certificate", required = true) + String certificateId; + @ApiModelProperty(name = "tenantId", value = "The ID of the tenant who adds the certificate", required = true) int tenantId; @@ -44,8 +50,8 @@ public class CertificateResponse { @ApiModelProperty(name = "notBefore", value = "The date from when the certificate is valid", required = true) long notBefore; - @ApiModelProperty(name = "certificateserial", value = "The serial number of the certificate", required = true) - BigInteger certificateserial; + @ApiModelProperty(name = "certificateSerial", value = "The serial number of the certificate", required = true) + BigInteger certificateSerial; @ApiModelProperty(name = "issuer", value = "The identity of the authority that signs the SSL certificate", required = true) String issuer; @@ -83,12 +89,12 @@ public class CertificateResponse { this.notBefore = notBefore; } - public BigInteger getCertificateserial() { - return certificateserial; + public BigInteger getCertificateSerial() { + return certificateSerial; } - public void setCertificateserial(BigInteger certificateserial) { - this.certificateserial = certificateserial; + public void setCertificateSerial(BigInteger certificateSerial) { + this.certificateSerial = certificateSerial; } public String getIssuer() { @@ -146,4 +152,20 @@ public class CertificateResponse { public void setTenantId(int tenantId) { this.tenantId = tenantId; } + + public String getDeviceIdentifier() { + return deviceIdentifier; + } + + public void setDeviceIdentifier(String deviceIdentifier) { + this.deviceIdentifier = deviceIdentifier; + } + + public String getCertificateId() { + return certificateId; + } + + public void setCertificateId(String certificateId) { + this.certificateId = certificateId; + } } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java index 4fe75afb8a..347dea3d4f 100755 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java @@ -108,7 +108,7 @@ public class CertificateGenerator { X509Certificate certificate = (X509Certificate) x509Certificate; certificateResponse.setNotAfter(certificate.getNotAfter().getTime()); certificateResponse.setNotBefore(certificate.getNotBefore().getTime()); - certificateResponse.setCertificateserial(certificate.getSerialNumber()); + certificateResponse.setCertificateSerial(certificate.getSerialNumber()); certificateResponse.setIssuer(certificate.getIssuerDN().getName()); certificateResponse.setSubject(certificate.getSubjectDN().getName()); certificateResponse.setCertificateVersion(certificate.getVersion()); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java index 3eb94d21f1..611295ba3f 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java @@ -17,6 +17,7 @@ */ package io.entgra.device.mgt.core.certificate.mgt.core.service; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.dto.SCEPResponse; import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; @@ -71,10 +72,12 @@ public interface CertificateManagementService { CertificateResponse retrieveCertificate(String serialNumber) throws CertificateManagementException; - PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementException; + PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementException; boolean removeCertificate(String serialNumber) throws CertificateManagementException; + boolean getValidateMetaValue() throws CertificateManagementException; + List getCertificates() throws CertificateManagementException; List searchCertificates(String serialNumber) throws CertificateManagementException; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java index 95ec72a111..06cbedfb4d 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java @@ -17,6 +17,12 @@ */ package io.entgra.device.mgt.core.certificate.mgt.core.service; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; +import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; +import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagerUtil; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateDAO; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; @@ -27,12 +33,15 @@ import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreExceptio import io.entgra.device.mgt.core.certificate.mgt.core.exception.TransactionManagementException; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.impl.KeyStoreReader; -import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; -import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagerUtil; + +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.bouncycastle.pkcs.PKCS10CertificationRequest; + import java.io.InputStream; import java.security.PrivateKey; import java.security.cert.Certificate; @@ -154,25 +163,24 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe } @Override - public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementException { + public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementException { try { CertificateManagementDAOFactory.openConnection(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); - return certificateDAO.getAllCertificates(rowNum, CertificateManagerUtil.validateCertificateListPageSize(limit)); + return certificateDAO.getAllCertificates(request); } catch (SQLException e) { String msg = "Error occurred while opening a connection to the underlying data source"; log.error(msg, e); throw new CertificateManagementException(msg, e); } catch (CertificateManagementDAOException e) { String msg = "Error occurred while looking up for the list of certificates managed in the underlying " + - "certificate repository"; + "certificate repository"; log.error(msg, e); throw new CertificateManagementException(msg, e); } finally { CertificateManagementDAOFactory.closeConnection(); } } - @Override public boolean removeCertificate(String serialNumber) throws CertificateManagementException { try { @@ -182,18 +190,43 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe CertificateManagementDAOFactory.commitTransaction(); return status; } catch (TransactionManagementException e) { - String msg = "Error occurred while removing certificate carrying serial number '" + serialNumber + "'"; + String msg = "Error occurred while removing certificate carrying serialNumber '" + serialNumber + "'"; log.error(msg, e); throw new CertificateManagementException(msg, e); } catch (CertificateManagementDAOException e) { CertificateManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred while removing the certificate carrying serial number '" + serialNumber + + String msg = "Error occurred while removing the certificate carrying serialNumber '" + serialNumber + "' from the certificate repository"; log.error(msg, e); throw new CertificateManagementException(msg, e); } } + @Override + public boolean getValidateMetaValue() throws CertificateManagementException { + Metadata metadata; + try { + metadata = CertificateManagerUtil.getMetadataManagementService().retrieveMetadata(CertificateManagementConstants.CERTIFICATE_DELETE); + if (metadata != null) { + String metaValue = metadata.getMetaValue(); + if (StringUtils.isNotEmpty(metaValue)) { + JsonParser parser = new JsonParser(); + JsonObject jsonObject = parser.parse(metaValue).getAsJsonObject(); + return jsonObject.get(CertificateManagementConstants.IS_CERTIFICATE_DELETE_ENABLE).getAsBoolean(); + } + } + return false; + } catch (MetadataManagementException e) { + String msg = "Error occurred while getting the metadata entry for metaKey: " + CertificateManagementConstants.CERTIFICATE_DELETE; + log.error(msg, e); + throw new CertificateManagementException(msg, e); + } catch (JsonParseException e) { + String msg = "Error occurred while parsing the JSON metadata value for metaKey: " + CertificateManagementConstants.CERTIFICATE_DELETE; + log.error(msg, e); + throw new CertificateManagementException(msg, e); + } + } + @Override public List getCertificates() throws CertificateManagementException { try { diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagementConstants.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagementConstants.java index 8235b3ee77..f851bd05f0 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagementConstants.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagementConstants.java @@ -41,6 +41,12 @@ public final class CertificateManagementConstants { public static final int RSA_KEY_LENGTH = 2048; public static final String SIGNING_ALGORITHM = "SHA256withRSA"; + public static final int DEFAULT_PAGE_LIMIT = 50; + + public static final String CERTIFICATE_DELETE = "CERTIFICATE_DELETE"; + public static final String IS_CERTIFICATE_DELETE_ENABLE = "isCertificateDelete"; + + public static final class DataBaseTypes { private DataBaseTypes() { throw new AssertionError(); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagerUtil.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagerUtil.java index 4383396448..2da3d4d414 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagerUtil.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagerUtil.java @@ -19,15 +19,17 @@ package io.entgra.device.mgt.core.certificate.mgt.core.util; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; import io.entgra.device.mgt.core.certificate.mgt.core.config.CertificateConfigurationManager; import io.entgra.device.mgt.core.certificate.mgt.core.config.CertificateManagementConfig; import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.JNDILookupDefinition; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; +import org.wso2.carbon.context.PrivilegedCarbonContext; import javax.sql.DataSource; import javax.xml.XMLConstants; @@ -41,6 +43,7 @@ public class CertificateManagerUtil { public static final String GENERAL_CONFIG_RESOURCE_PATH = "general"; public static final String MONITORING_FREQUENCY = "notifierFrequency"; + private static MetadataManagementService metadataManagementService; private static final Log log = LogFactory.getLog(CertificateManagerUtil.class); public static Document convertToDocument(File file) throws CertificateManagementException { @@ -105,4 +108,26 @@ public class CertificateManagerUtil { return limit; } + /** + * Initializing and accessing method for MetadataManagementService. + * + * @return MetadataManagementService instance + * @throws IllegalStateException if metadataManagementService cannot be initialized + */ + public static MetadataManagementService getMetadataManagementService() { + if (metadataManagementService == null) { + synchronized (CertificateManagerUtil.class) { + if (metadataManagementService == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + metadataManagementService = (MetadataManagementService) ctx.getOSGiService( + MetadataManagementService.class, null); + if (metadataManagementService == null) { + throw new IllegalStateException("Metadata Management service not initialized."); + } + } + } + } + return metadataManagementService; + } + } \ No newline at end of file diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java index 1f7dbf0f3c..7aff1cd586 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java @@ -18,10 +18,7 @@ package io.entgra.device.mgt.core.certificate.mgt.core.impl; -import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; -import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; -import io.entgra.device.mgt.core.certificate.mgt.core.exception.TransactionManagementException; -import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementServiceImpl; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; @@ -33,6 +30,10 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.wso2.carbon.base.MultitenantConstants; +import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; +import io.entgra.device.mgt.core.certificate.mgt.core.exception.TransactionManagementException; +import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementServiceImpl; import org.wso2.carbon.context.PrivilegedCarbonContext; import javax.sql.DataSource; @@ -110,7 +111,8 @@ public class CertificateManagementServiceImplNegativeTests extends PowerMockTest public void negativeTestGetAllCertificates() throws Exception { PowerMockito.mockStatic(CertificateManagementDAOFactory.class); PowerMockito.doThrow(new SQLException()).when(CertificateManagementDAOFactory.class, "openConnection"); - instance.getAllCertificates(1, 2); + CertificatePaginationRequest request = new CertificatePaginationRequest(0, 2); + instance.getAllCertificates(request); } @Test(description = "This test case tests behaviour when an error occurs getting the list of certificates from repository" @@ -118,7 +120,8 @@ public class CertificateManagementServiceImplNegativeTests extends PowerMockTest public void negativeTestGetAllCertificates2() throws Exception { CertificateManagementDAOFactory.init(daoExceptionDatasource); CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance(); - instance1.getAllCertificates(1, 2); + CertificatePaginationRequest request = new CertificatePaginationRequest(0, 2); + instance.getAllCertificates(request); } @Test(description = "This test case tests behaviour when data source transaction error occurs when removing the certificate" diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java index 6337837ef1..a3cca775a9 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java @@ -32,6 +32,7 @@ import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagement import io.entgra.device.mgt.core.certificate.mgt.core.util.DummyCertificate; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -210,14 +211,15 @@ public class CertificateManagementServiceImplTests extends BaseDeviceManagementC X509Certificate x509Certificate = managementService.generateX509Certificate(); CertificateResponse certificateResponse = managementService.retrieveCertificate(x509Certificate.getSerialNumber().toString()); Assert.assertNotNull(certificateResponse); - Assert.assertEquals(x509Certificate.getSerialNumber(), certificateResponse.getCertificateserial()); + Assert.assertEquals(x509Certificate.getSerialNumber(), certificateResponse.getCertificateSerial()); } @Test(description = "This test case tests the retrieval of Certificates from keystore in desired pagination") public void testGetAllCertificatesPaginated() throws CertificateManagementException, KeystoreException { managementService.generateX509Certificate(); managementService.generateX509Certificate(); - PaginationResult allCertificates = managementService.getAllCertificates(0, 2); + CertificatePaginationRequest request = new CertificatePaginationRequest(0,2); + PaginationResult allCertificates = managementService.getAllCertificates(request); Assert.assertEquals(allCertificates.getData().size(), 2); log.info("GetAllCertificatesPaginated Test Successful"); } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql index 46582aa390..0fb769e406 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql @@ -37,6 +37,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, CERTIFICATE BLOB DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, + DEVICE_IDENTIFIER VARCHAR(300), USERNAME VARCHAR(500) DEFAULT NULL, PRIMARY KEY (ID) ); \ No newline at end of file diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml index da2dfcd2df..b218c20dd4 100644 --- a/components/certificate-mgt/pom.xml +++ b/components/certificate-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml index 0e946ff81d..6bed168fde 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml index 60ea674ab9..66530f647c 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml index 04a9e048e6..d4c7eda985 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml @@ -21,7 +21,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml index c64715c941..90a6331adb 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml index f4e6546fe8..e5b71633c3 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml index 4054d7c446..b3fabbd1a3 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml index 64f3d4265b..44fac89fc6 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml index ffbef61ef9..5a27316b32 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml index e6e8dde418..173081ceff 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/pom.xml b/components/device-mgt-extensions/pom.xml index 4a0aa662a3..6fce15dac4 100644 --- a/components/device-mgt-extensions/pom.xml +++ b/components/device-mgt-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml index dc7016b80f..d5bbb2e967 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml @@ -22,7 +22,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml @@ -448,5 +448,10 @@ io.entgra.device.mgt.core.apimgt.analytics.extension provided + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.apimgt.webapp.publisher + provided + \ No newline at end of file diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ApplicationUninstallation.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ApplicationUninstallation.java index a38ae2982d..f78d15966e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ApplicationUninstallation.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ApplicationUninstallation.java @@ -41,6 +41,14 @@ public class ApplicationUninstallation { @Pattern(regexp = "^[A-Za-z]*$") String type; + String name; + + String platform; + + String version; + + String user; + public ApplicationUninstallation() { } @@ -49,6 +57,47 @@ public class ApplicationUninstallation { this.type = type; } + public ApplicationUninstallation(String appIdentifier, String type, String name, String platform, String version, String user) { + this.appIdentifier = appIdentifier; + this.type = type; + this.name = name; + this.platform = platform; + this.version = version; + this.user = user; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPlatform() { + return platform; + } + + public void setPlatform(String platform) { + this.platform = platform; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + public String getAppIdentifier() { return appIdentifier; } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/RoleInfo.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/RoleInfo.java index c67634446d..6269bcbcba 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/RoleInfo.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/RoleInfo.java @@ -31,6 +31,11 @@ public class RoleInfo { @ApiModelProperty(name = "permissions", value = "Lists out all the permissions associated with roles.", required = true, dataType = "List[java.lang.String]") private String[] permissions; + + @ApiModelProperty(name = "removedPermissions", value = "Lists out all the permissions unassociated with roles.", + required = true, dataType = "List[java.lang.String]") + private String[] removedPermissions; + @ApiModelProperty(name = "users", value = "The list of users assigned to the selected role.", required = true, dataType = "List[java.lang.String]") private String[] users; @@ -74,4 +79,7 @@ public class RoleInfo { this.permissionList = permissionList; } + public String[] getRemovedPermissions() { return removedPermissions; } + + public void setRemovedPermissions(String[] removedPermissions) { this.removedPermissions = removedPermissions; } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ActivityInfoProviderService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ActivityInfoProviderService.java index d4f5881670..42e9d47ff4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ActivityInfoProviderService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ActivityInfoProviderService.java @@ -58,9 +58,9 @@ import java.util.List; @Scope( name = "Get activities", description = "Get activities", - key = "perm:get-activity", + key = "dm:activity:get", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/devices/owning-device/activities/view"} ) } ) @@ -79,7 +79,7 @@ public interface ActivityInfoProviderService { tags = "Activity Info Provider", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:get-activity") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:activity:get") }) } ) @@ -153,7 +153,7 @@ public interface ActivityInfoProviderService { tags = "Activity Info Provider", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:get-activity") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:activity:get") }) }, nickname = "getActivitiesByActivityIdList" @@ -216,7 +216,7 @@ public interface ActivityInfoProviderService { tags = "Activity Info Provider", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:get-activity") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:activity:get") }) } ) @@ -290,7 +290,17 @@ public interface ActivityInfoProviderService { "Provide the value in the Java Date Format: EEE, d MMM yyyy HH:mm:ss Z\n." + "Example: Mon, 05 Jan 2014 15:10:00 +0200", required = false) - @HeaderParam("If-Modified-Since") String ifModifiedSince); + @HeaderParam("If-Modified-Since") String ifModifiedSince, + @ApiParam( + name = "response", + value = "The starting pagination index for the complete list of qualified items.", + required = false) + @QueryParam("response") Boolean response, + @ApiParam( + name = "appInstall", + value = "The starting pagination index for the complete list of qualified items.", + required = false) + @QueryParam("appInstall") Boolean appInstall); @GET @Path("/type/{operationCode}") @@ -303,7 +313,7 @@ public interface ActivityInfoProviderService { tags = "Activity Info Provider", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:get-activity") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:activity:get") }) }, nickname = "getActivitiesByOperationCode" @@ -367,7 +377,7 @@ public interface ActivityInfoProviderService { tags = "Activity Info Provider", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:get-activity") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:activity:get") }) }, nickname = "getActivitiesWithFilters" @@ -438,6 +448,11 @@ public interface ActivityInfoProviderService { value = "Operation Code to filter" ) @QueryParam("operationCode") String operationCode, + @ApiParam( + name = "operationId", + value = "Operation Id to filter" + ) + @QueryParam("operationId") int operationId, @ApiParam( name = "deviceType", value = "Device Type to filter" diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/AnalyticsArtifactsManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/AnalyticsArtifactsManagementService.java index fd03db1080..f509284431 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/AnalyticsArtifactsManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/AnalyticsArtifactsManagementService.java @@ -51,49 +51,49 @@ import javax.ws.rs.core.Response; @Scope( name = "Create Event Stream Artifact", description = "Create Event Stream Artifact", - key = "perm:analytics:artifacts:stream", + key = "dm:an:artifacts:stream:add", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/analytics/artifacts/stream/add"}), @Scope( name = "Delete Stream Artifact", description = "Delete Stream Artifact", - key = "perm:analytics:artifacts:stream:delete", + key = "dm:an:artifacts:stream:delete", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/analytics/artifacts/stream/delete"}), @Scope( name = "Create Event Receiver Artifact", description = "Create Event Receiver Artifact", - key = "perm:analytics:artifacts:receiver", + key = "dm:an:artifacts:rcv:add", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/analytics/artifacts/receiver/add"}), @Scope( name = "Delete Receiver Artifact", description = "Delete Receiver Artifact", - key = "perm:analytics:artifacts:receiver:delete", + key = "dm:an:artifacts:rcv:delete", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/analytics/artifacts/receiver/delete"}), @Scope( name = "Create Event Publisher Artifact", description = "Create Event Publisher Artifact", - key = "perm:analytics:artifacts:publisher", + key = "dm:an:artifacts:pub:add", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/analytics/artifacts/publisher/add"}), @Scope( name = "Delete Publisher Artifact", description = "Delete Publisher Artifact", - key = "perm:analytics:artifacts:publisher:delete", + key = "dm:an:artifacts:pub:delete", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/analytics/artifacts/publisher/delete"}), @Scope( name = "Create Siddhi Script Artifact", description = "Create Siddhi Script Artifact", - key = "perm:analytics:artifacts:siddhi", + key = "dm:an:artifacts:siddhi:add", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/analytics/artifacts/siddhi-script/add"}), @Scope( name = "Delete Siddhi Script Artifact", description = "Delete Siddhi Script Artifact", - key = "perm:analytics:artifacts:siddhi:delete", + key = "dm:an:artifacts:siddhi:delete", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/analytics/artifacts/siddhi-script/delete"}) } @@ -118,7 +118,7 @@ public interface AnalyticsArtifactsManagementService { @Extension(properties = { @ExtensionProperty( name = Constants.SCOPE, - value = "perm:analytics:artifacts:stream" + value = "dm:an:artifacts:stream:add" )}) } ) @@ -176,7 +176,7 @@ public interface AnalyticsArtifactsManagementService { @Extension(properties = { @ExtensionProperty( name = Constants.SCOPE, - value = "perm:analytics:artifacts:stream" + value = "dm:an:artifacts:stream:add" )}) } ) @@ -222,7 +222,7 @@ public interface AnalyticsArtifactsManagementService { @Extension(properties = { @ExtensionProperty( name = Constants.SCOPE, - value = "perm:analytics:artifacts:stream:delete" + value = "dm:an:artifacts:stream:delete" )}) } ) @@ -275,7 +275,7 @@ public interface AnalyticsArtifactsManagementService { @Extension(properties = { @ExtensionProperty( name = Constants.SCOPE, - value = "perm:analytics:artifacts:receiver" + value = "dm:an:artifacts:rcv:add" )}) } ) @@ -327,7 +327,7 @@ public interface AnalyticsArtifactsManagementService { @Extension(properties = { @ExtensionProperty( name = Constants.SCOPE, - value = "perm:analytics:artifacts:receiver" + value = "dm:an:artifacts:rcv:add" )}) } ) @@ -374,7 +374,7 @@ public interface AnalyticsArtifactsManagementService { @Extension(properties = { @ExtensionProperty( name = Constants.SCOPE, - value = "perm:analytics:artifacts:receiver:delete" + value = "dm:an:artifacts:rcv:delete" )}) } ) @@ -421,7 +421,7 @@ public interface AnalyticsArtifactsManagementService { @Extension(properties = { @ExtensionProperty( name = Constants.SCOPE, - value = "perm:analytics:artifacts:publisher" + value = "dm:an:artifacts:pub:add" )}) } ) @@ -473,7 +473,7 @@ public interface AnalyticsArtifactsManagementService { @Extension(properties = { @ExtensionProperty( name = Constants.SCOPE, - value = "perm:analytics:artifacts:publisher" + value = "dm:an:artifacts:pub:add" )}) } ) @@ -520,7 +520,7 @@ public interface AnalyticsArtifactsManagementService { @Extension(properties = { @ExtensionProperty( name = Constants.SCOPE, - value = "perm:analytics:artifacts:publisher:delete" + value = "dm:an:artifacts:pub:delete" )}) } ) @@ -564,7 +564,7 @@ public interface AnalyticsArtifactsManagementService { @Extension(properties = { @ExtensionProperty( name = Constants.SCOPE, - value = "perm:analytics:artifacts:siddhi" + value = "dm:an:artifacts:siddhi:add" )}) } ) @@ -615,7 +615,7 @@ public interface AnalyticsArtifactsManagementService { @Extension(properties = { @ExtensionProperty( name = Constants.SCOPE, - value = "perm:analytics:artifacts:siddhi:delete" + value = "dm:an:artifacts:siddhi:delete" ) }) } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ConfigurationManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ConfigurationManagementService.java index 720b6ea184..5957783c3a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ConfigurationManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ConfigurationManagementService.java @@ -55,14 +55,14 @@ import javax.ws.rs.core.Response; @Scope( name = "View configurations", description = "", - key = "perm:view-configuration", + key = "dm:conf:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/platform-configurations/view"} ), @Scope( name = "Manage configurations", description = "", - key = "perm:manage-configuration", + key = "dm:conf:manage", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/platform-configurations/manage"} ) @@ -81,7 +81,7 @@ public interface ConfigurationManagementService { tags = "Configuration Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:view-configuration") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:conf:view") }) } ) @@ -141,7 +141,7 @@ public interface ConfigurationManagementService { tags = "Configuration Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:manage-configuration") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:conf:manage") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceAgentService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceAgentService.java index 0dbc238688..1aee1b1b29 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceAgentService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceAgentService.java @@ -57,37 +57,37 @@ import java.util.Map; @Scope( name = "Enroll Device", description = "Register a device", - key = "perm:device:enroll", + key = "dm:device:enroll", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/devices/owning-device/add"} ), @Scope( name = "Modify Device", description = "Modify a device", - key = "perm:device:modify", + key = "dm:device:modify", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/devices/owning-device/modify"} ), @Scope( name = "Disenroll Device", description = "Disenroll a device", - key = "perm:device:disenroll", + key = "dm:device:disenroll", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/remove"} + permissions = {"/device-mgt/devices/owning-device/disenroll"} ), @Scope( name = "Publish Event", description = "publish device event", - key = "perm:device:publish-event", + key = "dm:device:event:publish", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/event"} + permissions = {"/device-mgt/devices/owning-device/event/publish"} ), @Scope( name = "Getting Device Operation Details", description = "Getting Device Operation Details", - key = "perm:device:operations", + key = "dm:devices:ops:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/devices/owning-device/operations/view"} ) } ) @@ -103,7 +103,7 @@ public interface DeviceAgentService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:enroll") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device:enroll") }) } ) @@ -155,7 +155,7 @@ public interface DeviceAgentService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:disenroll") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device:disenroll") }) } ) @@ -185,7 +185,7 @@ public interface DeviceAgentService { tags = "Device Agent Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:modify") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device:modify") }) } ) @@ -243,7 +243,7 @@ public interface DeviceAgentService { tags = "Device Agent Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:publish-event") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device:event:publish") }) }, nickname = "publishEventFromAgent" @@ -309,7 +309,7 @@ public interface DeviceAgentService { tags = "Device Agent Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:publish-event") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device:event:publish") }) }, nickname = "publishEventsByTypeAndDevice" @@ -376,7 +376,7 @@ public interface DeviceAgentService { tags = "Device Agent Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:operations") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:ops:view") }) } ) @@ -435,7 +435,7 @@ public interface DeviceAgentService { tags = "Device Agent Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:operations") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:ops:view") }) } ) @@ -493,7 +493,7 @@ public interface DeviceAgentService { tags = "Device Agent Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:operations") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:ops:view") }) } ) @@ -552,7 +552,7 @@ public interface DeviceAgentService { tags = "Device Agent Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:modify") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device:modify") }) } ) @@ -612,7 +612,7 @@ public interface DeviceAgentService { tags = "Device Agent Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:operations") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:ops:view") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceEventManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceEventManagementService.java index 8c532f4e23..fd7258e3c0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceEventManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceEventManagementService.java @@ -51,16 +51,16 @@ import java.util.List; @Scope( name = "Add or Delete Event Definition for device type", description = "Add or Delete Event Definition for device type", - key = "perm:device-types:events", + key = "dm:device-type:event:modify", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/device-type/add"} + permissions = {"/device-mgt/devices/owning-device/event/modify"} ), @Scope( name = "Get Events Details of a Device Type", description = "Get Events Details of a Device Type", - key = "perm:device-types:events:view", + key = "dm:device-type:event:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/devices/owning-device/event/view"} ) } ) @@ -80,7 +80,7 @@ public interface DeviceEventManagementService { tags = "Device Event Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device-type:event:modify") }) } ) @@ -139,7 +139,7 @@ public interface DeviceEventManagementService { tags = "Device Event Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device-type:event:modify") }) } ) @@ -191,7 +191,7 @@ public interface DeviceEventManagementService { // tags = "Device Event Management", // extensions = { // @Extension(properties = { -// @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") +// @ExtensionProperty(name = Constants.SCOPE, value = "dm:device-type:event:view") // }) // } // ) @@ -253,7 +253,7 @@ public interface DeviceEventManagementService { // tags = "Device Event Management", // extensions = { // @Extension(properties = { -// @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") +// @ExtensionProperty(name = Constants.SCOPE, value = "dm:device-type:event:view") // }) // } // ) @@ -309,7 +309,7 @@ public interface DeviceEventManagementService { // tags = "Device Event Management", // extensions = { // @Extension(properties = { -// @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") +// @ExtensionProperty(name = Constants.SCOPE, value = "dm:device-type:event:view") // }) // } // ) @@ -369,7 +369,7 @@ public interface DeviceEventManagementService { tags = "Device Event Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device-type:event:view") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceManagementService.java index 96091625ba..c42557b7df 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceManagementService.java @@ -41,6 +41,7 @@ import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; +import java.util.Map; /** * Device related REST-API. This can be used to manipulated device related details. @@ -65,91 +66,91 @@ import java.util.List; @Scope( name = "Getting Details of Registered Devices", description = "Getting Details of Registered Devices", - key = "perm:devices:view", + key = "dm:devices:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/devices/owning-device/view"} ), @Scope( name = "Getting Details of a Device", description = "Getting Details of a Device", - key = "perm:devices:details", + key = "dm:devices:details", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/devices/owning-device/details/view"} ), @Scope( name = "Update the device specified by device id", description = "Update the device specified by device id", - key = "perm:devices:update", + key = "dm:devices:update", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/devices/owning-device/update"} ), @Scope( name = "Delete the device specified by device id", description = "Delete the device specified by device id", - key = "perm:devices:delete", + key = "dm:devices:delete", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/devices/owning-device/delete"} ), @Scope( name = "Getting Feature Details of a Device", description = "Getting Feature Details of a Device", - key = "perm:devices:features", + key = "dm:devices:features:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/devices/owning-device/features/view"} ), @Scope( name = "Advanced Search for Devices", description = "Advanced Search for Devices", - key = "perm:devices:search", + key = "dm:devices:search", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/devices/owning-device/search"} ), @Scope( name = "Getting Installed Application Details of a Device", description = "Getting Installed Application Details of a Device", - key = "perm:devices:applications", + key = "dm:devices:app:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/devices/owning-device/apps/view"} ), @Scope( name = "Getting Device Operation Details", description = "Getting Device Operation Details", - key = "perm:devices:operations", + key = "dm:devices:ops:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/devices/owning-device/operations/view"} ), @Scope( name = "Get the details of the policy that is enforced on a device.", description = "Get the details of the policy that is enforced on a device.", - key = "perm:devices:effective-policy", + key = "dm:devices:policy:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/devices/owning-device/policies/view"} ), @Scope( name = "Getting Policy Compliance Details of a Device", description = "Getting Policy Compliance Details of a Device", - key = "perm:devices:compliance-data", + key = "dm:devices:compliance:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/devices/owning-device/compliance/view"} ), @Scope( name = "Change device status.", description = "Change device status.", - key = "perm:devices:change-status", + key = "dm:devices:status:change", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/devices/change-status"} ), @Scope( name = "Enroll Device", description = "Register a device", - key = "perm:device:enroll", + key = "dm:device:enroll", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/devices/owning-device/add"} ), @Scope( name = "Viewing Enrollment Guide", description = "Show enrollment guide to users", - key = "perm:devices:enrollment-guide:view", + key = "dm:devices:enrollment-guide:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/devices/enrollment-guide/view"} ), @@ -170,7 +171,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -259,6 +260,12 @@ public interface DeviceManagementService { required = false) @QueryParam("serialNumber") String serialNumber, + @ApiParam( + name = "customProperty", + value = "CustomProperty from device as a JSON encoded string.", + required = false) + @QueryParam("customProperty") + String customProperty, @ApiParam( name = "status", value = "Provide the device status details, such as active or inactive.", @@ -319,7 +326,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -395,7 +402,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:details") }) } ) @@ -485,7 +492,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:details") }) } ) @@ -573,7 +580,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:details") }) } ) @@ -649,7 +656,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:details") }) } ) @@ -727,7 +734,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:enrollment-guide:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:enrollment-guide:view") }) } ) @@ -778,7 +785,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:details") }) } ) @@ -814,9 +821,9 @@ public interface DeviceManagementService { Response getDeviceByIdList(List deviceIds); - @PUT + @GET @Produces(MediaType.APPLICATION_JSON) - @Path("/{type}/{id}") + @Path("/{type}/{id}/status") @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", @@ -825,7 +832,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) }, nickname = "isEnrolledByType" @@ -882,7 +889,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:details") }) } ) @@ -959,7 +966,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:details") }) } ) @@ -1035,7 +1042,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:details") }) } ) @@ -1115,7 +1122,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:update") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:update") }) } ) @@ -1190,7 +1197,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:delete") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:delete") }) }, nickname = "deleteDeviceByTypeAndId" @@ -1261,7 +1268,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:features") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:features:view") }) } ) @@ -1343,7 +1350,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:search") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:search") }) } ) @@ -1423,7 +1430,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:search") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:search") }) } ) @@ -1501,7 +1508,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:applications") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:app:view") }) } @@ -1606,7 +1613,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:applications") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:app:view") }) }) @ApiResponses( @@ -1633,7 +1640,31 @@ public interface DeviceManagementService { value = "The package name of the app user want to uninstall", required = true) @QueryParam("packageName") - String packageName); + String packageName, + @ApiParam( + name = "platform", + value = "The platform of the app user want to uninstall", + required = false) + @QueryParam("platform") + String platform, + @ApiParam( + name = "name", + value = "The name of the app user want to uninstall", + required = false) + @QueryParam("name") + String name, + @ApiParam( + name = "version", + value = "The version of the app user want to uninstall", + required = false) + @QueryParam("version") + String version, + @ApiParam( + name = "user", + value = "The user who triggered the app uninstall", + required = false) + @QueryParam("user") + String user); @GET @Produces(MediaType.APPLICATION_JSON) @@ -1646,7 +1677,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:operations") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:ops:view") }) } ) @@ -1788,7 +1819,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:effective-policy") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:policy:view") }) } ) @@ -1877,7 +1908,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:compliance-data") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:compliance:view") }) } ) @@ -1924,7 +1955,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -1992,7 +2023,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -2062,7 +2093,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:change-status") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:status:change") }) } ) @@ -2138,7 +2169,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:operations") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:ops:view") }) } ) @@ -2195,7 +2226,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -2264,7 +2295,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -2334,7 +2365,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:change-status") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:status:change") }) } ) @@ -2395,7 +2426,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:compliance-data") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:compliance:view") }) } ) @@ -2463,7 +2494,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:compliance-data") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:compliance:view") }) } ) @@ -2503,7 +2534,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:applications") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:app:view") }) } ) @@ -2570,7 +2601,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:applications") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:app:view") }) } ) @@ -2615,7 +2646,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:operations") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:ops:view") }) } ) @@ -2667,7 +2698,7 @@ public interface DeviceManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -2706,7 +2737,7 @@ public interface DeviceManagementService { notes = "Getting the default access token by using given client ID and the client secret value.", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:enroll") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device:enroll") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceTypeManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceTypeManagementService.java index e355c5bfae..7ad07f5c0c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceTypeManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceTypeManagementService.java @@ -52,28 +52,28 @@ import javax.ws.rs.core.Response; @Scope( name = "Getting the Supported Device Platforms", description = "Getting the Supported Device Platforms", - key = "perm:device-types:types", + key = "dm:device-type:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/device-type/view"} ), @Scope( name = "Get Feature Details of a Device Type", description = "Get Feature Details of a Device Type", - key = "perm:device-types:features", + key = "dm:device-type:features:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/device-type/features/view"} ), @Scope( name = "Get Config Details of a Device Type", description = "Get Config Details of a Device Type", - key = "perm:device-types:configs", + key = "dm:device-type:conf:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/device-type/config/view"} ), @Scope( name = "Getting Details of Policies", description = "Getting Details of Policies", - key = "perm:policies:get-details", + key = "dm:policies:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/policies/view"} ) @@ -95,7 +95,7 @@ public interface DeviceTypeManagementService { tags = "Device Type Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:types") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device-type:view") }) }, nickname = "getAllDeviceTypesPaginated" @@ -177,7 +177,7 @@ public interface DeviceTypeManagementService { tags = "Device Type Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:types") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device-type:view") }) }, nickname = "getDeviceTypeByDeviceTypeName" @@ -232,7 +232,7 @@ public interface DeviceTypeManagementService { tags = "Device Type Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:features") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device-type:features:view") }) } ) @@ -311,7 +311,7 @@ public interface DeviceTypeManagementService { tags = "Device Type Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:configs") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:device-type:conf:view") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GeoLocationBasedService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GeoLocationBasedService.java index 5f97523365..c5faaf1f1c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GeoLocationBasedService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GeoLocationBasedService.java @@ -54,21 +54,21 @@ import java.util.List; @Scope( name = "View Analytics", description = "", - key = "perm:geo-service:analytics-view", + key = "dm:geo:an:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/devices/owning-device/view-analytics"} ), @Scope( name = "Manage Alerts", description = "", - key = "perm:geo-service:alerts-manage", + key = "dm:geo:alerts:manage", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/devices/owning-device/manage-alerts"} ), @Scope( name = "Manage Geo Fences", description = "", - key = "perm:geo-service:geo-fence", + key = "dm:geo:geo-fence:manage", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/devices/owning-device/manage-geo-fence"} ) @@ -93,7 +93,7 @@ public interface GeoLocationBasedService { // tags = "Geo Service Management", // extensions = { // @Extension(properties = { -// @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:analytics-view") +// @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:an:view") // }) // } // ) @@ -162,7 +162,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:analytics-view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:an:view") }) } ) @@ -246,7 +246,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:analytics-view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:an:view") }) } ) @@ -363,7 +363,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:alerts:manage") }) } ) @@ -429,7 +429,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:alerts:manage") }) } ) @@ -482,7 +482,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:alerts:manage") }) } ) @@ -547,7 +547,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:alerts:manage") }) } ) @@ -600,7 +600,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:alerts:manage") }) } ) @@ -664,7 +664,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:alerts:manage") }) } ) @@ -717,7 +717,7 @@ public interface GeoLocationBasedService { // tags = "Geo Service Management", // extensions = { // @Extension(properties = { -// @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") +// @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:alerts:manage") // }) // } // ) @@ -786,7 +786,7 @@ public interface GeoLocationBasedService { // tags = "Geo Service Management", // extensions = { // @Extension(properties = { -// @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") +// @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:alerts:manage") // }) // } // ) @@ -845,7 +845,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:alerts:manage") }) } ) @@ -910,7 +910,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:alerts:manage") }) } ) @@ -960,7 +960,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:geo-fence") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:geo-fence:manage") }) } ) @@ -1002,7 +1002,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:geo-fence") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:geo-fence:manage") }) }, nickname = "getGeofenceByFenceId" @@ -1053,7 +1053,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:geo-fence") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:geo-fence:manage") }) } ) @@ -1105,7 +1105,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:geo-fence") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:geo-fence:manage") }) } ) @@ -1151,7 +1151,7 @@ public interface GeoLocationBasedService { tags = "Geo Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:geo-fence") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:geo:geo-fence:manage") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GroupManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GroupManagementService.java index c39ae0b540..c302d15edf 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GroupManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GroupManagementService.java @@ -82,114 +82,107 @@ import java.util.List; @Scope( name = "Get the list of groups belongs to current user.", description = "Get the list of groups belongs to current user.", - key = "perm:groups:groups", + key = "gm:groups:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/groups/view"} ), @Scope( name = "Get the count of groups belongs to current user.", description = "Get the count of groups belongs to current user.", - key = "perm:groups:count", + key = "gm:groups:count", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/groups/view"} + permissions = {"/device-mgt/groups/count"} ), @Scope( name = "Add new device group to the system.", description = "Add new device group to the system.", - key = "perm:groups:add", + key = "gm:groups:add", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/groups/add"} ), @Scope( name = "View group specified", description = "View group specified", - key = "perm:groups:groups-view", + key = "gm:groups:groups-view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/groups/view"} + permissions = {"/device-mgt/groups/specified-groups/view"} ), @Scope( name = "Update a group", description = "Update a group", - key = "perm:groups:update", + key = "gm:groups:update", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/groups/update"} ), @Scope( name = "Delete a group", description = "Delete a group", - key = "perm:groups:remove", + key = "gm:groups:remove", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/groups/remove"} ), @Scope( name = "Manage group sharing with a user", description = "Manage group sharing with a user", - key = "perm:groups:share", + key = "gm:roles:share", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/groups/share"} ), @Scope( name = "View list of roles of a device group", description = "View list of roles of a device group", - key = "perm:groups:roles", + key = "gm:roles:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/groups/roles/view"} ), @Scope( name = "View list of devices in the device group", description = "View list of devices in the device group", - key = "perm:groups:devices", + key = "gm:devices:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/groups/devices/view"} ), @Scope( name = "View list of device count in the device group", description = "View list of device count in the device group", - key = "perm:groups:devices-count", + key = "gm:devices:count", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/groups/devices/view"} + permissions = {"/device-mgt/groups/devices/count"} ), @Scope( name = "Add devices to group", description = "Add devices to group", - key = "perm:groups:devices-add", + key = "gm:devices:add", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/groups/devices/add"} ), @Scope( name = "Remove devices from group", description = "Remove devices from group", - key = "perm:groups:devices-remove", + key = "gm:devices:remove", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/groups/devices/remove"} ), @Scope( name = "Assign devices to groups", description = "Assign devices to groups", - key = "perm:groups:assign", + key = "gm:devices:assign", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/groups/devices/add"} + permissions = {"/device-mgt/groups/devices/assign"} ), @Scope( name = "List of groups that have the device", description = "List of groups that have the device", - key = "perm:groups:device", + key = "gm:groups:device:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/groups/devices/view"} + permissions = {"/device-mgt/groups/device-groups/view"} ), @Scope( name = "View whether the groups has relevant device types", description = "View whether the groups has relevant device types", - key = "perm:groups:devices-types", + key = "gm:devices-types:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/groups/devices/types"} - ), - @Scope( - name = "View whether the groups has relevant device types", - description = "View whether the groups has relevant device types", - key = "perm:groups:add", - roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/groups/device-types"} + permissions = {"/device-mgt/groups/device-types/view"} ) } ) @@ -209,7 +202,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:groups") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:groups:view") }) }, nickname = "getGroupsWithFilter" @@ -284,7 +277,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:groups") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:groups:view") }) }, nickname = "getGroupsWithHierarchyNonAdmin" @@ -355,6 +348,52 @@ public interface GroupManagementService { @QueryParam("limit") int limit); + @Path("/hierarchy/count") + @GET + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_GET, + value = "Getting the Number of Hirarchical Device Groups", + notes = "Get the number of hierarchical device groups in the server that the current signed in user can access.", + tags = "Device Group Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "gm:groups:count") + }) + }, + nickname = "getGroupCountNonAdmin" + + ) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the hierarchical device group count.", + response = DeviceGroupList.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching the group count.", + response = ErrorResponse.class) + }) + Response getHierarchicalGroupCount(); + @Path("/count") @GET @ApiOperation( @@ -365,7 +404,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:count") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:groups:count") }) }, nickname = "getGroupCountNonAdmin" @@ -410,7 +449,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:add") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:groups:add") }) }, nickname = "createGroupByGroupObject" @@ -479,7 +518,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:groups-view") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:groups:groups-view") }) } ) @@ -552,7 +591,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:groups-view") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:groups:groups-view") }) }, nickname = "getGroupByGroupNameFilter" @@ -619,7 +658,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:update") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:groups:update") }) } ) @@ -677,7 +716,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:remove") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:groups:remove") }) } ) @@ -734,7 +773,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:share") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:roles:share") }) } ) @@ -791,7 +830,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:roles") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:roles:view") }) } ) @@ -843,7 +882,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:devices") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:devices:view") }) } ) @@ -917,7 +956,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:devices-count") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:devices:count") }) } ) @@ -970,7 +1009,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:devices-add") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:devices:add") }) } ) @@ -1026,7 +1065,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:devices-remove") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:devices:remove") }) } ) @@ -1083,7 +1122,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:assign") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:devices:assign") }) } ) @@ -1138,7 +1177,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:device") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:groups:device:view") }) }, nickname = "getGroupsNonAdmin" @@ -1200,7 +1239,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:devices-types") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:devices-types:view") }) }, nickname = "getGroupByGroupNameFilter" @@ -1255,7 +1294,7 @@ public interface GroupManagementService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:add") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:groups:add") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/MetadataService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/MetadataService.java index 5f79032843..1fcdb4d0e8 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/MetadataService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/MetadataService.java @@ -54,28 +54,28 @@ import javax.ws.rs.core.Response; @Scope( name = "View metadata records", description = "View metadata records", - key = "perm:metadata:view", + key = "dm:metadata:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/metadata/view"} ), @Scope( name = "Create a metadata record", description = "Create a metadata record", - key = "perm:metadata:create", + key = "dm:metadata:create", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/metadata/create"} ), @Scope( name = "Update a metadata record", description = "Updating a specified metadata record", - key = "perm:metadata:update", + key = "dm:metadata:update", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/metadata/update"} ), @Scope( name = "Delete a metadata record", description = "Delete a specified metadata record", - key = "perm:metadata:remove", + key = "dm:metadata:remove", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/metadata/remove"} ) @@ -96,7 +96,7 @@ public interface MetadataService { tags = "Device Metadata Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:metadata:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:metadata:view") }) } ) @@ -152,7 +152,7 @@ public interface MetadataService { tags = "Device Metadata Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:metadata:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:metadata:view") }) } ) @@ -197,7 +197,7 @@ public interface MetadataService { tags = "Device Metadata Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:metadata:create") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:metadata:create") }) } ) @@ -248,7 +248,7 @@ public interface MetadataService { tags = "Device Metadata Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:metadata:update") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:metadata:update") }) } ) @@ -295,7 +295,7 @@ public interface MetadataService { tags = "Device Metadata Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:metadata:remove") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:metadata:remove") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/NotificationManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/NotificationManagementService.java index 5e804c3ce3..c86153ecc3 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/NotificationManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/NotificationManagementService.java @@ -54,16 +54,16 @@ import javax.ws.rs.core.Response; @Scope( name = "Getting All Device Notification Details", description = "Getting All Device Notification Details", - key = "perm:notifications:view", + key = "dm:notifications:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/notifications/view"} ), @Scope( name = "Updating the Device Notification Status", description = "Updating the Device Notification Status", - key = "perm:notifications:mark-checked", + key = "dm:notif:mark-checked", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/notifications/view"} + permissions = {"/device-mgt/notifications/update"} ) } ) @@ -82,7 +82,7 @@ public interface NotificationManagementService { tags = "Device Notification Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:notifications:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:notifications:view") }) } ) @@ -171,7 +171,7 @@ public interface NotificationManagementService { tags = "Device Notification Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:notifications:mark-checked") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:notif:mark-checked") }) } ) @@ -211,7 +211,7 @@ public interface NotificationManagementService { tags = "Device Notification Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:notifications:mark-checked") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:notif:mark-checked") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/PolicyManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/PolicyManagementService.java index deb3d4c8bb..9b550b9b65 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/PolicyManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/PolicyManagementService.java @@ -59,72 +59,72 @@ import java.util.List; @Scope( name = "Adding a Policy", description = "Adding a Policy", - key = "perm:policies:manage", + key = "pm:policies:add", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/policies/manage"} + permissions = {"/device-mgt/policies/add"} ), @Scope( name = "Getting Details of Policies", description = "Getting Details of Policies", - key = "perm:policies:get-details", + key = "dm:policies:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/policies/view"} ), @Scope( name = "Getting Details of a Policy", description = "Getting Details of a Policy", - key = "perm:policies:get-policy-details", + key = "pm:policies:details:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/policies/view"} + permissions = {"/device-mgt/policies/view-details"} ), @Scope( name = "Updating a Policy", description = "Updating a Policy", - key = "perm:policies:update", + key = "pm:policies:update", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/policies/manage"} + permissions = {"/device-mgt/policies/update"} ), @Scope( name = "Removing Multiple Policies", description = "Removing Multiple Policies", - key = "perm:policies:remove", + key = "pm:policies:remove", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/policies/manage"} + permissions = {"/device-mgt/policies/remove"} ), @Scope( name = "Activating Policies", description = "Activating Policies", - key = "perm:policies:activate", + key = "pm:policies:activate", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/policies/manage"} + permissions = {"/device-mgt/policies/activate"} ), @Scope( name = "Deactivating Policies", description = "Deactivating Policies", - key = "perm:policies:deactivate", + key = "pm:policies:deactivate", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/policies/manage"} + permissions = {"/device-mgt/policies/deactivate"} ), @Scope( name = "Applying Changes on Policies", description = "Applying Changes on Policies", - key = "perm:policies:changes", + key = "pm:policies:change", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/policies/manage"} + permissions = {"/device-mgt/policies/apply-changes"} ), @Scope( name = "Updating the Policy Priorities", description = "Updating the Policy Priorities", - key = "perm:policies:priorities", + key = "pm:policies:priorities:update", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/policies/manage"} + permissions = {"/device-mgt/policies/update-priority"} ), @Scope( name = "Fetching the Effective Policy", description = "Fetching the Effective Policy", - key = "perm:policies:effective-policy", + key = "pm:policies:effective-policy", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/policies/view"} + permissions = {"/device-mgt/policies/view-effective-policy"} ) } ) @@ -148,7 +148,7 @@ public interface PolicyManagementService { tags = "Device Policy Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:manage") + @ExtensionProperty(name = Constants.SCOPE, value = "pm:policies:add") }) } ) @@ -219,7 +219,7 @@ public interface PolicyManagementService { tags = "Device Policy Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:manage") + @ExtensionProperty(name = Constants.SCOPE, value = "pm:policies:add") }) } ) @@ -288,7 +288,7 @@ public interface PolicyManagementService { tags = "Device Policy Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:get-details") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:policies:view") }) } ) @@ -364,7 +364,7 @@ public interface PolicyManagementService { tags = "Device Policy Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:get-policy-details") + @ExtensionProperty(name = Constants.SCOPE, value = "pm:policies:details:view") }) } ) @@ -433,7 +433,7 @@ public interface PolicyManagementService { tags = "Device Policy Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:update") + @ExtensionProperty(name = Constants.SCOPE, value = "pm:policies:update") }) } ) @@ -502,7 +502,7 @@ public interface PolicyManagementService { tags = "Device Policy Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:remove") + @ExtensionProperty(name = Constants.SCOPE, value = "pm:policies:remove") }) } ) @@ -550,7 +550,7 @@ public interface PolicyManagementService { tags = "Device Policy Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:activate") + @ExtensionProperty(name = Constants.SCOPE, value = "pm:policies:activate") }) } ) @@ -592,7 +592,7 @@ public interface PolicyManagementService { tags = "Device Policy Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:deactivate") + @ExtensionProperty(name = Constants.SCOPE, value = "pm:policies:deactivate") }) } ) @@ -638,7 +638,7 @@ public interface PolicyManagementService { tags = "Device Policy Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:changes") + @ExtensionProperty(name = Constants.SCOPE, value = "pm:policies:change") }) } ) @@ -666,7 +666,7 @@ public interface PolicyManagementService { tags = "Device Policy Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:priorities") + @ExtensionProperty(name = Constants.SCOPE, value = "pm:policies:priorities:update") }) } ) @@ -702,7 +702,7 @@ public interface PolicyManagementService { tags = "Device Policy Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:effective-policy") + @ExtensionProperty(name = Constants.SCOPE, value = "pm:policies:effective-policy") }) } ) @@ -772,7 +772,7 @@ public interface PolicyManagementService { tags = "Device Policy Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:get-details") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:policies:view") }) }, nickname = "getPoliciesFilteredByType" @@ -856,7 +856,7 @@ public interface PolicyManagementService { tags = "Device Policy Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:get-details") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:policies:view") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RemoteSessionService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RemoteSessionService.java index e9bd6f6d9f..4df5b8c7e6 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RemoteSessionService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RemoteSessionService.java @@ -50,7 +50,7 @@ import javax.ws.rs.core.Response; @Scope( name = "Remote Session Connection", description = "", - key = "perm:remote-session-service:connect", + key = "dm:remote:connect", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/devices/owning-device/remote-session"} ) @@ -75,7 +75,7 @@ public interface RemoteSessionService { tags = "Remote Session Service Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:remote-session-service:connect") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:remote:connect") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ReportManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ReportManagementService.java index 89353182ad..af7c103764 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ReportManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ReportManagementService.java @@ -50,7 +50,7 @@ import java.util.List; @Scope( name = "Getting Details of Registered Devices", description = "Getting Details of Registered Devices", - key = "perm:devices:view", + key = "dm:devices:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/devices/owning-device/view"} ), @@ -73,7 +73,7 @@ public interface ReportManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -157,7 +157,7 @@ public interface ReportManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -229,7 +229,7 @@ public interface ReportManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -307,7 +307,7 @@ public interface ReportManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -366,7 +366,7 @@ public interface ReportManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -416,7 +416,7 @@ public interface ReportManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -491,7 +491,7 @@ public interface ReportManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) @@ -559,7 +559,7 @@ public interface ReportManagementService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:view") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RoleManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RoleManagementService.java index 5031f1598d..eedede200a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RoleManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RoleManagementService.java @@ -51,58 +51,58 @@ import java.util.List; @Scope( name = "Getting the List of Roles", description = "Getting the List of Roles", - key = "perm:roles:view", + key = "rm:roles:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/roles/view"} ), @Scope( name = "Getting Permission Details of a Role", description = "Getting Permission Details of a Role", - key = "perm:roles:permissions", + key = "rm:roles:permissions:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/roles/view"} + permissions = {"/device-mgt/roles/view-permissions"} ), @Scope( name = "Getting the List of Roles", description = "Getting the List of Roles", - key = "perm:roles:details", + key = "rm:roles:details:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/roles/view"} + permissions = {"/device-mgt/roles/view-details"} ), @Scope( name = "Adding a Role", description = "Adding a Role", - key = "perm:roles:add", + key = "rm:roles:add", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/roles/manage"} + permissions = {"/device-mgt/roles/add"} ), @Scope( name = "Adding a combined Role", description = "Adding a combined Role", - key = "perm:roles:create-combined-role", + key = "rm:roles:combined:add", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/roles/manage"} + permissions = {"/device-mgt/roles/combined-role/add"} ), @Scope( name = "Updating Role Details", description = "Updating Role Details", - key = "perm:roles:update", + key = "rm:roles:update", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/roles/manage"} + permissions = {"/device-mgt/roles/update"} ), @Scope( name = "Deleting a Role", description = "Deleting a Role", - key = "perm:roles:delete", + key = "rm:roles:delete", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/roles/manage"} + permissions = {"/device-mgt/roles/delete"} ), @Scope( name = "Adding Users to a Role", description = "Adding Users to a Role", - key = "perm:roles:add-users", + key = "rm:users:add", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/roles/manage"} + permissions = {"/device-mgt/roles/assign-user"} ) } ) @@ -122,7 +122,7 @@ public interface RoleManagementService { tags = "Role Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:roles:view") + @ExtensionProperty(name = Constants.SCOPE, value = "rm:roles:view") }) } ) @@ -198,7 +198,7 @@ public interface RoleManagementService { tags = "Role Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:roles:view") + @ExtensionProperty(name = Constants.SCOPE, value = "rm:roles:view") }) } ) @@ -296,7 +296,7 @@ public interface RoleManagementService { tags = "Role Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:roles:view") + @ExtensionProperty(name = Constants.SCOPE, value = "rm:roles:view") }) } ) @@ -382,7 +382,7 @@ public interface RoleManagementService { tags = "Role Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:roles:permissions") + @ExtensionProperty(name = Constants.SCOPE, value = "rm:roles:permissions:view") }) } ) @@ -457,7 +457,7 @@ public interface RoleManagementService { tags = "Role Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:roles:details") + @ExtensionProperty(name = Constants.SCOPE, value = "rm:roles:details:view") }) } ) @@ -531,7 +531,7 @@ public interface RoleManagementService { tags = "Role Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:roles:add") + @ExtensionProperty(name = Constants.SCOPE, value = "rm:roles:add") }) } ) @@ -593,7 +593,7 @@ public interface RoleManagementService { tags = "Role Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:roles:create-combined-role") + @ExtensionProperty(name = Constants.SCOPE, value = "rm:roles:combined:add") }) } ) @@ -657,7 +657,7 @@ public interface RoleManagementService { tags = "Role Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:roles:update") + @ExtensionProperty(name = Constants.SCOPE, value = "rm:roles:update") }) } ) @@ -727,7 +727,7 @@ public interface RoleManagementService { tags = "Role Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:roles:delete") + @ExtensionProperty(name = Constants.SCOPE, value = "rm:roles:delete") }) } ) @@ -779,7 +779,7 @@ public interface RoleManagementService { tags = "Role Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:roles:add-users") + @ExtensionProperty(name = Constants.SCOPE, value = "rm:users:add") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/UserManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/UserManagementService.java index e92d4a7081..b8a3c1e528 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/UserManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/UserManagementService.java @@ -51,91 +51,91 @@ import javax.ws.rs.core.Response; @Scope( name = "Adding a User", description = "Adding a User", - key = "perm:users:add", + key = "um:users:add", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/users/manage"} + permissions = {"/device-mgt/users/add"} ), @Scope( name = "Getting Details of a User", description = "Getting Details of a User", - key = "perm:users:details", + key = "um:users:details:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/users/view"} + permissions = {"/device-mgt/users/details/view"} ), @Scope( name = "Updating Details of a User", description = "Updating Details of a User", - key = "perm:users:update", + key = "um:users:update", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/users/manage"} + permissions = {"/device-mgt/users/update"} ), @Scope( name = "Deleting a User", description = "Deleting a User", - key = "perm:users:delete", + key = "um:users:delete", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/users/manage"} + permissions = {"/device-mgt/users/delete"} ), @Scope( name = "Getting the Role Details of a User", description = "Getting the Role Details of a User", - key = "perm:users:roles", + key = "um:roles:view", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/users/view"} + permissions = {"/device-mgt/users/roles/view"} ), @Scope( name = "Getting Details of Users", description = "Getting Details of Users", - key = "perm:users:user-details", + key = "um:users:user-details:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/users/view"} ), @Scope( name = "Getting the User Count", description = "Getting the User Count", - key = "perm:users:count", + key = "um:users:count", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/users/view"} + permissions = {"/device-mgt/users/count"} ), @Scope( name = "Getting the User existence status", description = "Getting the User existence status", - key = "perm:users:is-exist", + key = "um:users:is-exist", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/users/view"} + permissions = {"/device-mgt/users/existence/view"} ), @Scope( name = "Searching for a User Name", description = "Searching for a User Name", - key = "perm:users:search", + key = "um:users:search", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/users/view"} + permissions = {"/device-mgt/users/search"} ), @Scope( name = "Changing the User Password", description = "Adding a User", - key = "perm:users:credentials", + key = "um:users:cred:change", roles = {"Internal/devicemgt-user"}, - permissions = {"/login"} + permissions = {"/login/password/update"} ), @Scope( name = "Sending Enrollment Invitations to Users", description = "Sending Enrollment Invitations to Users", - key = "perm:users:send-invitation", + key = "um:users:invite", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/users/manage"} + permissions = {"/device-mgt/users/invite"} ), @Scope( name = "Get activities", description = "Get activities", - key = "perm:get-activity", + key = "dm:activity:get", roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/devices/owning-device/activities/view"} ), @Scope( name = "Getting the Permissions of the User", description = "Getting the Permissions of the User", - key = "perm:user:permission-view", + key = "um:users:permission:view", roles = {"Internal/devicemgt-user"}, permissions = {"/login"} ) @@ -158,7 +158,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:add") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:add") }) } ) @@ -217,7 +217,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:details") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:details:view") }) } ) @@ -288,7 +288,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:update") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:update") }) } ) @@ -355,7 +355,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:delete") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:delete") }) } ) @@ -400,7 +400,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:roles") + @ExtensionProperty(name = Constants.SCOPE, value = "um:roles:view") }) } ) @@ -465,7 +465,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:user-details") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:user-details:view") }) } ) @@ -543,7 +543,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:user-details") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:user-details:view") }) }, nickname = "getUsersByFilter" @@ -629,7 +629,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:count") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:count") }) } ) @@ -665,7 +665,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:is-exist") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:is-exist") }) } ) @@ -709,7 +709,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:search") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:search") }) } ) @@ -788,7 +788,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:credentials") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:cred:change") }) } ) @@ -835,7 +835,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:send-invitation") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:invite") }) } ) @@ -878,7 +878,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:send-invitation") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:invite") }) } ) @@ -926,7 +926,7 @@ public interface UserManagementService { tags = "Activity Info Provider", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:get-activity") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:activity:get") }) } ) @@ -1002,7 +1002,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:details") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:details:view") }) } ) @@ -1062,7 +1062,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:details") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:details:view") }) } ) @@ -1118,7 +1118,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:details") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:details:view") }) } ) @@ -1174,7 +1174,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:user:permission-view") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:permission:view") }) } ) @@ -1221,7 +1221,7 @@ public interface UserManagementService { tags = "User Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:users:user-details") + @ExtensionProperty(name = Constants.SCOPE, value = "um:users:user-details:view") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/WhiteLabelService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/WhiteLabelService.java index fdf2e62793..e6fd3e2c7a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/WhiteLabelService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/WhiteLabelService.java @@ -54,14 +54,14 @@ import javax.ws.rs.core.Response; @Scope( name = "View Whitelabel", description = "View whitelabel details", - key = "perm:whitelabel:view", + key = "dm:whitelable:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/whitelabel/view"} ), @Scope( name = "Update Whitelabel", description = "Updating whitelabel", - key = "perm:whitelabel:update", + key = "dm:whitelable:update", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/whitelabel/update"} ), @@ -197,7 +197,7 @@ public interface WhiteLabelService { tags = "Tenant Metadata Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:whitelabel:update") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:whitelable:update") }) } ) @@ -237,7 +237,7 @@ public interface WhiteLabelService { tags = "Tenant Metadata Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:whitelabel:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:whitelable:view") }) } ) @@ -278,7 +278,7 @@ public interface WhiteLabelService { tags = "Tenant Metadata Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:whitelabel:update") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:whitelable:update") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/ApplicationManagementAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/ApplicationManagementAdminService.java index 28ec2cb92a..9e7fa5a247 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/ApplicationManagementAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/ApplicationManagementAdminService.java @@ -56,16 +56,16 @@ import javax.ws.rs.core.Response; @Scope( name = "Installing an Application (Internal API)", description = "Installing an Application (Internal API)", - key = "perm:applications:install", + key = "am:admin:app:install", roles = {"Internal/devicemgt-admin"}, - permissions = {"/device-mgt/applications/manage"} + permissions = {"/device-mgt/admin/applications/install"} ), @Scope( name = "Uninstalling an Application (Internal API)", description = "Uninstalling an Application (Internal API)", - key = "perm:applications:uninstall", + key = "am:admin:app:uninstall", roles = {"Internal/devicemgt-admin"}, - permissions = {"/device-mgt/applications/manage"} + permissions = {"/device-mgt/admin/applications/uninstall"} ) } ) @@ -85,7 +85,7 @@ public interface ApplicationManagementAdminService { tags = "Application Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:applications:install") + @ExtensionProperty(name = Constants.SCOPE, value = "am:admin:app:install") }) } ) @@ -129,7 +129,7 @@ public interface ApplicationManagementAdminService { tags = "Application Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:applications:uninstall") + @ExtensionProperty(name = Constants.SCOPE, value = "am:admin:app:uninstall") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceAccessAuthorizationAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceAccessAuthorizationAdminService.java index aabaf7f793..a29604db1b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceAccessAuthorizationAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceAccessAuthorizationAdminService.java @@ -57,7 +57,7 @@ import javax.ws.rs.core.Response; @Scope( name = "Verify device authorization", description = "Verify device authorization", - key = "perm:authorization:verify", + key = "dm:authorization:verify", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/authorization/verify"} ) @@ -81,7 +81,7 @@ public interface DeviceAccessAuthorizationAdminService { tags = "Authorization Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:authorization:verify") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:authorization:verify") }) }) @@ -120,7 +120,7 @@ public interface DeviceAccessAuthorizationAdminService { tags = "Authorization Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:authorization:verify") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:authorization:verify") }) }) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceManagementAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceManagementAdminService.java index 20188e87c2..13a63087a7 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceManagementAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceManagementAdminService.java @@ -59,28 +59,28 @@ import java.util.List; @Scope( name = "Getting Details of a Device", description = "Getting Details of a Device", - key = "perm:admin:devices:view", + key = "dm:admin:devices:view", roles = {"Internal/devicemgt-admin"}, - permissions = {"/device-mgt/devices/owning-device/view"} + permissions = {"/device-mgt/admin/devices/view"} ), @Scope( name = "Update the Device Owner", description = "Update the ownership of the device", - key = "perm:admin:devices:update-enrollment", + key = "dm:admin:enrollment:update", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/devices/update-enrollment"} ), @Scope( name = "Permanently Delete the device specified by device id", description = "Permanently Delete the device specified by device id", - key = "perm:devices:permanent-delete", + key = "dm:admin:devices:permanent-delete", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/devices/permanent-delete"} ), @Scope( name = "Get Usage of Devices", description = "Get Usage of Devices", - key = "perm:admin:usage:view", + key = "dm:admin:devices:usage:view", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/devices/usage/view"} ), @@ -99,7 +99,7 @@ public interface DeviceManagementAdminService { tags = "Device Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:devices:view") }) } ) @@ -193,7 +193,7 @@ public interface DeviceManagementAdminService { tags = "Device Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:devices:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:devices:view") }) } ) @@ -246,7 +246,7 @@ public interface DeviceManagementAdminService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:devices:update-enrollment") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:enrollment:update") }) } ) @@ -297,7 +297,7 @@ public interface DeviceManagementAdminService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:permanent-delete") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:devices:permanent-delete") }) } ) @@ -348,7 +348,7 @@ public interface DeviceManagementAdminService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:android:enroll") + @ExtensionProperty(name = Constants.SCOPE, value = "and:devices:enroll") }) } ) @@ -407,7 +407,7 @@ public interface DeviceManagementAdminService { tags = "Device Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:usage:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:devices:usage:view") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceTypeManagementAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceTypeManagementAdminService.java index 4cac83ae6b..7be8baf855 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceTypeManagementAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceTypeManagementAdminService.java @@ -56,21 +56,21 @@ import javax.ws.rs.core.Response; @Scope( name = "Manage a Device Type", description = "Add, Edit or View a Device Type", - key = "perm:admin:device-type", + key = "dm:admin:device-type:modify", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/device-type"} ), @Scope( name = "Getting Details of a Device Type", description = "Getting Details of a Device Type", - key = "perm:admin:device-type:view", + key = "dm:admin:device-type:view", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/device-type/view"} ), @Scope( name = "Add Device Type Config", description = "Add Platform Config of a Device Type", - key = "perm:admin:device-type:configs", + key = "dm:admin:device-type:conf:add", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/device-type/config"} ) @@ -88,7 +88,7 @@ public interface DeviceTypeManagementAdminService { tags = "Device Type Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:device-type:view") }) } ) @@ -142,7 +142,7 @@ public interface DeviceTypeManagementAdminService { tags = "Device Type Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type:view") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:device-type:view") }) } ) @@ -195,7 +195,7 @@ public interface DeviceTypeManagementAdminService { tags = "Device Type Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:device-type:modify") }) } ) @@ -248,7 +248,7 @@ public interface DeviceTypeManagementAdminService { tags = "Device Type Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:device-type:modify") }) } ) @@ -304,7 +304,7 @@ public interface DeviceTypeManagementAdminService { tags = "Device Type Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type:configs") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:device-type:conf:add") }) } ) @@ -362,7 +362,7 @@ public interface DeviceTypeManagementAdminService { tags = "Device Type Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:device-type:modify") }) } ) @@ -416,7 +416,7 @@ public interface DeviceTypeManagementAdminService { tags = "Device Type Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:device-type:modify") }) } ) @@ -468,7 +468,7 @@ public interface DeviceTypeManagementAdminService { tags = "Device Type Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:device-type:modify") }) } ) @@ -522,7 +522,7 @@ public interface DeviceTypeManagementAdminService { tags = "Device Type Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:device-type:modify") }) } ) @@ -575,7 +575,7 @@ public interface DeviceTypeManagementAdminService { tags = "Device Type Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:admin:device-type:modify") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/GroupManagementAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/GroupManagementAdminService.java index 4c27cb6908..6d69127405 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/GroupManagementAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/GroupManagementAdminService.java @@ -75,21 +75,21 @@ import javax.ws.rs.core.Response; @Scope( name = "View groups", description = "", - key = "perm:admin-groups:view", + key = "gm:admin:groups:view", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/groups/view"} ), @Scope( name = "Count groups", description = "", - key = "perm:admin-groups:count", + key = "gm:admin:groups:count", roles = {"Internal/devicemgt-admin"}, - permissions = {"/device-mgt/admin/groups/view"} + permissions = {"/device-mgt/admin/groups/count"} ), @Scope( name = "Add groups", description = "", - key = "perm:admin-groups:add", + key = "gm:admin:groups:add", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/groups/add"} ) @@ -106,7 +106,7 @@ public interface GroupManagementAdminService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin-groups:view") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:admin:groups:view") }) } ) @@ -182,7 +182,7 @@ public interface GroupManagementAdminService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin-groups:view") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:admin:groups:view") }) } ) @@ -256,6 +256,58 @@ public interface GroupManagementAdminService { @QueryParam("limit") int limit); + @Path("/hierarchy/count") + @GET + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_GET, + value = "Get the count of all hierarchical groups belongs to current admin user.", + notes = "Returns count of all permitted hierarchical groups enrolled with the system.", + tags = "Device Group Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "gm:admin:groups:count") + }) + } + ) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the hierarchical device group count.", + response = Integer.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching the group count.", + response = ErrorResponse.class) + }) + Response getHierarchicalGroupCount(@ApiParam( + name = "status", + value = "status of hierarchical groups of which count should be retrieved") + @QueryParam("status") + String status); + @Path("/count") @GET @ApiOperation( @@ -266,7 +318,7 @@ public interface GroupManagementAdminService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin-groups:count") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:admin:groups:count") }) } ) @@ -317,7 +369,7 @@ public interface GroupManagementAdminService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin-groups:add") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:admin:groups:add") }) } ) @@ -387,7 +439,7 @@ public interface GroupManagementAdminService { tags = "Device Group Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:add") + @ExtensionProperty(name = Constants.SCOPE, value = "gm:groups:add") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java index a6f2deeec7..1feefa0756 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java @@ -51,16 +51,16 @@ import javax.ws.rs.core.Response; @Scope( name = "View Users", description = "View Users", - key = "perm:admin-users:view", + key = "um:admin:users:view", roles = {"Internal/devicemgt-admin"}, - permissions = {"/device-mgt/users/manage"} + permissions = {"/device-mgt/admin/users/view"} ), @Scope( name = "Delete Users Device Information", description = "Delete users device details", - key = "perm:admin-users:remove", + key = "um:admin:users:remove", roles = {"Internal/devicemgt-admin"}, - permissions = {"/device-mgt/users/manage"} + permissions = {"/device-mgt/admin/users/delete"} ) } ) @@ -84,7 +84,7 @@ public interface UserManagementAdminService { tags = "User Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin-users:view") + @ExtensionProperty(name = Constants.SCOPE, value = "um:admin:users:view") }) } ) @@ -143,7 +143,7 @@ public interface UserManagementAdminService { tags = "Device details remove", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin-users:remove") + @ExtensionProperty(name = Constants.SCOPE, value = "um:admin:users:remove") }) } ) @@ -201,7 +201,7 @@ public interface UserManagementAdminService { tags = "Device details remove privacy compliance", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin-users:remove") + @ExtensionProperty(name = Constants.SCOPE, value = "um:admin:users:remove") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImpl.java index f9e1a64432..b5d1c76ed1 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImpl.java @@ -18,20 +18,22 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; import com.google.gson.Gson; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ActivityList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.common.ActivityIdList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.ActivityInfoProviderService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; +import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.ActivityPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ActivityList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.common.ActivityIdList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.ActivityInfoProviderService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.user.api.UserStoreException; import javax.validation.constraints.Size; @@ -139,8 +141,11 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService @Size(max = 45) String devicetype, @PathParam("deviceid") @Size(max = 45) String deviceid, - @HeaderParam("If-Modified-Since") String ifModifiedSince) { - Activity activity; + @HeaderParam("If-Modified-Since") String ifModifiedSince, + @QueryParam("response") Boolean response, + @QueryParam("appInstall") Boolean appInstall) { + Activity activity = new Activity(); + Activity appActivity = null; DeviceManagementProviderService dmService; try { RequestValidationUtil.validateActivityId(id); @@ -150,7 +155,29 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService deviceIdentifier.setType(devicetype); dmService = DeviceMgtAPIUtils.getDeviceManagementService(); - activity = dmService.getOperationByActivityIdAndDevice(id, deviceIdentifier); + + if (appInstall != null && appInstall) { + if (response != null && response) { + activity = dmService.getOperationByActivityIdAndDevice(id, deviceIdentifier); + } + SubscriptionManager subscriptionManager = DeviceMgtAPIUtils.getSubscriptionManager(); + appActivity = subscriptionManager.getOperationAppDetails(id); + if (appActivity != null) { + activity.setUsername(appActivity.getUsername()); + activity.setPackageName(appActivity.getPackageName()); + activity.setAppName(appActivity.getAppName()); + activity.setStatus(appActivity.getStatus()); + activity.setAppType(appActivity.getAppType()); + activity.setVersion(appActivity.getVersion()); + activity.setTriggeredBy(appActivity.getTriggeredBy()); + } else { + String msg = "Cannot find the app details related to the operation "; + log.error(msg); + Response.status(404).entity(msg).build(); + } + } else { + activity = dmService.getOperationByActivityIdAndDevice(id, deviceIdentifier); + } if (activity == null) { String msg = "No activity can be " + "found upon the provided activity id '" + id + "'"; @@ -162,6 +189,11 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (SubscriptionManagementException e) { + String msg = "ErrorResponse occurred while fetching the app details for the supplied id."; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -214,6 +246,7 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService @QueryParam("since") String since, @QueryParam("initiatedBy") String initiatedBy, @QueryParam("operationCode") String operationCode, + @QueryParam("operationId") int operationId, @QueryParam("deviceType") String deviceType, @QueryParam("deviceId") List deviceIds, @QueryParam("type") String type, @@ -282,6 +315,9 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService if (operationCode != null && !operationCode.isEmpty()) { activityPaginationRequest.setOperationCode(operationCode); } + if (operationId > 0) { + activityPaginationRequest.setOperationId(operationId); + } if (deviceType != null && !deviceType.isEmpty()) { activityPaginationRequest.setDeviceType(deviceType); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java index b591fcdc13..de206daf85 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -18,25 +18,24 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.DCRResponse; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenRequest; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenResponse; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; import io.entgra.device.mgt.core.application.mgt.common.ApplicationInstallResponse; import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.*; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.InputValidationException; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.DCRResponse; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenRequest; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenResponse; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException; @@ -74,16 +73,18 @@ import io.entgra.device.mgt.core.device.mgt.core.search.mgt.SearchMgtException; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.*; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceManagementService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.InputValidationException; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.lang.StringUtils; -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.user.api.UserStoreException; @@ -93,12 +94,15 @@ import javax.validation.Valid; import javax.validation.constraints.Size; import javax.ws.rs.*; import javax.ws.rs.core.Response; +import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; +import java.util.concurrent.ExecutionException; +import java.util.Map; @Path("/devices") public class DeviceManagementServiceImpl implements DeviceManagementService { @@ -136,6 +140,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @QueryParam("role") String role, @QueryParam("ownership") String ownership, @QueryParam("serialNumber") String serialNumber, + @QueryParam("customProperty") String customProperty, @QueryParam("status") List status, @QueryParam("groupId") int groupId, @QueryParam("since") String since, @@ -149,6 +154,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } // RequestValidationUtil.validateSelectionCriteria(type, user, roleName, ownership, status); + final ObjectMapper objectMapper = new ObjectMapper(); RequestValidationUtil.validatePaginationParameters(offset, limit); DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); DeviceAccessAuthorizationService deviceAccessAuthorizationService = @@ -160,6 +166,22 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { if (name != null && !name.isEmpty()) { request.setDeviceName(name); } + if (customProperty != null && !customProperty.isEmpty()) { + try { + Map customProperties = objectMapper.readValue(customProperty, Map.class); + // Extract and set custom properties + for (Map.Entry entry : customProperties.entrySet()) { + String propertyName = entry.getKey(); + String propertyValue = entry.getValue(); + // Add custom property to the paginationRequest object + request.addCustomProperty(propertyName, propertyValue); + } + } catch (IOException e) { + String msg = "Error occurred while converting custom property string to a Java Map"; + log.error(msg); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } if (type != null && !type.isEmpty()) { request.setDeviceType(type); } @@ -975,7 +997,11 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { public Response uninstallation( @PathParam("type") @Size(max = 45) String type, @PathParam("id") @Size(max = 45) String id, - @QueryParam("packageName") String packageName) { + @QueryParam("packageName") String packageName, + @QueryParam("platform") String platform, + @QueryParam("name") String name, + @QueryParam("version") String version, + @QueryParam("user") String user) { List deviceIdentifiers = new ArrayList<>(); Operation operation = new Operation(); try { @@ -998,7 +1024,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { //if the applications not installed via entgra store } else { if (Constants.ANDROID.equals(type)) { - ApplicationUninstallation applicationUninstallation = new ApplicationUninstallation(packageName, "PUBLIC"); + ApplicationUninstallation applicationUninstallation = new ApplicationUninstallation(packageName, "PUBLIC", name, platform, version, user); Gson gson = new Gson(); operation.setCode(MDMAppConstants.AndroidConstants.UNMANAGED_APP_UNINSTALL); operation.setType(Operation.Type.PROFILE); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GeoLocationBasedServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GeoLocationBasedServiceImpl.java index 1d410d43d5..21fdb282df 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GeoLocationBasedServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GeoLocationBasedServiceImpl.java @@ -836,6 +836,14 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { PaginationResult paginationResult = new PaginationResult(); paginationResult.setData(geofenceList); paginationResult.setRecordsTotal(geofenceList.size()); + try { + GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); + paginationResult.setTotalDeviceCount(geoService.getGeoFenceCount()); + } catch (GeoLocationBasedServiceException e) { + String msg = "Failed to retrieve geofence data"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } return Response.status(Response.Status.OK).entity(paginationResult).build(); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GroupManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GroupManagementServiceImpl.java index 347ebe88f9..7912c72441 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GroupManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GroupManagementServiceImpl.java @@ -133,6 +133,19 @@ public class GroupManagementServiceImpl implements GroupManagementService { } } + @Override + public Response getHierarchicalGroupCount() { + try { + String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getHierarchicalGroupCount(currentUser, null); + return Response.status(Response.Status.OK).entity(count).build(); + } catch (GroupManagementException e) { + String msg = "Error occurred while retrieving hierarchical group count."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + @Override public Response getGroupCount() { try { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RoleManagementServiceImpl.java index 28610ce73a..4f900b2efb 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RoleManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RoleManagementServiceImpl.java @@ -17,10 +17,20 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException; import com.google.common.base.Strings; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import org.apache.commons.logging.Log; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.CarbonConstants; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.RoleInfo; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.RoleList; @@ -30,15 +40,8 @@ import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestV import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.SetReferenceTransformer; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; +import org.wso2.carbon.user.api.*; import org.springframework.util.StringUtils; -import org.wso2.carbon.CarbonConstants; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.RegistryType; import org.wso2.carbon.registry.api.Registry; import org.wso2.carbon.registry.core.session.UserRegistry; @@ -74,8 +77,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; -import java.util.Optional; import java.util.Set; +import java.util.Optional; import static io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants.PRIMARY_USER_STORE; @@ -297,15 +300,49 @@ public class RoleManagementServiceImpl implements RoleManagementService { } } - private UIPermissionNode getAllRolePermissions(String roleName, UserRealm userRealm) throws UserAdminException { - org.wso2.carbon.user.core.UserRealm userRealmCore = null; - if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { - userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; + /** + * Retrieve filtered permissions by analyzing all the permission paths. + * + * @param rolePermissions All the permission paths + * @param permissionPaths Permission paths that needs to filter + * @param permissions List of filtered permissions + * @return {@link List} + */ + private List processAndFilterPermissions(UIPermissionNode[] rolePermissions, List permissionPaths, List permissions) { + + for (UIPermissionNode rolePermission : rolePermissions) { + if (permissionPaths.isEmpty()) { + return permissions; + } + + if (rolePermission.getNodeList().length == 0) { + if (permissionPaths.contains(rolePermission.getResourcePath())) { + permissions.add(rolePermission.getResourcePath()); + } + } + permissionPaths.remove(rolePermission.getResourcePath()); + if (rolePermission.getNodeList().length != 0) { + processAndFilterPermissions(rolePermission.getNodeList(), permissionPaths, permissions); + } } - final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); - final UIPermissionNode rolePermissions = - userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID); - return rolePermissions; + return permissions; + } + + /** + * Getting platform permissions + * + * @param roleName Role Name + * @param userRealm {@link UserRealm} + * @param permissions list of permissions + * @return {@link List} + * @throws UserAdminException if error occurred when getting {@link UIPermissionNode} + */ + private String[] getPlatformUIPermissions(String roleName, UserRealm userRealm, String[] permissions) + throws UserAdminException { + UIPermissionNode uiPermissionNode = getUIPermissionNode(roleName, userRealm); + List permissionsArray = processAndFilterPermissions(uiPermissionNode.getNodeList(), new ArrayList<>(Arrays.asList(permissions)), + new ArrayList<>()); + return permissionsArray.toArray(new String[0]); } private UIPermissionNode getUIPermissionNode(String roleName, UserRealm userRealm) @@ -381,18 +418,6 @@ public class RoleManagementServiceImpl implements RoleManagementService { } } - private List getAuthorizedPermissions(UIPermissionNode uiPermissionNode, List list) { - for (UIPermissionNode permissionNode : uiPermissionNode.getNodeList()) { - if (permissionNode.isSelected()) { - list.add(permissionNode.getResourcePath()); - } - if (permissionNode.getNodeList() != null && permissionNode.getNodeList().length > 0) { - getAuthorizedPermissions(permissionNode, list); - } - } - return list; - } - @POST @Override public Response addRole(RoleInfo roleInfo) { @@ -403,6 +428,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { if (log.isDebugEnabled()) { log.debug("Persisting the role in the underlying user store"); } + Permission[] permissions = null; if (roleInfo.getPermissions() != null && roleInfo.getPermissions().length > 0) { permissions = new Permission[roleInfo.getPermissions().length]; @@ -412,7 +438,17 @@ public class RoleManagementServiceImpl implements RoleManagementService { } } userStoreManager.addRole(roleInfo.getRoleName(), roleInfo.getUsers(), permissions); - authorizeRoleForAppmgt(roleInfo.getRoleName(), roleInfo.getPermissions()); + try { + if (roleInfo.getPermissions() != null && roleInfo.getPermissions().length > 0) { + String[] roleName = roleInfo.getRoleName().split("/"); + roleInfo.setRemovedPermissions(new String[0]); + updatePermissions(roleName[roleName.length - 1], roleInfo, DeviceMgtAPIUtils.getUserRealm()); + } + } catch (UserStoreException e) { + String msg = "Error occurred while loading the user store."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } //TODO fix what's returned in the entity return Response.created(new URI(API_BASE_PATH + "/" + URLEncoder.encode(roleInfo.getRoleName(), "UTF-8"))). @@ -522,11 +558,10 @@ public class RoleManagementServiceImpl implements RoleManagementService { final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); final UserStoreManager userStoreManager = userRealm.getUserStoreManager(); if (!userStoreManager.isExistingRole(roleName)) { - String msg = "No role exists with the name : " + roleName ; + String msg = "No role exists with the name : " + roleName; return Response.status(404).entity(msg).build(); } - final AuthorizationManager authorizationManager = userRealm.getAuthorizationManager(); if (log.isDebugEnabled()) { log.debug("Updating the role to user store"); } @@ -548,31 +583,8 @@ public class RoleManagementServiceImpl implements RoleManagementService { } if (roleInfo.getPermissions() != null) { - // Get all role permissions - final UIPermissionNode rolePermissions = this.getAllRolePermissions(roleName, userRealm); - List permissions = new ArrayList(); - final UIPermissionNode emmRolePermissions = (UIPermissionNode) this.getRolePermissions(roleName); - List emmConsolePermissions = new ArrayList(); - this.getAuthorizedPermissions(emmRolePermissions, emmConsolePermissions); - emmConsolePermissions.removeAll(new ArrayList(Arrays.asList(roleInfo.getPermissions()))); - this.getAuthorizedPermissions(rolePermissions, permissions); - for (String permission : roleInfo.getPermissions()) { - permissions.add(permission); - } - permissions.removeAll(emmConsolePermissions); - String[] allApplicablePerms = new String[permissions.size()]; - allApplicablePerms = permissions.toArray(allApplicablePerms); - roleInfo.setPermissions(allApplicablePerms); - - // Delete all authorizations for the current role before authorizing the permission tree - authorizationManager.clearRoleAuthorization(roleName); - if (roleInfo.getPermissions().length > 0) { - for (int i = 0; i < roleInfo.getPermissions().length; i++) { - String permission = roleInfo.getPermissions()[i]; - authorizationManager.authorizeRole(roleName, permission, CarbonConstants.UI_PERMISSION_ACTION); - } - } - authorizeRoleForAppmgt(roleName, roleInfo.getPermissions()); + String[] roleDetails = roleName.split("/"); + updatePermissions(roleDetails[roleDetails.length - 1], roleInfo, userRealm); } //TODO: Need to send the updated role information in the entity back to the client return Response.status(Response.Status.OK).entity("Role '" + roleInfo.getRoleName() + "' has " + @@ -589,70 +601,12 @@ public class RoleManagementServiceImpl implements RoleManagementService { String msg = "Role already exists with name : " + role + ". Try with another role name."; log.warn(msg); return Response.status(Response.Status.CONFLICT).entity(msg).build(); - }else{ + } else { String msg = "Error occurred while updating role '" + roleName + "'"; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } - } catch (UserAdminException e) { - String msg = "Error occurred while updating permissions of the role '" + roleName + "'"; - log.error(msg, e); - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); - } - } - - /** - * When presented with role and a set of permissions, if given role has permission to - * perform mobile app management, said role will be given rights mobile app collection in the - * governance registry. - * - * @param role - * @param permissions - * @return state of role update Operation - */ - private boolean authorizeRoleForAppmgt(String role, String[] permissions) { - String permissionString = - "ra^true:rd^false:wa^true:wd^false:da^true:dd^false:aa^true:ad^false"; - String resourcePath = "/_system/governance/mobileapps/"; - boolean appmPermAvailable = false; - - if (permissions != null) { - for (int i = 0; i < permissions.length; i++) - switch (permissions[i]) { - case "/permission/admin/manage/mobileapp": - appmPermAvailable = true; - break; - case "/permission/admin/manage/mobileapp/create": - appmPermAvailable = true; - break; - case "/permission/admin/manage/mobileapp/publish": - appmPermAvailable = true; - break; - } - } - - if (appmPermAvailable) { - try { - Registry registry = CarbonContext.getThreadLocalCarbonContext(). - getRegistry(RegistryType.SYSTEM_GOVERNANCE); - ChangeRolePermissionsUtil.changeRolePermissions((UserRegistry) registry, - resourcePath, role + ":" + permissionString); - - return true; - } catch (Exception e) { - String msg = "Error while retrieving user registry in order to update permissions " - + "for resource : " + resourcePath; - log.error(msg, e); - return false; - } - } else { - if (log.isDebugEnabled()) { - log.debug("Mobile App Management permissions not selected, therefore role : " + - role + " not given permission for registry collection : " + resourcePath); - } - return false; } } @@ -780,4 +734,33 @@ public class RoleManagementServiceImpl implements RoleManagementService { } return rolePermissions; } + + /** + * Update the role's permissions. This will function in the fire and forget pattern and run on a new thread. + * + * @param roleName Role Name + * @param roleInfo {@link RoleInfo} + * @param userRealm {@link UserRealm} + */ + private void updatePermissions(String roleName, RoleInfo roleInfo, UserRealm userRealm) { + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); + Thread thread = new Thread(new Runnable() { + @Override + public void run() { + try { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); + DeviceMgtAPIUtils.getApiPublisher().updateScopeRoleMapping(roleName, + RoleManagementServiceImpl.this.getPlatformUIPermissions(roleName, userRealm, + roleInfo.getPermissions()), RoleManagementServiceImpl.this.getPlatformUIPermissions(roleName, userRealm, + roleInfo.getRemovedPermissions())); + } catch (APIManagerPublisherException | UserAdminException e) { + log.error("Error Occurred while updating role scope mapping. ", e); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } + }); + thread.start(); + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java index d0f5239fa3..10b5a29dfe 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java @@ -19,6 +19,15 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpStatus; +import org.eclipse.wst.common.uriresolver.internal.util.URIEncoder; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.*; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.exception.BadRequestException; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.UserManagementService; @@ -28,7 +37,6 @@ import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.CredentialManagementR import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.OTPManagementException; import io.entgra.device.mgt.core.device.mgt.common.invitation.mgt.DeviceEnrollmentInvitation; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; @@ -37,13 +45,6 @@ import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.EmailMetaInfo; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; -import org.eclipse.wst.common.uriresolver.internal.util.URIEncoder; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataManagementAdminService; import org.wso2.carbon.identity.claim.metadata.mgt.dto.AttributeMappingDTO; import org.wso2.carbon.identity.claim.metadata.mgt.dto.ClaimPropertyDTO; @@ -83,11 +84,6 @@ public class UserManagementServiceImpl implements UserManagementService { private static final String API_BASE_PATH = "/users"; private static final Log log = LogFactory.getLog(UserManagementServiceImpl.class); - private static final String ADMIN_ROLE = "admin"; - private static final String DEFAULT_DEVICE_USER = "Internal/devicemgt-user"; - private static final String DEFAULT_DEVICE_ADMIN = "Internal/devicemgt-admin"; - private static final String DEFAULT_SUBSCRIBER = "Internal/subscriber"; - // Permissions that are given for a normal device user. private static final Permission[] PERMISSIONS_FOR_DEVICE_USER = { new Permission("/permission/admin/Login", "ui.execute"), @@ -124,51 +120,9 @@ public class UserManagementServiceImpl implements UserManagementService { Map defaultUserClaims = this.buildDefaultUserClaims(userInfo.getFirstname(), userInfo.getLastname(), userInfo.getEmailAddress(), true); - // calling addUser method of carbon user api - List tmpRoles = new ArrayList<>(); - String[] userInfoRoles = userInfo.getRoles(); - tmpRoles.add(DEFAULT_DEVICE_USER); - - boolean subscriberFound = false; - boolean adminFound = false; - - if (userInfoRoles != null) { - //check if subscriber role is coming in the payload - for (String r : userInfoRoles) { - if (!subscriberFound || !adminFound) { - if (DEFAULT_SUBSCRIBER.equals(r)) { - subscriberFound = true; - } else if (ADMIN_ROLE.equals(r)) { - tmpRoles.add(DEFAULT_DEVICE_ADMIN); - adminFound = true; - } - } else { - break; - } - } - tmpRoles.addAll(Arrays.asList(userInfoRoles)); - } - - if (!subscriberFound) { - // Add Internal/subscriber role to new users - if (userStoreManager.isExistingRole(DEFAULT_SUBSCRIBER)) { - tmpRoles.add(DEFAULT_SUBSCRIBER); - } else { - log.warn("User: " + userInfo.getUsername() + " will not be able to enroll devices as '" + - DEFAULT_SUBSCRIBER + "' is missing in the system"); - } - } - - String[] roles = new String[tmpRoles.size()]; - tmpRoles.toArray(roles); - - // If the normal device user role does not exist, create a new role with the minimal permissions - if (!userStoreManager.isExistingRole(DEFAULT_DEVICE_USER)) { - userStoreManager.addRole(DEFAULT_DEVICE_USER, null, PERMISSIONS_FOR_DEVICE_USER); - } userStoreManager.addUser(userInfo.getUsername(), initialUserPassword, - roles, defaultUserClaims, null); + userInfo.getRoles(), defaultUserClaims, null); // Outputting debug message upon successful addition of user if (log.isDebugEnabled()) { log.debug("User '" + userInfo.getUsername() + "' has successfully been added."); @@ -336,32 +290,42 @@ public class UserManagementServiceImpl implements UserManagementService { @Consumes(MediaType.WILDCARD) @Override public Response removeUser(@QueryParam("username") String username, @QueryParam("domain") String domain) { + boolean nameWithDomain = false; if (domain != null && !domain.isEmpty()) { username = domain + '/' + username; + nameWithDomain = true; } try { + int deviceCount; UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (!userStoreManager.isExistingUser(username)) { if (log.isDebugEnabled()) { - log.debug("User by username: " + username + " does not exist for removal."); + log.debug("User by user: " + username + " does not exist for removal."); } - String msg = "User by username: " + username + " does not exist for removal."; + String msg = "User by user: " + username + " does not exist for removal."; return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } - // Un-enroll all devices for the user DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); - deviceManagementService.setStatus(username, EnrolmentInfo.Status.REMOVED); - - userStoreManager.deleteUser(username); - if (log.isDebugEnabled()) { - log.debug("User '" + username + "' was successfully removed."); + if (nameWithDomain) { + deviceCount = deviceManagementService.getDeviceCount(username.split("/")[1]); + } else { + deviceCount = deviceManagementService.getDeviceCount(username); + } + if (deviceCount == 0) { + userStoreManager.deleteUser(username); + if (log.isDebugEnabled()) { + log.debug("User '" + username + "' was successfully removed."); + } + return Response.status(Response.Status.OK).build(); + } else { + String msg = "There are enrolled devices for user: " + username + ". Please remove them before deleting the user."; + log.error(msg); + return Response.status(400).entity(msg).build(); } - return Response.status(Response.Status.OK).build(); } catch (DeviceManagementException | UserStoreException e) { - String msg = "Exception in trying to remove user by username: " + username; + String msg = "Exception in trying to remove user by user: " + username; log.error(msg, e); - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + return Response.status(400).entity(msg).build(); } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java index 51b00ec613..8c13cf4bf3 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java @@ -133,6 +133,23 @@ public class GroupManagementAdminServiceImpl implements GroupManagementAdminServ } } + @Override + public Response getHierarchicalGroupCount(String status) { + try { + int count; + if (status == null || status.isEmpty()) { + count = DeviceMgtAPIUtils.getGroupManagementProviderService().getHierarchicalGroupCount(); + } else { + count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCountByStatus(status); + } + return Response.status(Response.Status.OK).entity(count).build(); + } catch (GroupManagementException e) { + String msg = "ErrorResponse occurred while retrieving hierarchical group count."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + @Override public Response getGroupCount(String status) { try { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java index 1073737ef5..7b52ddd57c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.util; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceTypeVersionWrapper; @@ -155,6 +156,8 @@ public class DeviceMgtAPIUtils { private static volatile SubscriptionManager subscriptionManager; private static volatile ApplicationManager applicationManager; + private static volatile APIPublisherService apiPublisher; + static { String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password"); String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty( @@ -233,6 +236,24 @@ public class DeviceMgtAPIUtils { return applicationManager; } + public static APIPublisherService getApiPublisher() { + if (apiPublisher == null) { + synchronized (DeviceMgtAPIUtils.class) { + if (apiPublisher == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + apiPublisher = + (APIPublisherService) ctx.getOSGiService(APIPublisherService.class, null); + if (apiPublisher == null) { + String msg = "Application Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + } + } + return apiPublisher; + } + public static void scheduleTaskService(int notifierFrequency) { TaskScheduleService taskScheduleService; try { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImplTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImplTest.java index 6e118a1104..738a7c0fd0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImplTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImplTest.java @@ -206,7 +206,7 @@ public class ActivityProviderServiceImplTest { Mockito.when(this.deviceManagementProviderService .getOperationByActivityIdAndDevice(TEST_ACTIVITY_ID, deviceIdentifier)).thenReturn(activity); Response response = this.activityInfoProviderService.getActivityByDevice(TEST_ACTIVITY_ID, - DEVICE_TYPE, DEVICE_ID, IF_MODIFIED_SINCE); + DEVICE_TYPE, DEVICE_ID, IF_MODIFIED_SINCE, false, false); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Mockito.reset(this.deviceManagementProviderService); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImplTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImplTest.java index 25cdd5168c..0f50c89156 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImplTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImplTest.java @@ -157,7 +157,7 @@ public class DeviceManagementServiceImplTest { .toReturn(this.deviceAccessAuthorizationService); Response response = this.deviceManagementService .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 1, null, null, false, + null, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); } @@ -177,22 +177,22 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 1, null, null, false, + null,null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, null, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 1, null, null, false, + null, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 1, null, null, false, + null, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 1, null, null, true, + null, null, DEFAULT_STATUS_LIST, 1, null, null, true, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); } @@ -306,7 +306,7 @@ public class DeviceManagementServiceImplTest { .toReturn(this.deviceManagementProviderService); Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true); deviceManagementService.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, - DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, DEFAULT_STATUS_LIST, 1, + DEFAULT_ROLE, DEFAULT_OWNERSHIP, null,null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); } @@ -326,11 +326,11 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP - , null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); + , null, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP - , null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); + , null, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); } @@ -352,7 +352,7 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 0, null, null, false, + null, null, DEFAULT_STATUS_LIST, 0, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode()); Mockito.reset(this.deviceAccessAuthorizationService); @@ -374,17 +374,17 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, false, + null, null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, true, + null, null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, true, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 0, null, "ErrorModifiedSince", + null, null, DEFAULT_STATUS_LIST, 0, null, "ErrorModifiedSince", false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); } @@ -405,17 +405,17 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 0, since, null, false, + null, null,DEFAULT_STATUS_LIST, 0, since, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 0, since, null, true, + null, null,DEFAULT_STATUS_LIST, 0, since, null, true, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 0, "ErrorSince", null, false, + null, null,DEFAULT_STATUS_LIST, 0, "ErrorSince", null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); } @@ -438,7 +438,7 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 1, null, null, false, + null, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Mockito.reset(this.deviceManagementProviderService); @@ -461,7 +461,7 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - null, DEFAULT_STATUS_LIST, 1, null, null, false, + null, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Mockito.reset(this.deviceAccessAuthorizationService); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImplTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImplTest.java index 5b2417c4db..ea6594d15b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImplTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImplTest.java @@ -18,20 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.BasicUserInfo; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.EnrollmentInvitation; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.UserInfo; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.UserManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.OTPManagementException; -import io.entgra.device.mgt.core.device.mgt.common.invitation.mgt.DeviceEnrollmentInvitation; -import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; -import io.entgra.device.mgt.core.device.mgt.core.otp.mgt.service.OTPManagementServiceImpl; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import io.entgra.device.mgt.core.device.mgt.common.Device; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -45,6 +32,20 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.wso2.carbon.context.CarbonContext; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.OTPManagementException; +import io.entgra.device.mgt.core.device.mgt.common.invitation.mgt.DeviceEnrollmentInvitation; +import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; +import io.entgra.device.mgt.core.device.mgt.core.otp.mgt.service.OTPManagementServiceImpl; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.BasicUserInfo; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.EnrollmentInvitation; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.UserInfo; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.UserManagementService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.user.api.RealmConfiguration; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; @@ -272,7 +273,7 @@ public class UserManagementServiceImplTest { .toReturn(this.userStoreManager); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); - Mockito.doReturn(true).when(deviceManagementProviderService).setStatus(Mockito.anyString(), Mockito.any()); + Mockito.doReturn(0).when(deviceManagementProviderService).getDeviceCount(TEST_USERNAME); Mockito.doNothing().when(userStoreManager).deleteUser(Mockito.anyString()); Response response = userManagementService.removeUser(TEST_USERNAME, null); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), @@ -337,7 +338,7 @@ public class UserManagementServiceImplTest { Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "Response returned successful for a user updating request with problematic inputs"); response = userManagementService.removeUser(TEST3_USERNAME, null); - Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), "Response returned successful for a user removal request with problematic inputs"); response = userManagementService.getRolesOfUser(TEST3_USERNAME, null); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml index 291280ef73..ca51d3e198 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml @@ -21,7 +21,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/ActivityPaginationRequest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/ActivityPaginationRequest.java index b535ab4bd6..058b82dd2f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/ActivityPaginationRequest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/ActivityPaginationRequest.java @@ -32,6 +32,7 @@ public class ActivityPaginationRequest { private String deviceType; private List deviceIds; private String operationCode; + private int operationId; private String initiatedBy; private long since; private Operation.Type type; @@ -132,4 +133,12 @@ public class ActivityPaginationRequest { public void setEndTimestamp(long endTimestamp) { this.endTimestamp = endTimestamp; } + + public int getOperationId() { + return operationId; + } + + public void setOperationId(int operationId) { + this.operationId = operationId; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/CertificatePaginationRequest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/CertificatePaginationRequest.java new file mode 100644 index 0000000000..fdfcf5d30c --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/CertificatePaginationRequest.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.device.mgt.common; + +public class CertificatePaginationRequest { + private int startIndex; + private int rowCount; + private String serialNumber; + private String deviceIdentifier; + private String username; + + public CertificatePaginationRequest(int start, int rowCount) { + this.startIndex = start; + this.rowCount = rowCount; + } + + public int getStartIndex() { + return startIndex; + } + + public void setStartIndex(int startIndex) { + this.startIndex = startIndex; + } + + public int getRowCount() { + return rowCount; + } + + public void setRowCount(int rowCount) { + this.rowCount = rowCount; + } + + public String getSerialNumber() { + return serialNumber; + } + + public void setSerialNumber(String serialNumber) { + this.serialNumber = serialNumber; + } + + public String getDeviceIdentifier() { + return deviceIdentifier; + } + + public void setDeviceIdentifier(String deviceIdentifier) { + this.deviceIdentifier = deviceIdentifier; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @Override + public String toString() { + return "Certificate serial number '" + this.serialNumber + "' num of rows: " + this.rowCount + " start index: " + this.startIndex; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/EnrolmentInfo.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/EnrolmentInfo.java index 9085468df0..2b287fa427 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/EnrolmentInfo.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/EnrolmentInfo.java @@ -31,7 +31,7 @@ public class EnrolmentInfo implements Serializable { public enum Status { CREATED, ACTIVE, INACTIVE, UNREACHABLE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED, DISENROLLMENT_REQUESTED, CONFIGURED, READY_TO_CONNECT, RETURN_PENDING, RETURNED, DEFECTIVE, WARRANTY_PENDING, WARRANTY_SENT, - WARRANTY_REPLACED, ASSIGNED + WARRANTY_REPLACED, ASSIGNED, DELETED } public enum OwnerShip { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/PaginationRequest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/PaginationRequest.java index ab1eeeff80..766bf6dc27 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/PaginationRequest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/PaginationRequest.java @@ -37,6 +37,7 @@ public class PaginationRequest { private Date since; private String filter; private String serialNumber; + private Map customProperty = new HashMap<>(); private Map property = new HashMap<>(); private List statusList = new ArrayList<>(); private OperationLogFilters operationLogFilters = new OperationLogFilters(); @@ -111,6 +112,18 @@ public class PaginationRequest { return ownership; } + public Map getCustomProperty() { + return customProperty; + } + + public void setCustomProperty(Map customProperty) { + this.customProperty = customProperty; + } + + public void addCustomProperty(String key, String value) { + customProperty.put(key, value); + } + public void setOwnership(String ownership) { this.ownership = ownership; } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/GeoLocationProviderService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/GeoLocationProviderService.java index 1d1cbf1d95..4a9da7c79c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/GeoLocationProviderService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/GeoLocationProviderService.java @@ -169,4 +169,11 @@ public interface GeoLocationProviderService { * @throws GeoLocationBasedServiceException any errors occurred while reading event records to geofence */ List getEventsOfGeoFence(int geoFenceId) throws GeoLocationBasedServiceException; + + /** + * Get geo fence count by tenant id + * @return returns the geofence count of tenant. + * @throws GeoLocationBasedServiceException any errors occurred while reading event records to geofence + */ + int getGeoFenceCount() throws GeoLocationBasedServiceException; } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/Activity.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/Activity.java index 5a04185e0a..3c68fc74b2 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/Activity.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/Activity.java @@ -49,6 +49,14 @@ public class Activity { @JsonProperty("code") private String code; + @ApiModelProperty( + name = "operationId", + value = "Operation Id", + required = false, + example = "10") + @JsonProperty("operationId") + private int operationId; + @ApiModelProperty( name = "type", value = "Activity type", @@ -80,6 +88,32 @@ public class Activity { @JsonProperty("initiatedBy") private String initiatedBy; + @ApiModelProperty(name = "appName", value = "App Name.") + private String appName; + + @ApiModelProperty(name = "packageName", + value = "package name of the application") + private String packageName; + @ApiModelProperty(name = "username", + value = "username of subscribed person") + private String username; + @ApiModelProperty(name = "status", + value = "Status of app install") + private String status; + + @ApiModelProperty(name = "version", + value = "Version of app") + private String version; + + @ApiModelProperty(name = "triggeredBy", + value = "Operation triggered by what") + private String triggeredBy; + + @ApiModelProperty(name = "appType", + value = "Type of application") + private String appType; + + public String getActivityId() { return activityId; } @@ -96,6 +130,14 @@ public class Activity { this.code = code; } + public int getOperationId() { + return operationId; + } + + public void setOperationId(int operationId) { + this.operationId = operationId; + } + public Type getType() { return type; } @@ -127,5 +169,61 @@ public class Activity { public void setInitiatedBy(String initiatedBy) { this.initiatedBy = initiatedBy; } + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public String getPackageName() { + return packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getTriggeredBy() { + return triggeredBy; + } + + public void setTriggeredBy(String triggeredBy) { + this.triggeredBy = triggeredBy; + } + + public String getAppType() { + return appType; + } + + public void setAppType(String appType) { + this.appType = appType; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml index e842d254fc..9f2d5aa52b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml @@ -22,7 +22,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/DeviceManagementConfigService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/DeviceManagementConfigService.java index 729e477c00..e5d65dd4d3 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/DeviceManagementConfigService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/DeviceManagementConfigService.java @@ -53,28 +53,28 @@ import java.util.List; @Scope( name = "View configurations", description = "", - key = "perm:view-configuration", + key = "dm:conf:view", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/platform-configurations/view"} ), @Scope( name = "Manage configurations", description = "", - key = "perm:manage-configuration", + key = "dm:conf:manage", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/platform-configurations/manage"} ), @Scope( name = "Getting Details of Device tenants", description = "Getting Details of Device tenants", - key = "perm:admin:tenant:view", + key = "admin:tenant:view", roles = {"Internal/devicemgt-user"}, permissions = {"/tenants/view"} ), @Scope( name = "Add a permission to the permission tree", description = "Add a permission to the permission tree", - key = "perm:admin:permissions:add", + key = "admin:permissions:add", roles = {"Internal/devicemgt-user"}, permissions = {"/permissions/add"} ) @@ -156,7 +156,7 @@ public interface DeviceManagementConfigService { tags = "Device Management Configuration", extensions = { @Extension(properties = { - @ExtensionProperty(name = "scope", value = "perm:manage-configuration") + @ExtensionProperty(name = "scope", value = "dm:conf:manage") }) } ) @@ -240,7 +240,7 @@ public interface DeviceManagementConfigService { tags = "Device Management Administrative Service", extensions = { @Extension(properties = { - @ExtensionProperty(name = "scope", value ="perm:admin:tenant:view") + @ExtensionProperty(name = "scope", value ="admin:tenant:view") }) } ) @@ -288,7 +288,7 @@ public interface DeviceManagementConfigService { extensions = { @Extension(properties = { @ExtensionProperty(name = "scope", value = - "perm:admin:permissions:add") + "admin:permissions:add") }) } ) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml index bf43ea4cde..d2f15964d3 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementConstants.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementConstants.java index 58be3dae82..8fc2e2804a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementConstants.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementConstants.java @@ -29,6 +29,7 @@ public final class DeviceManagementConstants { public static final String GEOFENCE_CACHE = "GEOFENCE_CACHE"; public static final String BILLING_CACHE = "BILLING_CACHE"; public static final String META_KEY = "PER_DEVICE_COST"; + public static final String DEP_META_KEY = "DEP_CONFIG"; public static final String ACTIVE_STATUS = "ACTIVE"; public static final String ENROLLMENT_NOTIFICATION_API_ENDPOINT = "/api/device-mgt/enrollment-notification"; public static final String URL_SEPERATOR = "/"; @@ -37,7 +38,7 @@ public final class DeviceManagementConstants { private ConfigurationManagement(){ throw new AssertionError(); } - public static final String SCOPES_FOR_TOKEN = "perm:device:operations perm:device:publish-event perm:windows:enroll"; + public static final String SCOPES_FOR_TOKEN = "dm:devices:ops:view dm:device:event:publish win:devices:enroll"; public static final String IOT_GATEWAY_HOST = "iot.gateway.host"; public static final String IOT_GATEWAY_HTTPS_PORT = "iot.gateway.https.port"; public static final String IOT_CORE_HOST = "iot.core.host"; @@ -155,6 +156,7 @@ public final class DeviceManagementConstants { new Permission("/permission/admin/device-mgt/devices/enroll", "ui.execute"), new Permission("/permission/admin/device-mgt/devices/disenroll", "ui.execute"), new Permission("/permission/admin/device-mgt/devices/owning-device/view", "ui.execute"), + new Permission("/permission/admin/device-mgt/devices/owning-device/operations/view", "ui.execute"), new Permission("/permission/admin/device-mgt/metadata", "ui.execute"), new Permission("/permission/admin/manage/portal", "ui.execute") }; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/DeviceManagementConfig.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/DeviceManagementConfig.java index e97ee8e108..d38eb41338 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/DeviceManagementConfig.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/DeviceManagementConfig.java @@ -39,6 +39,7 @@ import io.entgra.device.mgt.core.device.mgt.core.config.remote.session.RemoteSes import io.entgra.device.mgt.core.device.mgt.core.config.status.task.DeviceStatusTaskConfig; import io.entgra.device.mgt.core.device.mgt.core.config.task.TaskConfiguration; import io.entgra.device.mgt.core.device.mgt.core.event.config.EventOperationTaskConfiguration; +import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermissions; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @@ -75,6 +76,8 @@ public final class DeviceManagementConfig { private MetaDataConfiguration metaDataConfiguration; private EnrollmentGuideConfiguration enrollmentGuideConfiguration; + private DefaultPermissions defaultPermissions; + @XmlElement(name = "ManagementRepository", required = true) public DeviceManagementConfigRepository getDeviceManagementConfigRepository() { return deviceManagementConfigRepository; @@ -287,5 +290,14 @@ public final class DeviceManagementConfig { public void setEnrollmentGuideConfiguration(EnrollmentGuideConfiguration enrollmentGuideConfiguration) { this.enrollmentGuideConfiguration = enrollmentGuideConfiguration; } + + @XmlElement(name = "DefaultPermissions", required = true) + public DefaultPermissions getDefaultPermissions() { + return defaultPermissions; + } + + public void setDefaultPermissions(DefaultPermissions defaultPermissions) { + this.defaultPermissions = defaultPermissions; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/DefaultPermission.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/DefaultPermission.java new file mode 100644 index 0000000000..d8ee628924 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/DefaultPermission.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.device.mgt.core.config.permission; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "DefaultPermission") +public class DefaultPermission { + + private String name; + private ScopeMapping scopeMapping; + + @XmlElement(name = "Name", required = true) + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlElement(name = "MappedScopeDetails", required = true) + public ScopeMapping getScopeMapping() { + return scopeMapping; + } + + public void setScopeMapping(ScopeMapping scopeMapping) { + this.scopeMapping = scopeMapping; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/DefaultPermissions.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/DefaultPermissions.java new file mode 100644 index 0000000000..c04695b111 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/DefaultPermissions.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.device.mgt.core.config.permission; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "DefaultPermissions") +public class DefaultPermissions { + + private List defaultPermissions; + + @XmlElement(name = "DefaultPermission", required = true) + public List getDefaultPermissions() { + return defaultPermissions; + } + + public void setDefaultPermissions(List defaultPermissions) { + this.defaultPermissions = defaultPermissions; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/ScopeMapping.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/ScopeMapping.java new file mode 100644 index 0000000000..e745126502 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/ScopeMapping.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.device.mgt.core.config.permission; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "MappedScopeDetails") +public class ScopeMapping { + + private String name; + private String key; + + private String defaultRoles; + + @XmlElement(name = "Name", required = true) + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlElement(name = "Key", required = true) + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + @XmlElement(name = "DefaultRoles", required = true) + public String getDefaultRoles() { + return defaultRoles; + } + + public void setDefaultRoles(String defaultRoles) { + this.defaultRoles = defaultRoles; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/DeviceInfoConfigurations.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/DeviceInfoConfigurations.java new file mode 100644 index 0000000000..0e37753018 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/DeviceInfoConfigurations.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.device.mgt.core.config.ui; + +import javax.xml.bind.annotation.XmlElement; +import java.util.List; + +class DeviceInfoConfigurations { + + private List deviceInfoItems; + + @XmlElement(name = "DeviceInfoItem") + public List getDeviceInfoItems() { + return deviceInfoItems; + } + + public void setDeviceInfoItems(List deviceInfoItems) { + this.deviceInfoItems = deviceInfoItems; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/DeviceInfoItem.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/DeviceInfoItem.java new file mode 100644 index 0000000000..0f02669a49 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/DeviceInfoItem.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.device.mgt.core.config.ui; + +import javax.xml.bind.annotation.XmlElement; + +class DeviceInfoItem { + + private String definedValue; + private String displayValue; + + private String type; + + @XmlElement(name = "DefinedValue") + public String getDefinedValue() { + return definedValue; + } + + public void setDefinedValue(String definedValue) { + this.definedValue = definedValue; + } + + @XmlElement(name = "DisplayValue") + public String getDisplayValue() { + return displayValue; + } + + public void setDisplayValue(String displayValue) { + this.displayValue = displayValue; + } + + @XmlElement(name = "Type") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfiguration.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfiguration.java index 844c4039d2..6e71d17072 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfiguration.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfiguration.java @@ -36,6 +36,8 @@ public class UIConfiguration { private Billing billing; private HubspotChat hubspotChat; + private DeviceInfoConfigurations deviceInfoConfigurations; + @XmlElement(name = "AppRegistration", required=true) public AppRegistration getAppRegistration() { return appRegistration; @@ -98,4 +100,13 @@ public class UIConfiguration { public void setLoginCacheCapacity(int loginCacheCapacity) { this.loginCacheCapacity = loginCacheCapacity; } + + @XmlElement(name = "DeviceInfoConfigurations", required = true) + public DeviceInfoConfigurations getDeviceInfoConfigurations() { + return deviceInfoConfigurations; + } + + public void setDeviceInfoConfigurations(DeviceInfoConfigurations deviceInfoConfigurations) { + this.deviceInfoConfigurations = deviceInfoConfigurations; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceDAO.java index fa58ba9f4f..8b08641e2c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceDAO.java @@ -634,7 +634,7 @@ public interface DeviceDAO { * @param enrollmentIds list of enrollment ids. * @throws DeviceManagementDAOException when no enrolments are found for the given device. */ - void deleteDevices(List deviceIdentifiers, List deviceIds, List enrollmentIds) throws DeviceManagementDAOException; + void deleteDevices(List deviceIdentifiers, List deviceIds, List enrollmentIds, List validDevices) throws DeviceManagementDAOException; boolean transferDevice(String deviceType, String deviceId, String owner, int destinationTenantId) throws DeviceManagementDAOException, SQLException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GeofenceDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GeofenceDAO.java index a6fcf172e5..1546d4034e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GeofenceDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GeofenceDAO.java @@ -174,4 +174,12 @@ public interface GeofenceDAO { * @throws DeviceManagementDAOException */ GeofenceData getGeofence(int fenceId, boolean requireGroupData) throws DeviceManagementDAOException; + + /** + * This method is used to get the geofence count by tenant id. + * @param tenantId tenant id. + * @return returns the geofence count of tenant. + * @throws DeviceManagementDAOException + */ + int getGeofenceCount(int tenantId) throws DeviceManagementDAOException; } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 4515dc8734..3f654e3be1 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -41,6 +41,10 @@ import org.apache.commons.logging.LogFactory; import java.sql.*; import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.StringJoiner; +import java.util.Random; import java.util.*; public abstract class AbstractDeviceDAOImpl implements DeviceDAO { @@ -2145,7 +2149,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } @Override - public void deleteDevices(List deviceIdentifiers, List deviceIds, List enrollmentIds) + public void deleteDevices(List deviceIdentifiers, List deviceIds, List enrollmentIds, List validDevices) throws DeviceManagementDAOException { Connection conn; try { @@ -2200,7 +2204,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "operation response, enrollment operation mapping data of " + "devices with identifiers: " + deviceIdentifiers); } - removeDeviceEnrollment(conn, deviceIds); + refactorEnrolment(conn, deviceIds); + refactorDeviceStatus(conn, validDevices); if (log.isDebugEnabled()) { log.debug("Successfully removed device enrollment data of devices: " + deviceIdentifiers); } @@ -2208,7 +2213,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { if (log.isDebugEnabled()) { log.debug("Successfully removed device group mapping data of devices: " + deviceIdentifiers); } - removeDevice(conn, deviceIds); + refactorDevice(conn, deviceIds); if (log.isDebugEnabled()) { log.debug("Successfully permanently deleted the device of devices: " + deviceIdentifiers); } @@ -2739,30 +2744,6 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } - /*** - * This method removes records of a given list of enrollments from the DM_ENROLMENT table - * @param conn Connection object - * @param enrollmentIds list of enrollment ids (primary keys) - * @throws DeviceManagementDAOException if deletion fails - */ - private void removeDeviceEnrollment(Connection conn, List enrollmentIds) - throws DeviceManagementDAOException { - String sql = "DELETE FROM DM_ENROLMENT WHERE DEVICE_ID = ?"; - try { - if (!executeBatchOperation(conn, sql, enrollmentIds)) { - String msg = "Failed to remove enrollments of devices with enrollmentIds : " + enrollmentIds - + " while executing batch operation"; - log.error(msg); - throw new DeviceManagementDAOException(msg); - } - } catch (SQLException e) { - String msg = "SQL error occurred while removing enrollments of devices with enrollmentIds : " - + enrollmentIds; - log.error(msg, e); - throw new DeviceManagementDAOException(msg, e); - } - } - /*** * This method removes records of a given list of devices from the DM_DEVICE_GROUP_MAP table * @param conn Connection object @@ -2787,26 +2768,113 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } /*** - * This method removes records of a given list of devices from the DM_DEVICE table + * This method refactors some attributes of a given list of devices which are being deleted by the user * @param conn Connection object * @param deviceIds list of device ids (primary keys) - * @throws DeviceManagementDAOException if deletion fails + * @throws DeviceManagementDAOException if refactoring fails */ - private void removeDevice(Connection conn, List deviceIds) throws DeviceManagementDAOException { - String sql = "DELETE FROM DM_DEVICE WHERE ID = ?"; - try { - if (!executeBatchOperation(conn, sql, deviceIds)) { - String msg = "Failed to remove devices with deviceIds : " + deviceIds + " while executing batch operation"; - log.error(msg); - throw new DeviceManagementDAOException(msg); + public void refactorDevice(Connection conn, List deviceIds) throws DeviceManagementDAOException { + String updateQuery = "UPDATE DM_DEVICE SET DEVICE_IDENTIFICATION = ?, NAME = ? WHERE ID = ?"; + + try (PreparedStatement preparedStatement = conn.prepareStatement(updateQuery)) { + for (int deviceId : deviceIds) { + + String randomIdentification = generateRandomString(10); + String randomName = generateRandomString(20); + + preparedStatement.setString(1, randomIdentification); + preparedStatement.setString(2, randomName); + preparedStatement.setInt(3, deviceId); + + preparedStatement.executeUpdate(); } + } catch (SQLException e) { - String msg = "SQL error occurred while removing devices with deviceIds : " + deviceIds; + String msg = "SQL error occurred while refactoring device properties of deviceIds: " + deviceIds; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } } + + /*** + * This method refactors some attributes of a given list of devices in the DM_ENROLMENT table + * @param conn Connection object + * @param deviceIds list of device ids (primary keys) + * @throws DeviceManagementDAOException if refactoring fails + */ + public void refactorEnrolment(Connection conn, List deviceIds) throws DeviceManagementDAOException { + String updateQuery = "UPDATE DM_ENROLMENT SET OWNER = ?, STATUS = ? WHERE DEVICE_ID = ?"; + + try (PreparedStatement preparedStatement = conn.prepareStatement(updateQuery)) { + for (int deviceId : deviceIds) { + + String randomOwner = generateRandomString(4); + + preparedStatement.setString(1, randomOwner); + preparedStatement.setString(2, String.valueOf(Status.DELETED)); + preparedStatement.setInt(3, deviceId); + + preparedStatement.executeUpdate(); + } + + } catch (SQLException e) { + String msg = "SQL error occurred while refactoring device enrolment properties of deviceIds: " + deviceIds; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + + /*** + * This method updates the status of a given list of devices to DELETED state in the DM_DEVICE_STATUS table + * @param conn Connection object + * @param validDevices list of devices + * @throws DeviceManagementDAOException if updating fails + */ + public void refactorDeviceStatus(Connection conn, List validDevices) throws DeviceManagementDAOException { + String updateQuery = "UPDATE DM_DEVICE_STATUS SET STATUS = ? WHERE ID = ?"; + String selectLastMatchingRecordQuery = "SELECT ID FROM DM_DEVICE_STATUS WHERE ENROLMENT_ID = ? AND DEVICE_ID = ? ORDER BY ID DESC LIMIT 1"; + + try (PreparedStatement selectStatement = conn.prepareStatement(selectLastMatchingRecordQuery); + PreparedStatement updateStatement = conn.prepareStatement(updateQuery)) { + + for (Device device : validDevices) { + + selectStatement.setInt(1, device.getEnrolmentInfo().getId()); + selectStatement.setInt(2, device.getId()); + + ResultSet resultSet = selectStatement.executeQuery(); + int lastRecordId = 0; + if (resultSet.next()) { + lastRecordId = resultSet.getInt("ID"); + } + + updateStatement.setString(1, String.valueOf(Status.DELETED)); + updateStatement.setInt(2, lastRecordId); + updateStatement.execute(); + } + + } catch (SQLException e) { + String msg = "SQL error occurred while updating device status properties."; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + + private String generateRandomString(int length) { + String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + StringBuilder randomString = new StringBuilder(); + + Random random = new Random(); + + for (int i = 0; i < length; i++) { + int index = random.nextInt(characters.length()); + randomString.append(characters.charAt(index)); + } + + return randomString.toString(); + } + /*** * This method executes batch operations for a given list of primary keys * where the statement only has one param of type int, following the given pattern: diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGeofenceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGeofenceDAOImpl.java index 2b52de02e0..ca73829320 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGeofenceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGeofenceDAOImpl.java @@ -633,4 +633,28 @@ public abstract class AbstractGeofenceDAOImpl implements GeofenceDAO { throw new DeviceManagementDAOException(msg, e); } } + + @Override + public int getGeofenceCount(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = this.getConnection(); + String sql = "SELECT COUNT(*) AS geofence_count " + + "FROM DM_GEOFENCE " + + "WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + try (ResultSet rst = stmt.executeQuery()) { + if (rst.next()) { + return rst.getInt("geofence_count"); + } + } + } + return 0; // Return 0 if no records found for the given tenantId. + } catch (SQLException e) { + String msg = "Error occurred while retrieving Geofence count of the tenant " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java index 9a527cec08..17236e678f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java @@ -526,6 +526,14 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { stmt.setInt(1, groupId); stmt.setInt(2, tenantId); stmt.executeUpdate(); + sql = "DELETE FROM DM_DEVICE_EVENT_GROUP_MAPPING WHERE GROUP_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, groupId); + stmt.executeUpdate(); + sql = "DELETE FROM DM_GEOFENCE_GROUP_MAPPING WHERE GROUP_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, groupId); + stmt.executeUpdate(); } catch (SQLException e) { throw new GroupManagementDAOException("Error occurred while removing mappings for group.'", e); } finally { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/ApplicationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/ApplicationDAOImpl.java index 56ab396c4b..37c696f9fc 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/ApplicationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/ApplicationDAOImpl.java @@ -292,11 +292,11 @@ public class ApplicationDAOImpl implements ApplicationDAO { "WHERE A.NAME = DM_APPLICATION.NAME " + "AND A.ID < DM_APPLICATION.ID) " + "AND PLATFORM = ? " + - "AND TENANT_ID = ?"; + "AND TENANT_ID = ? "; try { String filter = request.getFilter(); if (filter != null) { - sql = sql + "AND NAME LIKE ?"; + sql = sql + "AND NAME LIKE ? "; } sql = sql + "LIMIT ? OFFSET ?"; Connection conn = this.getConnection(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java index 8206a36066..5107002ddc 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java @@ -53,7 +53,7 @@ public class DeviceStatusDAOImpl implements DeviceStatusDAO { } if (billingStatus) { - sql += " ORDER BY UPDATE_TIME DESC"; + sql += " ORDER BY ID DESC"; } stmt = conn.prepareStatement(sql); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index 27a3bd1ecc..1fac9ae6ae 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -33,6 +33,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.StringJoiner; +import java.util.Map; /** * This class holds the generic implementation of DeviceDAO which can be used to support ANSI db syntax. @@ -84,14 +85,40 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DEVICE_IDENTIFICATION, " + "t.NAME AS DEVICE_TYPE "; - if (serial != null) { - sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " + - "WHERE DEVICE_TYPE_ID = t.ID " + - "AND d.ID= i.DEVICE_ID " + - "AND i.KEY_FIELD = 'serial' " + - "AND i.VALUE_FIELD LIKE ? " + - "AND d.TENANT_ID = ? "; - isSerialProvided = true; + //Filter by serial number or any Custom Property in DM_DEVICE_INFO + if ((serial != null) || (request.getCustomProperty() != null && !request.getCustomProperty().isEmpty())) { + sql = sql + + "FROM DM_DEVICE d " + + "INNER JOIN DM_DEVICE_TYPE t ON d.DEVICE_TYPE_ID = t.ID " + + "WHERE "; + if (serial != null) { + sql += "EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di " + + "WHERE di.DEVICE_ID = d.ID " + + "AND di.KEY_FIELD = 'serial' " + + "AND di.VALUE_FIELD LIKE ? ) "; + isSerialProvided = true; + } + if (!request.getCustomProperty().isEmpty()) { + if (serial != null) { + sql += "AND "; + } + boolean firstCondition = true; + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + if (!firstCondition) { + sql += "AND "; + } + sql += "EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di " + + "WHERE di.DEVICE_ID = d.ID " + + "AND di.KEY_FIELD = '" + entry.getKey() + "' " + + "AND di.VALUE_FIELD LIKE ? ) "; + firstCondition = false; + } + } + sql += "AND d.TENANT_ID = ? "; } else { sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? "; } @@ -135,6 +162,11 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { if (isSerialProvided) { stmt.setString(paramIdx++, "%" + serial + "%"); } + if (request.getCustomProperty() != null && !request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + stmt.setString(paramIdx++, "%" + entry.getValue() + "%"); + } + } stmt.setInt(paramIdx++, tenantId); if (isSinceProvided) { stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); @@ -197,7 +229,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "WHERE " + "e.TENANT_ID=? AND " + "d.ID=e.DEVICE_ID AND " + - "STATUS !='REMOVED' AND " + + "STATUS NOT IN ('REMOVED', 'DELETED') AND " + "(" + "DATE_OF_ENROLMENT BETWEEN ? AND ? " + ")"; @@ -236,7 +268,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "from DM_DEVICE d, DM_ENROLMENT e " + "where " + "e.TENANT_ID=? and d.ID=e.DEVICE_ID and " + - "STATUS ='REMOVED' and " + + "(" + + "STATUS = 'REMOVED' OR STATUS = 'DELETED' " + + ") and " + "(" + "DATE_OF_ENROLMENT between ? and ? " + ") and " + @@ -279,7 +313,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "where " + "e.TENANT_ID=? and " + "d.ID=e.DEVICE_ID and " + - "STATUS !='REMOVED' and " + + "STATUS NOT IN ('REMOVED', 'DELETED') and " + "(" + "DATE_OF_ENROLMENT < ? " + ")"; @@ -318,7 +352,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "from DM_DEVICE d, DM_ENROLMENT e " + "where " + "e.TENANT_ID=? and d.ID=e.DEVICE_ID and " + - "STATUS ='REMOVED' and " + + "(" + + "STATUS = 'REMOVED' OR STATUS = 'DELETED' " + + ") and " + "(" + "DATE_OF_ENROLMENT < ? " + ") and " + @@ -616,6 +652,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; + String serial = request.getSerialNumber(); + boolean isSerialProvided = false; try { Connection conn = getConnection(); @@ -684,6 +722,28 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { sql += buildStatusQuery(statusList); isStatusProvided = true; } + //Filter Group with serial number or any Custom Property in DM_DEVICE_INFO + if (serial != null || !request.getCustomProperty().isEmpty()) { + if (serial != null) { + sql += "AND EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di " + + "WHERE di.DEVICE_ID = d1.DEVICE_ID " + + "AND di.KEY_FIELD = 'serial' " + + "AND di.VALUE_FIELD LIKE ?) "; + isSerialProvided = true; + } + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + sql += "AND EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di2 " + + "WHERE di2.DEVICE_ID = d1.DEVICE_ID " + + "AND di2.KEY_FIELD = '" + entry.getKey() + "' " + + "AND di2.VALUE_FIELD LIKE ?)"; + } + } + } sql = sql + " LIMIT ?,?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { @@ -713,6 +773,14 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setString(paramIdx++, status); } } + if (isSerialProvided) { + stmt.setString(paramIdx++, "%" + serial + "%"); + } + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + stmt.setString(paramIdx++, "%" + entry.getValue() + "%"); + } + } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx, request.getRowCount()); @@ -1242,6 +1310,17 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { query += buildStatusQuery(status); isStatusProvided = true; } + // Loop through custom properties and add conditions + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + query += " AND EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di2 " + + "WHERE di2.DEVICE_ID = DM_DEVICE.ID " + + "AND di2.KEY_FIELD = '" + entry.getKey() + "' " + + "AND di2.VALUE_FIELD LIKE ?)"; + } + } query = query + " LIMIT ?,?"; @@ -1269,6 +1348,12 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { ps.setString(index++, deviceStatus); } } + // Set custom property values in the loop + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + ps.setString(index++, "%" + entry.getValue() + "%"); + } + } ps.setInt(index++, offsetValue); ps.setInt(index, limitValue); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index 124039c057..7cfcd9946d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -36,6 +36,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.StringJoiner; +import java.util.Map; /** * This class holds the generic implementation of DeviceDAO which can be used to support ANSI db syntax. @@ -87,14 +88,40 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DEVICE_IDENTIFICATION, " + "t.NAME AS DEVICE_TYPE "; - if (serial != null) { - sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " + - "WHERE DEVICE_TYPE_ID = t.ID " + - "AND d.ID= i.DEVICE_ID " + - "AND i.KEY_FIELD = 'serial' " + - "AND i.VALUE_FIELD LIKE ? " + - "AND d.TENANT_ID = ? "; - isSerialProvided = true; + //Filter by serial number or any Custom Property in DM_DEVICE_INFO + if (serial != null || !request.getCustomProperty().isEmpty()) { + sql = sql + + "FROM DM_DEVICE d " + + "INNER JOIN DM_DEVICE_TYPE t ON d.DEVICE_TYPE_ID = t.ID " + + "WHERE "; + if (serial != null) { + sql += "EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di " + + "WHERE di.DEVICE_ID = d.ID " + + "AND di.KEY_FIELD = 'serial' " + + "AND di.VALUE_FIELD LIKE ? ) "; + isSerialProvided = true; + } + if (!request.getCustomProperty().isEmpty()) { + if (serial != null) { + sql += "AND "; + } + boolean firstCondition = true; + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + if (!firstCondition) { + sql += "AND "; + } + sql += "EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di " + + "WHERE di.DEVICE_ID = d.ID " + + "AND di.KEY_FIELD = '" + entry.getKey() + "' " + + "AND di.VALUE_FIELD LIKE ? ) "; + firstCondition = false; + } + } + sql += "AND d.TENANT_ID = ? "; } else { sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? "; } @@ -138,6 +165,11 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { if (isSerialProvided) { stmt.setString(paramIdx++, "%" + serial + "%"); } + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + stmt.setString(paramIdx++, "%" + entry.getValue() + "%"); + } + } stmt.setInt(paramIdx++, tenantId); if (isSinceProvided) { stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); @@ -448,6 +480,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; + String serial = request.getSerialNumber(); + boolean isSerialProvided = false; try { conn = getConnection(); @@ -516,6 +550,28 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { sql += buildStatusQuery(statusList); isStatusProvided = true; } + //Filter Group with serial number or any Custom Property in DM_DEVICE_INFO + if (serial != null || !request.getCustomProperty().isEmpty()) { + if (serial != null) { + sql += "AND EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di " + + "WHERE di.DEVICE_ID = d1.DEVICE_ID " + + "AND di.KEY_FIELD = 'serial' " + + "AND di.VALUE_FIELD LIKE ?) "; + isSerialProvided = true; + } + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + sql += "AND EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di2 " + + "WHERE di2.DEVICE_ID = d1.DEVICE_ID " + + "AND di2.KEY_FIELD = '" + entry.getKey() + "' " + + "AND di2.VALUE_FIELD LIKE ?)"; + } + } + } sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { @@ -545,6 +601,14 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setString(paramIdx++, status); } } + if (isSerialProvided) { + stmt.setString(paramIdx++, "%" + serial + "%"); + } + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + stmt.setString(paramIdx++, "%" + entry.getValue() + "%"); + } + } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx, request.getRowCount()); @@ -1029,6 +1093,17 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { query += buildStatusQuery(status); isStatusProvided = true; } + // Loop through custom properties and add conditions + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + query += " AND EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di2 " + + "WHERE di2.DEVICE_ID = DM_DEVICE.ID " + + "AND di2.KEY_FIELD = '" + entry.getKey() + "' " + + "AND di2.VALUE_FIELD LIKE ?)"; + } + } query = query + " ORDER BY DM_DEVICE.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; @@ -1053,6 +1128,12 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { ps.setString(index++, deviceStatus); } } + // Set custom property values in the loop + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + ps.setString(index++, "%" + entry.getValue() + "%"); + } + } ps.setInt(index++, offsetValue); ps.setInt(index, limitValue); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index f1b0ec91bb..82e35a3842 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -35,6 +35,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.StringJoiner; +import java.util.Map; /** * This class holds the generic implementation of DeviceDAO which can be used to support ANSI db syntax. @@ -86,14 +87,40 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DEVICE_IDENTIFICATION, " + "t.NAME AS DEVICE_TYPE "; - if (serial != null) { - sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " + - "WHERE DEVICE_TYPE_ID = t.ID " + - "AND d.ID= i.DEVICE_ID " + - "AND i.KEY_FIELD = 'serial' " + - "AND i.VALUE_FIELD LIKE ? " + - "AND d.TENANT_ID = ? "; - isSerialProvided = true; + //Filter by serial number or any Custom Property in DM_DEVICE_INFO + if (serial != null || !request.getCustomProperty().isEmpty()) { + sql = sql + + "FROM DM_DEVICE d " + + "INNER JOIN DM_DEVICE_TYPE t ON d.DEVICE_TYPE_ID = t.ID " + + "WHERE "; + if (serial != null) { + sql += "EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di " + + "WHERE di.DEVICE_ID = d.ID " + + "AND di.KEY_FIELD = 'serial' " + + "AND di.VALUE_FIELD LIKE ? ) "; + isSerialProvided = true; + } + if (!request.getCustomProperty().isEmpty()) { + if (serial != null) { + sql += "AND "; + } + boolean firstCondition = true; + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + if (!firstCondition) { + sql += "AND "; + } + sql += "EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di " + + "WHERE di.DEVICE_ID = d.ID " + + "AND di.KEY_FIELD = '" + entry.getKey() + "' " + + "AND di.VALUE_FIELD LIKE ? ) "; + firstCondition = false; + } + } + sql += "AND d.TENANT_ID = ? "; } else { sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? "; } @@ -132,6 +159,11 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { if (isSerialProvided) { stmt.setString(paramIdx++, "%" + serial + "%"); } + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + stmt.setString(paramIdx++, "%" + entry.getValue() + "%"); + } + } stmt.setInt(paramIdx++, tenantId); if (isDeviceTypeProvided) { stmt.setString(paramIdx++, deviceType); @@ -429,6 +461,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; + String serial = request.getSerialNumber(); + boolean isSerialProvided = false; try { conn = getConnection(); @@ -496,6 +530,28 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { sql += buildStatusQuery(statusList); isStatusProvided = true; } + //Filter Group with serial number or any Custom Property in DM_DEVICE_INFO + if (serial != null || !request.getCustomProperty().isEmpty()) { + if (serial != null) { + sql += "AND EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di " + + "WHERE di.DEVICE_ID = d1.DEVICE_ID " + + "AND di.KEY_FIELD = 'serial' " + + "AND di.VALUE_FIELD LIKE ?) "; + isSerialProvided = true; + } + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + sql += "AND EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di2 " + + "WHERE di2.DEVICE_ID = d1.DEVICE_ID " + + "AND di2.KEY_FIELD = '" + entry.getKey() + "' " + + "AND di2.VALUE_FIELD LIKE ?)"; + } + } + } sql = sql + " LIMIT ? OFFSET ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { @@ -525,6 +581,14 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setString(paramIdx++, status); } } + if (isSerialProvided) { + stmt.setString(paramIdx++, "%" + serial + "%"); + } + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + stmt.setString(paramIdx++, "%" + entry.getValue() + "%"); + } + } stmt.setInt(paramIdx++, request.getRowCount()); stmt.setInt(paramIdx, request.getStartIndex()); @@ -1008,6 +1072,17 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { query += buildStatusQuery(status); isStatusProvided = true; } + // Loop through custom properties and add conditions + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + query += " AND EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di2 " + + "WHERE di2.DEVICE_ID = DM_DEVICE.ID " + + "AND di2.KEY_FIELD = '" + entry.getKey() + "' " + + "AND di2.VALUE_FIELD LIKE ?)"; + } + } query = query + " LIMIT ? OFFSET ?"; @@ -1032,6 +1107,12 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { ps.setString(index++, deviceStatus); } } + // Set custom property values in the loop + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + ps.setString(index++, "%" + entry.getValue() + "%"); + } + } ps.setInt(index++, offsetValue); ps.setInt(index, limitValue); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index 1cbf9fe4d8..a09f74a354 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -36,6 +36,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.StringJoiner; +import java.util.Map; /** * This class holds the generic implementation of DeviceDAO which can be used to support ANSI db syntax. @@ -87,14 +88,40 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DEVICE_IDENTIFICATION, " + "t.NAME AS DEVICE_TYPE "; - if (serial != null) { - sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " + - "WHERE DEVICE_TYPE_ID = t.ID " + - "AND d.ID= i.DEVICE_ID " + - "AND i.KEY_FIELD = 'serial' " + - "AND i.VALUE_FIELD LIKE ? " + - "AND d.TENANT_ID = ? "; - isSerialProvided = true; + //Filter by serial number or any Custom Property in DM_DEVICE_INFO + if (serial != null || !request.getCustomProperty().isEmpty()) { + sql = sql + + "FROM DM_DEVICE d " + + "INNER JOIN DM_DEVICE_TYPE t ON d.DEVICE_TYPE_ID = t.ID " + + "WHERE "; + if (serial != null) { + sql += "EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di " + + "WHERE di.DEVICE_ID = d.ID " + + "AND di.KEY_FIELD = 'serial' " + + "AND di.VALUE_FIELD LIKE ? ) "; + isSerialProvided = true; + } + if (!request.getCustomProperty().isEmpty()) { + if (serial != null) { + sql += "AND "; + } + boolean firstCondition = true; + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + if (!firstCondition) { + sql += "AND "; + } + sql += "EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di " + + "WHERE di.DEVICE_ID = d.ID " + + "AND di.KEY_FIELD = '" + entry.getKey() + "' " + + "AND di.VALUE_FIELD LIKE ? ) "; + firstCondition = false; + } + } + sql += "AND d.TENANT_ID = ? "; } else { sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? "; } @@ -138,6 +165,11 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { if (isSerialProvided) { stmt.setString(paramIdx++, "%" + serial + "%"); } + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + stmt.setString(paramIdx++, "%" + entry.getValue() + "%"); + } + } stmt.setInt(paramIdx++, tenantId); if (isSinceProvided) { stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); @@ -448,6 +480,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; + String serial = request.getSerialNumber(); + boolean isSerialProvided = false; try { conn = getConnection(); @@ -515,6 +549,28 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { sql += buildStatusQuery(statusList); isStatusProvided = true; } + //Filter Group with serial number or any Custom Property in DM_DEVICE_INFO + if (serial != null || !request.getCustomProperty().isEmpty()) { + if (serial != null) { + sql += "AND EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di " + + "WHERE di.DEVICE_ID = d1.DEVICE_ID " + + "AND di.KEY_FIELD = 'serial' " + + "AND di.VALUE_FIELD LIKE ?) "; + isSerialProvided = true; + } + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + sql += "AND EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di2 " + + "WHERE di2.DEVICE_ID = d1.DEVICE_ID " + + "AND di2.KEY_FIELD = '" + entry.getKey() + "' " + + "AND di2.VALUE_FIELD LIKE ?)"; + } + } + } sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { @@ -544,6 +600,14 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setString(paramIdx++, status); } } + if (isSerialProvided) { + stmt.setString(paramIdx++, "%" + serial + "%"); + } + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + stmt.setString(paramIdx++, "%" + entry.getValue() + "%"); + } + } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx, request.getRowCount()); @@ -876,6 +940,17 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { query += buildStatusQuery(status); isStatusProvided = true; } + // Loop through custom properties and add conditions + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + query += " AND EXISTS (" + + "SELECT VALUE_FIELD " + + "FROM DM_DEVICE_INFO di2 " + + "WHERE di2.DEVICE_ID = DM_DEVICE.ID " + + "AND di2.KEY_FIELD = '" + entry.getKey() + "' " + + "AND di2.VALUE_FIELD LIKE ?)"; + } + } query = query + " ORDER BY DM_DEVICE.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; @@ -900,6 +975,12 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { ps.setString(index++, deviceStatus); } } + // Set custom property values in the loop + if (!request.getCustomProperty().isEmpty()) { + for (Map.Entry entry : request.getCustomProperty().entrySet()) { + ps.setString(index++, "%" + entry.getValue() + "%"); + } + } ps.setInt(index++, offsetValue); ps.setInt(index, limitValue); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java index b54d0e3ea4..2b68c264cf 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java @@ -57,7 +57,7 @@ public class SQLServerGroupDAOImpl extends AbstractGroupDAOImpl { try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER, STATUS, PARENT_PATH FROM DM_GROUP " + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER, STATUS, PARENT_PATH, PARENT_GROUP_ID FROM DM_GROUP " + "WHERE TENANT_ID = ?"; if (groupName != null && !groupName.isEmpty()) { sql += " AND GROUP_NAME LIKE ?"; @@ -129,7 +129,7 @@ public class SQLServerGroupDAOImpl extends AbstractGroupDAOImpl { try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER, STATUS, PARENT_PATH FROM DM_GROUP " + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER, STATUS, PARENT_PATH, PARENT_GROUP_ID FROM DM_GROUP " + "WHERE TENANT_ID = ?"; if (groupName != null && !groupName.isEmpty()) { sql += " AND GROUP_NAME LIKE ?"; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index c7f56174e5..c048bd4422 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -18,6 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.impl; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; +import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationException; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceDetailsWrapper; @@ -41,10 +46,6 @@ import io.entgra.device.mgt.core.device.mgt.core.report.mgt.Constants; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import io.entgra.device.mgt.core.device.mgt.core.util.HttpReportingUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.user.api.UserStoreException; import java.sql.SQLException; @@ -232,9 +233,19 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { deviceDetailsWrapper.setGroups(groups); } - String[] rolesOfUser = DeviceManagerUtil.getRolesOfUser(CarbonContext - .getThreadLocalCarbonContext() - .getUsername()); + String username = CarbonContext.getThreadLocalCarbonContext().getUsername(); + if (StringUtils.isEmpty(username)) { + boolean isUserAuthorized = DeviceManagementDataHolder.getInstance(). + getDeviceAccessAuthorizationService().isUserAuthorized( + new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()), + device.getEnrolmentInfo().getOwner() + ); + if (isUserAuthorized) { + username = device.getEnrolmentInfo().getOwner(); + } + } + + String[] rolesOfUser = DeviceManagerUtil.getRolesOfUser(username); if (rolesOfUser != null && rolesOfUser.length > 0) { deviceDetailsWrapper.setRole(rolesOfUser); } @@ -248,6 +259,10 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { log.error("Error occurred while getting group list", e); } catch (UserStoreException e) { log.error("Error occurred while getting role list", e); + } catch (DeviceAccessAuthorizationException e) { + log.error("User with name '" + device.getEnrolmentInfo().getOwner() + + "' is unauthorized to publish events for device with the id '" + + device.getDeviceIdentifier() + "'", e); } } else { if(log.isTraceEnabled()) { @@ -363,13 +378,6 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { DeviceManagementDAOFactory.beginTransaction(); DeviceLocation previousLocation = deviceDetailsDAO.getDeviceLocation(device.getId(), device.getEnrolmentInfo().getId()); - if (previousLocation == null) { - deviceDetailsDAO.addDeviceLocation(deviceLocation, device.getEnrolmentInfo().getId()); - } else { - deviceDetailsDAO.updateDeviceLocation(deviceLocation, device.getEnrolmentInfo().getId()); - } - deviceDetailsDAO.addDeviceLocationInfo(device, deviceLocation, - CarbonContext.getThreadLocalCarbonContext().getTenantId()); if (DeviceManagerUtil.isPublishLocationResponseEnabled()) { Object[] metaData = {device.getDeviceIdentifier(), device.getEnrolmentInfo().getOwner(), device.getType()}; Object[] payload = new Object[]{ @@ -382,11 +390,17 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { deviceLocation.getDistance() }; } - //Tracker update GPS Location if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) { DeviceManagementDataHolder.getInstance().getTraccarManagementService().updateLocation(device, deviceLocation); } else { + if (previousLocation == null) { + deviceDetailsDAO.addDeviceLocation(deviceLocation, device.getEnrolmentInfo().getId()); + } else { + deviceDetailsDAO.updateDeviceLocation(deviceLocation, device.getEnrolmentInfo().getId()); + } + deviceDetailsDAO.addDeviceLocationInfo(device, deviceLocation, + CarbonContext.getThreadLocalCarbonContext().getTenantId()); if(!HttpReportingUtil.isLocationPublishing()) { if (log.isDebugEnabled()) { log.debug("Location publishing is disabled"); @@ -453,29 +467,29 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { DeviceManagementDAOFactory.beginTransaction(); boolean previousLocation = deviceDetailsDAO.hasLocations(device.getId(), device.getEnrolmentInfo().getId()); - if (previousLocation) { - deviceDetailsDAO.updateDeviceLocation(mostRecentDeviceLocation, device.getEnrolmentInfo().getId()); - } else { - deviceDetailsDAO.addDeviceLocation(mostRecentDeviceLocation, device.getEnrolmentInfo().getId()); - } - - deviceDetailsDAO.addDeviceLocationsInfo(device, deviceLocations, - CarbonContext.getThreadLocalCarbonContext().getTenantId()); - - for (DeviceLocation deviceLocation: deviceLocations) { - //Tracker update GPS Location - if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) { - DeviceManagementDataHolder.getInstance().getTraccarManagementService().updateLocation(device, deviceLocation); + if(!HttpReportingUtil.isTrackerEnabled()) { + if (previousLocation) { + deviceDetailsDAO.updateDeviceLocation(mostRecentDeviceLocation, device.getEnrolmentInfo().getId()); } else { - if(!HttpReportingUtil.isLocationPublishing()) { - if (log.isDebugEnabled()) { - log.debug("Location publishing is disabled"); - } + deviceDetailsDAO.addDeviceLocation(mostRecentDeviceLocation, device.getEnrolmentInfo().getId()); + } + deviceDetailsDAO.addDeviceLocationsInfo(device, deviceLocations, + CarbonContext.getThreadLocalCarbonContext().getTenantId()); + } + if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) { + for (DeviceLocation deviceLocation: deviceLocations) { + //Tracker update GPS Location + DeviceManagementDataHolder.getInstance().getTraccarManagementService().updateLocation(device, deviceLocation); + } + } else { + if(!HttpReportingUtil.isLocationPublishing()) { + if (log.isDebugEnabled()) { + log.debug("Location publishing is disabled"); } - if (!HttpReportingUtil.isTrackerEnabled()) { - if (log.isDebugEnabled()) { - log.debug("Traccar is disabled"); - } + } + if (!HttpReportingUtil.isTrackerEnabled()) { + if (log.isDebugEnabled()) { + log.debug("Traccar is disabled"); } } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java index eca73e2fc6..7b846ebe1e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java @@ -1731,6 +1731,32 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } } + @Override + public int getGeoFenceCount() throws GeoLocationBasedServiceException { + int tenantId; + try { + tenantId = DeviceManagementDAOUtil.getTenantId(); + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while retrieving tenant id while get geofence data"; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } + try { + EventManagementDAOFactory.openConnection(); + return geofenceDAO.getGeofenceCount(tenantId); + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while retrieving geofence data for the tenant " + tenantId; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } catch (SQLException e) { + String msg = "Failed to open the DB connection to retrieve Geofence"; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } finally { + EventManagementDAOFactory.closeConnection(); + } + } + /** * Delete events of geofence * diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/OperationDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/OperationDAO.java index 9d3de1494e..2b5658d85f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/OperationDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/OperationDAO.java @@ -105,6 +105,10 @@ public interface OperationDAO { Map> getOperationMappingsByStatus(Operation.Status opStatus, Operation.PushNotificationStatus pushNotificationStatus, int limit) throws OperationManagementDAOException; + Map> getAllocatedOperationMappingsByStatus(Operation.Status opStatus, + Operation.PushNotificationStatus pushNotificationStatus, int limit, int activeServerCount, int serverIndex) + throws OperationManagementDAOException; + List getActivities(List deviceTypes, String operationCode, long updatedSince, String operationStatus) throws OperationManagementDAOException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java index 826fde0d1f..f47f796674 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java @@ -18,14 +18,15 @@ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; @@ -44,7 +45,7 @@ public class CommandOperationDAOImpl extends GenericOperationDAOImpl { try { Connection connection = OperationManagementDAOFactory.getConnection(); String sql = "INSERT INTO DM_OPERATION(TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, " + - "INITIATED_BY, ENABLED) VALUES (?, ?, ?, ?, ?, ?)"; + "INITIATED_BY, ENABLED, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?)"; stmt = connection.prepareStatement(sql, new String[]{"id"}); stmt.setString(1, operation.getType().toString()); stmt.setLong(2, DeviceManagementDAOUtil.getCurrentUTCTime()); @@ -52,6 +53,7 @@ public class CommandOperationDAOImpl extends GenericOperationDAOImpl { stmt.setString(4, operation.getCode()); stmt.setString(5, operation.getInitiatedBy()); stmt.setBoolean(6, operation.isEnabled()); + stmt.setInt(7, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java index 2817d192ab..d493a9ef9d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java @@ -18,14 +18,15 @@ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.ConfigOperation; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -47,7 +48,7 @@ public class ConfigOperationDAOImpl extends GenericOperationDAOImpl { operation.setCreatedTimeStamp(new Timestamp(new Date().getTime()).toString()); Connection connection = OperationManagementDAOFactory.getConnection(); String sql = "INSERT INTO DM_OPERATION(TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, " + - "INITIATED_BY, OPERATION_DETAILS) VALUES (?, ?, ?, ?, ?, ?)"; + "INITIATED_BY, OPERATION_DETAILS, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?)"; stmt = connection.prepareStatement(sql, new String[]{"id"}); stmt.setString(1, operation.getType().toString()); stmt.setLong(2, DeviceManagementDAOUtil.getCurrentUTCTime()); @@ -55,6 +56,7 @@ public class ConfigOperationDAOImpl extends GenericOperationDAOImpl { stmt.setString(4, operation.getCode()); stmt.setString(5, operation.getInitiatedBy()); stmt.setObject(6, operation); + stmt.setInt(7, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index 45283118c1..f8210282a2 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -17,6 +17,11 @@ */ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl; +import io.entgra.device.mgt.core.device.mgt.common.MDMAppConstants; +import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.ProfileOperation; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.ActivityPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; @@ -34,14 +39,17 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationMana import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; -import java.sql.*; +import java.io.ObjectInputStream; +import java.io.ByteArrayInputStream; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; @@ -62,7 +70,7 @@ public class GenericOperationDAOImpl implements OperationDAO { try { Connection connection = OperationManagementDAOFactory.getConnection(); String sql = "INSERT INTO DM_OPERATION(TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, " + - "INITIATED_BY, OPERATION_DETAILS) VALUES (?, ?, ?, ?, ?, ?)"; + "INITIATED_BY, OPERATION_DETAILS, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?)"; stmt = connection.prepareStatement(sql, new String[]{"id"}); stmt.setString(1, operation.getType().toString()); stmt.setLong(2, DeviceManagementDAOUtil.getCurrentUTCTime()); @@ -70,6 +78,7 @@ public class GenericOperationDAOImpl implements OperationDAO { stmt.setString(4, operation.getCode()); stmt.setString(5, operation.getInitiatedBy()); stmt.setObject(6, operation); + stmt.setInt(7, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); @@ -1345,6 +1354,7 @@ public class GenericOperationDAOImpl implements OperationDAO { List operations = new ArrayList<>(); String createdTo = null; String createdFrom = null; + ProfileOperation profileOperation = null; DateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); boolean isCreatedDayProvided = false; boolean isUpdatedDayProvided = false; //updated day = received day @@ -1367,6 +1377,7 @@ public class GenericOperationDAOImpl implements OperationDAO { "o.RECEIVED_TIMESTAMP, " + "o.OPERATION_CODE, " + "o.INITIATED_BY, " + + "o.OPERATION_DETAILS, " + "om.STATUS, " + "om.ID AS OM_MAPPING_ID, " + "om.UPDATED_TIMESTAMP " + @@ -1465,6 +1476,22 @@ public class GenericOperationDAOImpl implements OperationDAO { } operation.setCode(rs.getString("OPERATION_CODE")); operation.setInitiatedBy(rs.getString("INITIATED_BY")); + if (MDMAppConstants.AndroidConstants.UNMANAGED_APP_UNINSTALL.equals(operation.getCode())) { + byte[] operationDetails = rs.getBytes("OPERATION_DETAILS"); + try (ByteArrayInputStream bais = new ByteArrayInputStream(operationDetails); + ObjectInputStream ois = new ObjectInputStream(bais)) { + profileOperation = (ProfileOperation) ois.readObject(); + operation.setPayLoad(profileOperation.getPayLoad()); + } catch (IOException e) { + String msg = "IO Error occurred while retrieving app data of operation "; + log.error(msg, e); + throw new OperationManagementDAOException(msg, e); + } catch (ClassNotFoundException e) { + String msg = "Class not found error occurred while retrieving app data of operation "; + log.error(msg, e); + throw new OperationManagementDAOException(msg, e); + } + } operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); operations.add(operation); @@ -1485,6 +1512,7 @@ public class GenericOperationDAOImpl implements OperationDAO { List operations = new ArrayList<>(); String createdTo = null; String createdFrom = null; + ProfileOperation profileOperation = null; DateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); boolean isCreatedDayProvided = false; boolean isUpdatedDayProvided = false; //updated day = received day @@ -1507,6 +1535,7 @@ public class GenericOperationDAOImpl implements OperationDAO { "o.RECEIVED_TIMESTAMP, " + "o.OPERATION_CODE, " + "o.INITIATED_BY, " + + "o.OPERATION_DETAILS, " + "om.STATUS, " + "om.ID AS OM_MAPPING_ID, " + "om.UPDATED_TIMESTAMP " + @@ -1605,6 +1634,22 @@ public class GenericOperationDAOImpl implements OperationDAO { } operation.setCode(rs.getString("OPERATION_CODE")); operation.setInitiatedBy(rs.getString("INITIATED_BY")); + if (MDMAppConstants.AndroidConstants.UNMANAGED_APP_UNINSTALL.equals(operation.getCode())) { + byte[] operationDetails = rs.getBytes("OPERATION_DETAILS"); + try (ByteArrayInputStream bais = new ByteArrayInputStream(operationDetails); + ObjectInputStream ois = new ObjectInputStream(bais)) { + profileOperation = (ProfileOperation) ois.readObject(); + operation.setPayLoad(profileOperation.getPayLoad()); + } catch (IOException e) { + String msg = "IO Error occurred while retrieving app data of operation "; + log.error(msg, e); + throw new OperationManagementDAOException(msg, e); + } catch (ClassNotFoundException e) { + String msg = "Class not found error occurred while retrieving app data of operation "; + log.error(msg, e); + throw new OperationManagementDAOException(msg, e); + } + } operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); operations.add(operation); @@ -1962,6 +2007,54 @@ public class GenericOperationDAOImpl implements OperationDAO { return operationMappingsTenantMap; } + @Override + public Map> getAllocatedOperationMappingsByStatus(Operation.Status opStatus, + Operation.PushNotificationStatus pushNotificationStatus, int limit, int activeServerCount, int serverIndex) + throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Connection conn; + OperationMapping operationMapping; + Map> operationMappingsTenantMap = new HashMap<>(); + try { + conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT op.ENROLMENT_ID, op.OPERATION_ID, d.DEVICE_IDENTIFICATION, dt.NAME as DEVICE_TYPE, " + + "d.TENANT_ID FROM DM_DEVICE d, DM_ENROLMENT_OP_MAPPING op, DM_DEVICE_TYPE dt WHERE op.STATUS = ?" + + " AND op.PUSH_NOTIFICATION_STATUS = ? AND d.DEVICE_TYPE_ID = dt.ID AND d.ID=op.ENROLMENT_ID AND MOD(d.ID, ?) = ? ORDER" + + " BY op.OPERATION_ID LIMIT ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, opStatus.toString()); + stmt.setString(2, pushNotificationStatus.toString()); + stmt.setInt(3, activeServerCount); + stmt.setInt(4, serverIndex); + stmt.setInt(5, limit); + rs = stmt.executeQuery(); + while (rs.next()) { + int tenantID = rs.getInt("TENANT_ID"); + List operationMappings = operationMappingsTenantMap.get(tenantID); + if (operationMappings == null) { + operationMappings = new LinkedList<>(); + operationMappingsTenantMap.put(tenantID, operationMappings); + } + operationMapping = new OperationMapping(); + operationMapping.setOperationId(rs.getInt("OPERATION_ID")); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + deviceIdentifier.setType(rs.getString("DEVICE_TYPE")); + operationMapping.setDeviceIdentifier(deviceIdentifier); + operationMapping.setEnrollmentId(rs.getInt("ENROLMENT_ID")); + operationMapping.setTenantId(tenantID); + operationMappings.add(operationMapping); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("SQL error while getting operation mappings from database. " + + e.getMessage(), e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return operationMappingsTenantMap; + } + public List getActivities(List deviceTypes, String operationCode, long updatedSince, String operationStatus) throws OperationManagementDAOException { @@ -2124,41 +2217,70 @@ public class GenericOperationDAOImpl implements OperationDAO { " DM_ENROLMENT_OP_MAPPING eom " + "LEFT JOIN " + " DM_DEVICE_OPERATION_RESPONSE opr ON opr.EN_OP_MAP_ID = eom.ID " + - "INNER JOIN " + - " (SELECT DISTINCT OPERATION_ID FROM DM_ENROLMENT_OP_MAPPING WHERE TENANT_ID = ? "); + "INNER JOIN "); - if (activityPaginationRequest.getDeviceType() != null) { - sql.append("AND DEVICE_TYPE = ? "); - } - if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) { - sql.append("AND DEVICE_IDENTIFICATION IN ("); - for (int i = 0; i < activityPaginationRequest.getDeviceIds().size() - 1; i++) { - sql.append("?, "); + if (activityPaginationRequest.getDeviceType() != null || + (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) || + activityPaginationRequest.getSince() != 0 || + activityPaginationRequest.getStatus() != null) { + + sql.append("(SELECT DISTINCT OPERATION_ID FROM DM_ENROLMENT_OP_MAPPING eom WHERE TENANT_ID = ? "); + + if (activityPaginationRequest.getDeviceType() != null) { + sql.append("AND DEVICE_TYPE = ? "); + } + if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) { + sql.append("AND eom.DEVICE_IDENTIFICATION IN ("); + for (int i = 0; i < activityPaginationRequest.getDeviceIds().size() - 1; i++) { + sql.append("?, "); + } + sql.append("?) "); + } + if (activityPaginationRequest.getOperationId() > 0) { + sql.append("AND OPERATION_ID = ? "); + } + if (activityPaginationRequest.getOperationCode() != null) { + sql.append("AND OPERATION_CODE = ? "); + } + if (activityPaginationRequest.getInitiatedBy() != null) { + sql.append("AND INITIATED_BY = ? "); + } + if (activityPaginationRequest.getSince() != 0) { + sql.append("AND UPDATED_TIMESTAMP > ? "); + } + if (activityPaginationRequest.getStartTimestamp() > 0 && activityPaginationRequest.getEndTimestamp() > 0) { + isTimeDurationFilteringProvided = true; + sql.append("AND CREATED_TIMESTAMP BETWEEN ? AND ? "); + } + if (activityPaginationRequest.getType() != null) { + sql.append("AND TYPE = ? "); + } + if (activityPaginationRequest.getStatus() != null) { + sql.append("AND STATUS = ? "); } - sql.append("?) "); - } - if (activityPaginationRequest.getOperationCode() != null) { - sql.append("AND OPERATION_CODE = ? "); - } - if (activityPaginationRequest.getInitiatedBy() != null) { - sql.append("AND INITIATED_BY = ? "); - } - if (activityPaginationRequest.getSince() != 0) { - sql.append("AND UPDATED_TIMESTAMP > ? "); - } - if (activityPaginationRequest.getStartTimestamp() > 0 && activityPaginationRequest.getEndTimestamp() > 0) { - isTimeDurationFilteringProvided = true; - sql.append("AND CREATED_TIMESTAMP BETWEEN ? AND ? "); - } - if (activityPaginationRequest.getType() != null) { - sql.append("AND TYPE = ? "); - } - if (activityPaginationRequest.getStatus() != null) { - sql.append("AND STATUS = ? "); - } - sql.append("ORDER BY OPERATION_ID ASC limit ? , ? ) eom_ordered " + - "ON eom_ordered.OPERATION_ID = eom.OPERATION_ID WHERE eom.TENANT_ID = ? "); + sql.append("ORDER BY OPERATION_ID ASC limit ? , ? ) eom_ordered " + + "ON eom_ordered.OPERATION_ID = eom.OPERATION_ID WHERE eom.TENANT_ID = ? "); + } else { + sql.append("(SELECT ID AS OPERATION_ID FROM DM_OPERATION WHERE TENANT_ID = ? "); + + if (activityPaginationRequest.getStartTimestamp() > 0 && activityPaginationRequest.getEndTimestamp() > 0) { + isTimeDurationFilteringProvided = true; + sql.append("AND CREATED_TIMESTAMP BETWEEN ? AND ? "); + } + if (activityPaginationRequest.getOperationId() > 0) { + sql.append("AND ID = ? "); + } + if (activityPaginationRequest.getOperationCode() != null) { + sql.append("AND OPERATION_CODE = ? "); + } + if (activityPaginationRequest.getInitiatedBy() != null) { + sql.append("AND INITIATED_BY = ? "); + } + + sql.append("ORDER BY ID ASC limit ? , ? ) dm_ordered " + + "ON dm_ordered.OPERATION_ID = eom.OPERATION_ID WHERE eom.TENANT_ID = ? "); + } if (activityPaginationRequest.getDeviceType() != null) { sql.append("AND eom.DEVICE_TYPE = ? "); @@ -2173,6 +2295,9 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getOperationCode() != null) { sql.append("AND eom.OPERATION_CODE = ? "); } + if (activityPaginationRequest.getOperationId() > 0) { + sql.append("AND eom.OPERATION_ID = ? "); + } if (activityPaginationRequest.getInitiatedBy() != null) { sql.append("AND eom.INITIATED_BY = ? "); } @@ -2180,7 +2305,7 @@ public class GenericOperationDAOImpl implements OperationDAO { sql.append("AND eom.UPDATED_TIMESTAMP > ? "); } if (isTimeDurationFilteringProvided) { - sql.append("AND eom.CREATED_TIMESTAMP BETWEEN ? AND ? "); + sql.append("AND eom.CREATED_TIMESTAMP BETWEEN ? AND ? "); } if (activityPaginationRequest.getType() != null) { sql.append("AND eom.TYPE = ? "); @@ -2194,48 +2319,86 @@ public class GenericOperationDAOImpl implements OperationDAO { int index = 1; try (PreparedStatement stmt = conn.prepareStatement(sql.toString())) { stmt.setInt(index++, tenantId); - if (activityPaginationRequest.getDeviceType() != null) { - stmt.setString(index++, activityPaginationRequest.getDeviceType()); - } - if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) { - for (String deviceId : activityPaginationRequest.getDeviceIds()) { - stmt.setString(index++, deviceId); + if (activityPaginationRequest.getDeviceType() != null || + (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) || + activityPaginationRequest.getSince() != 0 || + activityPaginationRequest.getStatus() != null) { + + if (activityPaginationRequest.getDeviceType() != null) { + stmt.setString(index++, activityPaginationRequest.getDeviceType()); + } + if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) { + for (String deviceId : activityPaginationRequest.getDeviceIds()) { + stmt.setString(index++, deviceId); + } + } + if (activityPaginationRequest.getOperationCode() != null) { + stmt.setString(index++, activityPaginationRequest.getOperationCode()); + } + if (activityPaginationRequest.getOperationId() > 0) { + stmt.setInt(index++, activityPaginationRequest.getOperationId()); + } + if (activityPaginationRequest.getInitiatedBy() != null) { + stmt.setString(index++, activityPaginationRequest.getInitiatedBy()); + } + if (activityPaginationRequest.getSince() != 0) { + stmt.setLong(index++, activityPaginationRequest.getSince()); + } + if (isTimeDurationFilteringProvided) { + stmt.setLong(index++, activityPaginationRequest.getStartTimestamp()); + stmt.setLong(index++, activityPaginationRequest.getEndTimestamp()); + } + if (activityPaginationRequest.getType() != null) { + stmt.setString(index++, activityPaginationRequest.getType().name()); + } + if (activityPaginationRequest.getStatus() != null) { + stmt.setString(index++, activityPaginationRequest.getStatus().name()); + } + + stmt.setInt(index++, activityPaginationRequest.getOffset()); + stmt.setInt(index++, activityPaginationRequest.getLimit()); + stmt.setInt(index++, tenantId); + + if (activityPaginationRequest.getDeviceType() != null) { + stmt.setString(index++, activityPaginationRequest.getDeviceType()); + } + if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) { + for (String deviceId : activityPaginationRequest.getDeviceIds()) { + stmt.setString(index++, deviceId); + } + } + } else { + if (isTimeDurationFilteringProvided) { + stmt.setLong(index++, activityPaginationRequest.getStartTimestamp()); + stmt.setLong(index++, activityPaginationRequest.getEndTimestamp()); + } + if (activityPaginationRequest.getOperationCode() != null) { + stmt.setString(index++, activityPaginationRequest.getOperationCode()); + } + if (activityPaginationRequest.getOperationId() > 0) { + stmt.setInt(index++, activityPaginationRequest.getOperationId()); + } + if (activityPaginationRequest.getInitiatedBy() != null) { + stmt.setString(index++, activityPaginationRequest.getInitiatedBy()); + } + stmt.setInt(index++, activityPaginationRequest.getOffset()); + stmt.setInt(index++, activityPaginationRequest.getLimit()); + stmt.setInt(index++, tenantId); + + if (activityPaginationRequest.getDeviceType() != null) { + stmt.setString(index++, activityPaginationRequest.getDeviceType()); + } + if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) { + for (String deviceId : activityPaginationRequest.getDeviceIds()) { + stmt.setString(index++, deviceId); + } } } if (activityPaginationRequest.getOperationCode() != null) { stmt.setString(index++, activityPaginationRequest.getOperationCode()); } - if (activityPaginationRequest.getInitiatedBy() != null) { - stmt.setString(index++, activityPaginationRequest.getInitiatedBy()); - } - if (activityPaginationRequest.getSince() != 0) { - stmt.setLong(index++, activityPaginationRequest.getSince()); - } - if (isTimeDurationFilteringProvided) { - stmt.setLong(index++, activityPaginationRequest.getStartTimestamp()); - stmt.setLong(index++, activityPaginationRequest.getEndTimestamp()); - } - if (activityPaginationRequest.getType() != null) { - stmt.setString(index++, activityPaginationRequest.getType().name()); - } - if (activityPaginationRequest.getStatus() != null) { - stmt.setString(index++, activityPaginationRequest.getStatus().name()); - } - - stmt.setInt(index++, activityPaginationRequest.getOffset()); - stmt.setInt(index++, activityPaginationRequest.getLimit()); - stmt.setInt(index++, tenantId); - - if (activityPaginationRequest.getDeviceType() != null) { - stmt.setString(index++, activityPaginationRequest.getDeviceType()); - } - if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) { - for (String deviceId : activityPaginationRequest.getDeviceIds()) { - stmt.setString(index++, deviceId); - } - } - if (activityPaginationRequest.getOperationCode() != null) { - stmt.setString(index++, activityPaginationRequest.getOperationCode()); + if (activityPaginationRequest.getOperationId() > 0) { + stmt.setInt(index++, activityPaginationRequest.getOperationId()); } if (activityPaginationRequest.getInitiatedBy() != null) { stmt.setString(index++, activityPaginationRequest.getInitiatedBy()); @@ -2278,33 +2441,57 @@ public class GenericOperationDAOImpl implements OperationDAO { boolean isTimeDurationFilteringProvided = false; Connection conn = OperationManagementDAOFactory.getConnection(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - StringBuilder sql = new StringBuilder("SELECT count(DISTINCT OPERATION_ID) AS ACTIVITY_COUNT " + - "FROM DM_ENROLMENT_OP_MAPPING WHERE TENANT_ID = ? "); + StringBuilder sql = new StringBuilder(); - if (activityPaginationRequest.getDeviceType() != null) { - sql.append("AND DEVICE_TYPE = ? "); - } - if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) { - sql.append("AND DEVICE_IDENTIFICATION IN ("); - for (int i = 0; i < activityPaginationRequest.getDeviceIds().size() - 1; i++) { - sql.append("?, "); + if (activityPaginationRequest.getDeviceType() != null || + (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) || + activityPaginationRequest.getSince() != 0 || + activityPaginationRequest.getStatus() != null) { + + sql.append("SELECT count(DISTINCT OPERATION_ID) AS ACTIVITY_COUNT " + + "FROM DM_ENROLMENT_OP_MAPPING WHERE TENANT_ID = ? "); + + if (activityPaginationRequest.getDeviceType() != null) { + sql.append("AND DEVICE_TYPE = ? "); + } + if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) { + sql.append("AND DEVICE_IDENTIFICATION IN ("); + for (int i = 0; i < activityPaginationRequest.getDeviceIds().size() - 1; i++) { + sql.append("?, "); + } + sql.append("?) "); + } + if (activityPaginationRequest.getOperationCode() != null) { + sql.append("AND OPERATION_CODE = ? "); + } + if (activityPaginationRequest.getOperationId() > 0) { + sql.append("AND OPERATION_ID = ? "); + } + if (activityPaginationRequest.getInitiatedBy() != null) { + sql.append("AND INITIATED_BY = ? "); + } + if (activityPaginationRequest.getSince() != 0) { + sql.append("AND UPDATED_TIMESTAMP > ? "); + } + if (activityPaginationRequest.getType() != null) { + sql.append("AND TYPE = ? "); + } + if (activityPaginationRequest.getStatus() != null) { + sql.append("AND STATUS = ? "); + } + + } else { + sql.append("SELECT count(ID) AS ACTIVITY_COUNT FROM DM_OPERATION WHERE TENANT_ID = ? "); + + if (activityPaginationRequest.getOperationCode() != null) { + sql.append("AND OPERATION_CODE = ? "); + } + if (activityPaginationRequest.getOperationId() > 0) { + sql.append("AND ID = ? "); + } + if (activityPaginationRequest.getInitiatedBy() != null) { + sql.append("AND INITIATED_BY = ? "); } - sql.append("?) "); - } - if (activityPaginationRequest.getOperationCode() != null) { - sql.append("AND OPERATION_CODE = ? "); - } - if (activityPaginationRequest.getInitiatedBy() != null) { - sql.append("AND INITIATED_BY = ? "); - } - if (activityPaginationRequest.getSince() != 0) { - sql.append("AND UPDATED_TIMESTAMP > ? "); - } - if (activityPaginationRequest.getType() != null) { - sql.append("AND TYPE = ? "); - } - if (activityPaginationRequest.getStatus() != null) { - sql.append("AND STATUS = ? "); } if (activityPaginationRequest.getStartTimestamp() > 0 && activityPaginationRequest.getEndTimestamp() > 0) { isTimeDurationFilteringProvided = true; @@ -2314,28 +2501,47 @@ public class GenericOperationDAOImpl implements OperationDAO { int index = 1; try (PreparedStatement stmt = conn.prepareStatement(sql.toString())) { stmt.setInt(index++, tenantId); - if (activityPaginationRequest.getDeviceType() != null) { - stmt.setString(index++, activityPaginationRequest.getDeviceType()); - } - if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) { - for (String deviceId : activityPaginationRequest.getDeviceIds()) { - stmt.setString(index++, deviceId); + + if (activityPaginationRequest.getDeviceType() != null || + (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) || + activityPaginationRequest.getSince() != 0 || + activityPaginationRequest.getStatus() != null) { + if (activityPaginationRequest.getDeviceType() != null) { + stmt.setString(index++, activityPaginationRequest.getDeviceType()); + } + if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) { + for (String deviceId : activityPaginationRequest.getDeviceIds()) { + stmt.setString(index++, deviceId); + } + } + if (activityPaginationRequest.getOperationCode() != null) { + stmt.setString(index++, activityPaginationRequest.getOperationCode()); + } + if (activityPaginationRequest.getOperationId() > 0) { + stmt.setInt(index++, activityPaginationRequest.getOperationId()); + } + if (activityPaginationRequest.getInitiatedBy() != null) { + stmt.setString(index++, activityPaginationRequest.getInitiatedBy()); + } + if (activityPaginationRequest.getSince() != 0) { + stmt.setLong(index++, activityPaginationRequest.getSince()); + } + if (activityPaginationRequest.getType() != null) { + stmt.setString(index++, activityPaginationRequest.getType().name()); + } + if (activityPaginationRequest.getStatus() != null) { + stmt.setString(index++, activityPaginationRequest.getStatus().name()); + } + } else { + if (activityPaginationRequest.getOperationCode() != null) { + stmt.setString(index++, activityPaginationRequest.getOperationCode()); + } + if (activityPaginationRequest.getOperationId() > 0) { + stmt.setInt(index++, activityPaginationRequest.getOperationId()); + } + if (activityPaginationRequest.getInitiatedBy() != null) { + stmt.setString(index++, activityPaginationRequest.getInitiatedBy()); } - } - if (activityPaginationRequest.getOperationCode() != null) { - stmt.setString(index++, activityPaginationRequest.getOperationCode()); - } - if (activityPaginationRequest.getInitiatedBy() != null) { - stmt.setString(index++, activityPaginationRequest.getInitiatedBy()); - } - if (activityPaginationRequest.getSince() != 0) { - stmt.setLong(index++, activityPaginationRequest.getSince()); - } - if (activityPaginationRequest.getType() != null) { - stmt.setString(index++, activityPaginationRequest.getType().name()); - } - if (activityPaginationRequest.getStatus() != null) { - stmt.setString(index++, activityPaginationRequest.getStatus().name()); } if (isTimeDurationFilteringProvided) { stmt.setLong(index++, activityPaginationRequest.getStartTimestamp()); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java index cffcd5744e..bd4d74386a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java @@ -17,14 +17,15 @@ */ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.PolicyOperation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import java.io.*; import java.sql.*; @@ -49,7 +50,7 @@ public class PolicyOperationDAOImpl extends GenericOperationDAOImpl { operation.setEnabled(true); Connection connection = OperationManagementDAOFactory.getConnection(); String sql = "INSERT INTO DM_OPERATION(TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, " + - "INITIATED_BY, OPERATION_DETAILS, ENABLED) VALUES (?, ?, ?, ?, ?, ?, ?)"; + "INITIATED_BY, OPERATION_DETAILS, ENABLED, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; stmt = connection.prepareStatement(sql, new String[]{"id"}); stmt.setString(1, operation.getType().toString()); stmt.setLong(2, DeviceManagementDAOUtil.getCurrentUTCTime()); @@ -63,6 +64,7 @@ public class PolicyOperationDAOImpl extends GenericOperationDAOImpl { stmt.setBytes(6, bao.toByteArray()); stmt.setBoolean(7, operation.isEnabled()); + stmt.setInt(8, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ProfileOperationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ProfileOperationDAOImpl.java index 489ce3d306..93b25f47dc 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ProfileOperationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ProfileOperationDAOImpl.java @@ -17,18 +17,20 @@ */ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.ProfileOperation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import java.io.*; import java.sql.*; import java.util.ArrayList; +import java.util.Date; import java.util.List; public class ProfileOperationDAOImpl extends GenericOperationDAOImpl { @@ -45,7 +47,7 @@ public class ProfileOperationDAOImpl extends GenericOperationDAOImpl { operation.setEnabled(true); Connection connection = OperationManagementDAOFactory.getConnection(); String sql = "INSERT INTO DM_OPERATION(TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, " + - "INITIATED_BY, OPERATION_DETAILS, ENABLED) VALUES (?, ?, ?, ?, ?, ?, ?)"; + "INITIATED_BY, OPERATION_DETAILS, ENABLED, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; stmt = connection.prepareStatement(sql, new String[]{"id"}); stmt.setString(1, operation.getType().toString()); stmt.setLong(2, DeviceManagementDAOUtil.getCurrentUTCTime()); @@ -59,6 +61,7 @@ public class ProfileOperationDAOImpl extends GenericOperationDAOImpl { stmt.setBytes(6, bao.toByteArray()); stmt.setBoolean(7, operation.isEnabled()); + stmt.setInt(8, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java index 518ce5952a..5c502834c9 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java @@ -241,6 +241,7 @@ public class OperationDAOUtil { activity.setCreatedTimeStamp( new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString()); activity.setCode(rs.getString("OPERATION_CODE")); + activity.setOperationId(rs.getInt("OPERATION_ID")); activity.setInitiatedBy(rs.getString("INITIATED_BY")); DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java index 0639d60b4c..157795aa5a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java @@ -18,6 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.core.operation.timeout.task.impl; import com.google.gson.Gson; +import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityStatus; @@ -27,8 +30,6 @@ import io.entgra.device.mgt.core.device.mgt.core.config.operation.timeout.Operat import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.task.impl.DynamicPartitionedScheduleTask; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; @@ -36,7 +37,6 @@ import java.util.List; public class OperationTimeoutTask extends DynamicPartitionedScheduleTask { private static final Log log = LogFactory.getLog(OperationTimeoutTask.class); - @Override protected void setup() { @@ -44,45 +44,60 @@ public class OperationTimeoutTask extends DynamicPartitionedScheduleTask { @Override protected void executeDynamicTask() { - String operationTimeoutTaskConfigStr = getProperty( - OperationTimeoutTaskManagerServiceImpl.OPERATION_TIMEOUT_TASK_CONFIG); - Gson gson = new Gson(); - OperationTimeout operationTimeoutConfig = gson.fromJson(operationTimeoutTaskConfigStr, OperationTimeout.class); - try { - long timeMillis = System.currentTimeMillis() - operationTimeoutConfig.getTimeout() * 60 * 1000; - List deviceTypes = new ArrayList<>(); - if (operationTimeoutConfig.getDeviceTypes().size() == 1 && - "ALL".equals(operationTimeoutConfig.getDeviceTypes().get(0))) { - try { - List deviceTypeList = DeviceManagementDataHolder.getInstance() - .getDeviceManagementProvider().getDeviceTypes(); - for (DeviceType deviceType : deviceTypeList) { - deviceTypes.add(deviceType.getName()); + if (isQualifiedToExecuteTask()) { // this task will run only in one node when the deployment has multiple nodes + String operationTimeoutTaskConfigStr = getProperty( + OperationTimeoutTaskManagerServiceImpl.OPERATION_TIMEOUT_TASK_CONFIG); + Gson gson = new Gson(); + OperationTimeout operationTimeoutConfig = gson.fromJson(operationTimeoutTaskConfigStr, OperationTimeout.class); + try { + long timeMillis = System.currentTimeMillis() - (long) operationTimeoutConfig.getTimeout(); + List deviceTypes = new ArrayList<>(); + if (operationTimeoutConfig.getDeviceTypes().size() == 1 && + "ALL".equals(operationTimeoutConfig.getDeviceTypes().get(0))) { + try { + List deviceTypeList = DeviceManagementDataHolder.getInstance() + .getDeviceManagementProvider().getDeviceTypes(); + for (DeviceType deviceType : deviceTypeList) { + deviceTypes.add(deviceType.getName()); + } + } catch (DeviceManagementException e) { + log.error("Error occurred while reading device types", e); } - } catch (DeviceManagementException e) { - log.error("Error occurred while reading device types", e); + } else { + deviceTypes = operationTimeoutConfig.getDeviceTypes(); } - } else { - deviceTypes = operationTimeoutConfig.getDeviceTypes(); - } - List activities = DeviceManagementDataHolder.getInstance().getOperationManager() - .getActivities(deviceTypes, operationTimeoutConfig.getCode(), timeMillis, - operationTimeoutConfig.getInitialStatus()); - for (Activity activity : activities) { - for (ActivityStatus activityStatus : activity.getActivityStatus()) { - String operationId = activity.getActivityId().replace("ACTIVITY_", ""); - Operation operation = DeviceManagementDataHolder.getInstance().getOperationManager() - .getOperation(Integer.parseInt(operationId)); - operation.setStatus(Operation.Status.valueOf(operationTimeoutConfig.getNextStatus())); - DeviceManagementDataHolder.getInstance().getOperationManager() - .updateOperation(activityStatus.getDeviceIdentifier(), operation); + List activities = DeviceManagementDataHolder.getInstance().getOperationManager() + .getActivities(deviceTypes, operationTimeoutConfig.getCode(), timeMillis, + operationTimeoutConfig.getInitialStatus()); + for (Activity activity : activities) { + for (ActivityStatus activityStatus : activity.getActivityStatus()) { + String operationId = activity.getActivityId().replace("ACTIVITY_", ""); + Operation operation = DeviceManagementDataHolder.getInstance().getOperationManager() + .getOperation(Integer.parseInt(operationId)); + operation.setStatus(Operation.Status.valueOf(operationTimeoutConfig.getNextStatus())); + DeviceManagementDataHolder.getInstance().getOperationManager() + .updateOperation(activityStatus.getDeviceIdentifier(), operation); + } } - } - } catch (OperationManagementException e) { - String msg = "Error occurred while retrieving operations."; - log.error(msg, e); + } catch (OperationManagementException e) { + String msg = "Error occurred while retrieving operations."; + log.error(msg, e); + } } + } + private boolean isQualifiedToExecuteTask() { + if (isDynamicTaskEligible()) { + try { + return DeviceManagementDataHolder.getInstance().getHeartBeatService().isQualifiedToExecuteTask(); + } catch (HeartBeatManagementException e) { + log.error("Error while checking is qualified to execute task", e); + } + } else { + return true; + } + return false; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTaskManagerServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTaskManagerServiceImpl.java index 4da31f9f41..6875b62125 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTaskManagerServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTaskManagerServiceImpl.java @@ -57,14 +57,14 @@ public class OperationTimeoutTaskManagerServiceImpl implements OperationTimeoutT log.debug("Operation timeout task is started for the device type(s) : " + config.getDeviceTypes() + ", operation code : " + config.getInitialStatus()); log.debug( - "Operation timeout task is at frequency of : " + config.getTimeout() + " minutes"); + "Operation timeout task is at frequency of : " + config.getTimeout() + " milliseconds"); } TaskManager taskManager = taskService.getTaskManager(OPERATION_TIMEOUT_TASK); TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); //Convert to milli seconds - triggerInfo.setIntervalMillis(config.getTimeout() * 60 * 1000); + triggerInfo.setIntervalMillis(config.getTimeout()); triggerInfo.setRepeatCount(-1); Gson gson = new Gson(); @@ -125,7 +125,7 @@ public class OperationTimeoutTaskManagerServiceImpl implements OperationTimeoutT if (taskManager.isTaskScheduled(taskName)) { taskManager.deleteTask(taskName); TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); - triggerInfo.setIntervalMillis(config.getTimeout() * 60 * 1000); + triggerInfo.setIntervalMillis(config.getTimeout()); triggerInfo.setRepeatCount(-1); Map properties = new HashMap<>(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java index 074eb8eed7..bff66f7489 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java @@ -266,9 +266,7 @@ public class OTPManagementServiceImpl implements OTPManagementService { public OneTimePinDTO generateOneTimePin(OneTimePinDTO oneTimePinDTO, boolean persistPin) throws OTPManagementException { String otpValue = UUID.randomUUID().toString(); - - Gson gson = new Gson(); - String metaInfo = gson.toJson(oneTimePinDTO.getMetaInfo()); + String metaInfo = oneTimePinDTO.getMetaInfo(); oneTimePinDTO.setMetaInfo(metaInfo); oneTimePinDTO.setOtpToken(otpValue); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/task/PushNotificationSchedulerTask.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/task/PushNotificationSchedulerTask.java index 223535a29a..c4c9df0e56 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/task/PushNotificationSchedulerTask.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/task/PushNotificationSchedulerTask.java @@ -17,6 +17,12 @@ */ package io.entgra.device.mgt.core.device.mgt.core.push.notification.mgt.task; +import io.entgra.device.mgt.core.device.mgt.common.ServerCtxInfo; +import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; @@ -32,9 +38,6 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationMana import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationMappingDAO; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import java.util.HashMap; import java.util.LinkedList; @@ -63,9 +66,27 @@ public class PushNotificationSchedulerTask implements Runnable { try { //Get next available operation list per device batch OperationManagementDAOFactory.openConnection(); - operationMappingsTenantMap = operationDAO.getOperationMappingsByStatus(Operation.Status - .PENDING, Operation.PushNotificationStatus.SCHEDULED, DeviceConfigurationManager.getInstance() - .getDeviceManagementConfig().getPushNotificationConfiguration().getSchedulerBatchSize()); + try { + if (DeviceManagementDataHolder.getInstance().getHeartBeatService().isTaskPartitioningEnabled()) { + ServerCtxInfo serverCtxInfo = DeviceManagementDataHolder.getInstance().getHeartBeatService().getServerCtxInfo(); + if (serverCtxInfo != null) { + operationMappingsTenantMap = operationDAO.getAllocatedOperationMappingsByStatus(Operation.Status + .PENDING, Operation.PushNotificationStatus.SCHEDULED, DeviceConfigurationManager.getInstance() + .getDeviceManagementConfig().getPushNotificationConfiguration().getSchedulerBatchSize(), + serverCtxInfo.getActiveServerCount(), serverCtxInfo.getLocalServerHashIdx()); + } else { + if (log.isDebugEnabled()) { + log.debug("Active server information not recorded yet."); + } + } + } else { + operationMappingsTenantMap = operationDAO.getOperationMappingsByStatus(Operation.Status + .PENDING, Operation.PushNotificationStatus.SCHEDULED, DeviceConfigurationManager.getInstance() + .getDeviceManagementConfig().getPushNotificationConfiguration().getSchedulerBatchSize()); + } + } catch (HeartBeatManagementException e) { + throw new RuntimeException(e); + } } catch (OperationManagementDAOException e) { log.error("Unable to retrieve scheduled pending operations for task.", e); } finally { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 0a526d0283..6b14d3d32c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -652,6 +652,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv Map deviceManagerMap = new HashMap<>(); List deviceCacheKeyList = new ArrayList<>(); List existingDevices; + List validDevices = new ArrayList<>(); int tenantId = this.getTenantId(); try { @@ -684,6 +685,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv deviceCacheKey.setDeviceType(device.getType()); deviceCacheKey.setTenantId(tenantId); deviceCacheKeyList.add(deviceCacheKey); + validDevices.add(device); deviceIds.add(device.getId()); validDeviceIdentifiers.add(device.getDeviceIdentifier()); enrollmentIds.add(device.getEnrolmentInfo().getId()); @@ -713,7 +715,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv try { DeviceManagementDAOFactory.beginTransaction(); //deleting device from the core - deviceDAO.deleteDevices(validDeviceIdentifiers, new ArrayList<>(deviceIds), enrollmentIds); + deviceDAO.deleteDevices(validDeviceIdentifiers, new ArrayList<>(deviceIds), enrollmentIds, validDevices); for (Map.Entry entry : deviceManagerMap.entrySet()) { try { // deleting device from the plugin level @@ -1032,7 +1034,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv * @return Whether status is changed or not * @throws DeviceManagementException on errors while trying to calculate Cost */ - public BillingResponse calculateCost(String tenantDomain, Timestamp startDate, Timestamp endDate, List allDevices) throws MetadataManagementDAOException, DeviceManagementException { + public BillingResponse calculateUsage(String tenantDomain, Timestamp startDate, Timestamp endDate, List allDevices) throws MetadataManagementDAOException, DeviceManagementException { BillingResponse billingResponse = new BillingResponse(); List deviceStatusNotAvailable = new ArrayList<>(); @@ -1045,55 +1047,19 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv Gson g = new Gson(); Collection costData = null; + int tenantIdContext = CarbonContext.getThreadLocalCarbonContext().getTenantId(); Type collectionType = new TypeToken>() { }.getType(); - if (metadata != null) { + if (tenantIdContext == MultitenantConstants.SUPER_TENANT_ID && metadata != null) { costData = g.fromJson(metadata.getMetaValue(), collectionType); for (Cost tenantCost : costData) { if (tenantCost.getTenantDomain().equals(tenantDomain)) { - for (Device device : allDevices) { - long dateDiff = 0; - device.setDeviceStatusInfo(getDeviceStatusHistory(device, null, endDate, true)); - List deviceStatus = device.getDeviceStatusInfo(); - if (device.getEnrolmentInfo().getDateOfEnrolment() < startDate.getTime()) { - if (!deviceStatus.isEmpty() && String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED")) { - if (deviceStatus.get(0).getUpdateTime().getTime() >= startDate.getTime()) { - dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - startDate.getTime(); - } - } else if (!deviceStatus.isEmpty() && !String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED")) { - dateDiff = endDate.getTime() - startDate.getTime(); - } - } else { - if (!deviceStatus.isEmpty() && String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED")) { - if (deviceStatus.get(0).getUpdateTime().getTime() >= device.getEnrolmentInfo().getDateOfEnrolment()) { - dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - device.getEnrolmentInfo().getDateOfEnrolment(); - } - } else if (!deviceStatus.isEmpty() && !String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED")) { - dateDiff = endDate.getTime() - device.getEnrolmentInfo().getDateOfEnrolment(); - } - } - - // Convert dateDiff to days as a decimal value - double dateDiffInDays = (double) dateDiff / (24 * 60 * 60 * 1000); - - if (dateDiffInDays % 1 >= 0.9) { - dateDiffInDays = Math.ceil(dateDiffInDays); - } - - long dateInDays = (long) dateDiffInDays; - double cost = (tenantCost.getCost() / 365) * dateInDays; - totalCost += cost; - device.setCost(Math.round(cost * 100.0) / 100.0); - long totalDays = dateInDays + device.getDaysUsed(); - device.setDaysUsed((int) totalDays); - if (deviceStatus.isEmpty()) { - deviceStatusNotAvailable.add(device); - } - } - + totalCost = generateCost(allDevices, startDate, endDate, tenantCost, deviceStatusNotAvailable, totalCost); } } + } else { + totalCost = generateCost(allDevices, startDate, endDate, null, deviceStatusNotAvailable, totalCost); } } catch (DeviceManagementException e) { String msg = "Error occurred calculating cost of devices"; @@ -1125,6 +1091,56 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return billingResponse; } + public double generateCost(List allDevices, Timestamp startDate, Timestamp endDate, Cost tenantCost, List deviceStatusNotAvailable, double totalCost) throws DeviceManagementException { + for (Device device : allDevices) { + long dateDiff = 0; + device.setDeviceStatusInfo(getDeviceStatusHistory(device, null, endDate, true)); + List deviceStatus = device.getDeviceStatusInfo(); + if (device.getEnrolmentInfo().getDateOfEnrolment() < startDate.getTime()) { + if (!deviceStatus.isEmpty() && (String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") + || String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { + if (deviceStatus.get(0).getUpdateTime().getTime() >= startDate.getTime()) { + dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - startDate.getTime(); + } + } else if (!deviceStatus.isEmpty() && (!String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") + && !String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { + dateDiff = endDate.getTime() - startDate.getTime(); + } + } else { + if (!deviceStatus.isEmpty() && (String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") + || String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { + if (deviceStatus.get(0).getUpdateTime().getTime() >= device.getEnrolmentInfo().getDateOfEnrolment()) { + dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - device.getEnrolmentInfo().getDateOfEnrolment(); + } + } else if (!deviceStatus.isEmpty() && (!String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") + && !String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { + dateDiff = endDate.getTime() - device.getEnrolmentInfo().getDateOfEnrolment(); + } + } + + // Convert dateDiff to days as a decimal value + double dateDiffInDays = (double) dateDiff / (24 * 60 * 60 * 1000); + + if (dateDiffInDays % 1 >= 0.9) { + dateDiffInDays = Math.ceil(dateDiffInDays); + } + + long dateInDays = (long) dateDiffInDays; + double cost = 0; + if (tenantCost != null) { + cost = (tenantCost.getCost() / 365) * dateInDays; + } + totalCost += cost; + device.setCost(Math.round(cost * 100.0) / 100.0); + long totalDays = dateInDays + device.getDaysUsed(); + device.setDaysUsed((int) totalDays); + if (deviceStatus.isEmpty()) { + deviceStatusNotAvailable.add(device); + } + } + return totalCost; + } + @Override public PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException { @@ -1186,7 +1202,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv // The query returns devices which are enrolled prior this year now in removed state allDevicesPerYear.addAll(deviceDAO.getRemovedPriorYearsDeviceList(tenantId, newStartDate, newEndDate)); - BillingResponse billingResponse = calculateCost(tenantDomain, newStartDate, newEndDate, allDevicesPerYear); + BillingResponse billingResponse = calculateUsage(tenantDomain, newStartDate, newEndDate, allDevicesPerYear); billingResponseList.add(billingResponse); allDevices.addAll(billingResponse.getDevice()); totalCost = totalCost + billingResponse.getTotalCostPerYear(); @@ -1210,7 +1226,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv // The query returns devices which are enrolled prior this year now in removed state allDevicesPerRemainingDays.addAll(deviceDAO.getRemovedPriorYearsDeviceList(tenantId, startDate, endDate)); - BillingResponse billingResponse = calculateCost(tenantDomain, startDate, endDate, allDevicesPerRemainingDays); + BillingResponse billingResponse = calculateUsage(tenantDomain, startDate, endDate, allDevicesPerRemainingDays); billingResponseList.add(billingResponse); allDevices.addAll(billingResponse.getDevice()); totalCost = totalCost + billingResponse.getTotalCostPerYear(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderService.java index cea303b522..d6040274ef 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderService.java @@ -183,6 +183,14 @@ public interface GroupManagementProviderService { PaginationResult getGroupsWithHierarchy(String username, GroupPaginationRequest request, boolean requireGroupProps) throws GroupManagementException; + /** + * Get all hierarchical device groups count in tenant + * + * @return hierarchical group count + * @throws GroupManagementException + */ + int getHierarchicalGroupCount() throws GroupManagementException; + /** * Get all device group count in tenant * @@ -209,6 +217,16 @@ public interface GroupManagementProviderService { */ int getGroupCount(String username, String parentPath) throws GroupManagementException; + /** + * Get hierarchical device groups count of user + * + * @param username of the user + * @param parentPath of the group + * @return hierarchical group count + * @throws GroupManagementException + */ + int getHierarchicalGroupCount(String username, String parentPath) throws GroupManagementException; + /** * Manage device group sharing with user with list of roles. * diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java index 29654efe0e..9bcd5f7e7a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -842,6 +842,28 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid return groupResult; } + @Override + public int getHierarchicalGroupCount() throws GroupManagementException { + if (log.isDebugEnabled()) { + log.debug("Get groups count"); + } + try { + GroupManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + return groupDAO.getGroupCount(tenantId, null); + } catch (GroupManagementDAOException e) { + String msg = "Error occurred while retrieving all groups in tenant"; + log.error(msg, e); + throw new GroupManagementException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the data source."; + log.error(msg, e); + throw new GroupManagementException(msg, e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + } + @Override public int getGroupCount() throws GroupManagementException { if (log.isDebugEnabled()) { @@ -950,6 +972,52 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } } + /** + * {@inheritDoc} + */ + @Override + public int getHierarchicalGroupCount(String username, String parentPath) throws GroupManagementException { + if (username == null || username.isEmpty()) { + String msg = "Received empty user name for getHierarchicalGroupCount"; + log.error(msg); + throw new GroupManagementException(msg); + } + if (log.isDebugEnabled()) { + log.debug("Get groups count of '" + username + "'"); + } + UserStoreManager userStoreManager; + int count; + try { + GroupManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) + .getUserStoreManager(); + if (isAdminUser(username, userStoreManager)) { + count = groupDAO.getGroupCount(tenantId, null); + return count; + } else { + String[] roleList = userStoreManager.getRoleListOfUser(username); + count = groupDAO.getOwnGroupsCount(username, tenantId, parentPath); + count += groupDAO.getGroupsCount(roleList, tenantId, parentPath); + return count; + } + } catch (UserStoreException e) { + String msg = "Error occurred while retrieving role list of user '" + username + "'"; + log.error(msg, e); + throw new GroupManagementException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while opening db connection to get group count."; + log.error(msg, e); + throw new GroupManagementException(msg, e); + } catch (GroupManagementDAOException e) { + String msg = "Error occurred while retrieving group count of user '" + username + "'"; + log.error(msg, e); + throw new GroupManagementException(msg, e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + } + /** * {@inheritDoc} */ diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/HttpReportingUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/HttpReportingUtil.java index 642b50da81..005274375a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/HttpReportingUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/HttpReportingUtil.java @@ -23,6 +23,7 @@ import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; @@ -32,6 +33,7 @@ import org.apache.http.protocol.HTTP; import org.json.JSONObject; import java.io.IOException; +import java.net.ConnectException; public class HttpReportingUtil { @@ -57,6 +59,9 @@ public class HttpReportingUtil { apiEndpoint.setEntity(requestEntity); HttpResponse response = client.execute(apiEndpoint); return response.getStatusLine().getStatusCode(); + } catch (ConnectException e) { + log.error("Connection refused to API endpoint: " + endpoint, e); + return HttpStatus.SC_SERVICE_UNAVAILABLE; } catch (IOException e) { throw new EventPublishingException("Error occurred when " + "invoking API. API endpoint: " + endpoint, e); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestHeartBeatManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestHeartBeatManagementService.java index 93140f9a55..9cda4c3a74 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestHeartBeatManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestHeartBeatManagementService.java @@ -66,4 +66,9 @@ public class TestHeartBeatManagementService implements HeartBeatManagementServic @Override public Map getActiveServers() throws HeartBeatManagementException { return null; } + + @Override + public void notifyClusterFormationChanged(int elapsedTimeInSeconds) throws HeartBeatManagementException { + + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/task/PushNotificationSchedulerTaskTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/task/PushNotificationSchedulerTaskTest.java index bc593718d3..df04c2fb88 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/task/PushNotificationSchedulerTaskTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/task/PushNotificationSchedulerTaskTest.java @@ -31,6 +31,8 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationMana import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mockito.Mockito; @@ -52,13 +54,16 @@ public class PushNotificationSchedulerTaskTest extends BaseDeviceManagementTest private PushNotificationSchedulerTask pushNotificationSchedulerTask; private OperationDAO operationDAO; + private HeartBeatManagementService heartBeatManagementService; @BeforeClass public void init() throws DeviceManagementException, RegistryException { DeviceConfigurationManager.getInstance().initConfig(); log.info("Initializing Push Notification Scheduler Test Class"); DeviceManagementServiceComponent.notifyStartupListeners(); this.deviceMgtProviderService = Mockito.mock(DeviceManagementProviderServiceImpl.class, Mockito.CALLS_REAL_METHODS); + this.heartBeatManagementService = Mockito.mock(HeartBeatManagementService.class, Mockito.CALLS_REAL_METHODS); DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(this.deviceMgtProviderService); + DeviceManagementDataHolder.getInstance().setHeartBeatService(this.heartBeatManagementService); this.operationDAO = OperationManagementDAOFactory.getOperationDAO(); this.pushNotificationSchedulerTask = new PushNotificationSchedulerTask(); } @@ -69,6 +74,7 @@ public class PushNotificationSchedulerTaskTest extends BaseDeviceManagementTest OperationManagementDAOException { try { log.info("Attempting to execute push notification task scheduler"); + Mockito.when(this.heartBeatManagementService.isTaskPartitioningEnabled()).thenReturn(false); Mockito.doReturn(new TestNotificationStrategy()).when(this.deviceMgtProviderService) .getNotificationStrategyByDeviceType(Mockito.anyString()); Mockito.doReturn(new io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation()) @@ -81,6 +87,8 @@ public class PushNotificationSchedulerTaskTest extends BaseDeviceManagementTest .getPushNotificationConfiguration().getSchedulerBatchSize()); Assert.assertEquals(operationMappingsTenantMap.size(), 0); log.info("Push notification task execution complete."); + } catch (HeartBeatManagementException e) { + throw new RuntimeException(e); } finally { OperationManagementDAOFactory.closeConnection(); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql index ace89fc192..c326ee6d32 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql @@ -73,6 +73,65 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP ( REFERENCES DM_GROUP (ID) ON DELETE CASCADE ON UPDATE CASCADE ); +-- DM_GEOFENCE TABLE-- +CREATE TABLE IF NOT EXISTS DM_GEOFENCE +( + ID INT NOT NULL AUTO_INCREMENT, + FENCE_NAME VARCHAR(255) NOT NULL, + DESCRIPTION TEXT DEFAULT NULL, + LATITUDE DOUBLE DEFAULT NULL, + LONGITUDE DOUBLE DEFAULT NULL, + RADIUS DOUBLE DEFAULT NULL, + GEO_JSON TEXT DEFAULT NULL, + FENCE_SHAPE VARCHAR(100) DEFAULT NULL, + CREATED_TIMESTAMP TIMESTAMP NOT NULL, + OWNER VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) +); +-- END OF DM_GEOFENCE TABLE-- + +-- DM_GEOFENCE_GROUP_MAPPING TABLE-- +CREATE TABLE IF NOT EXISTS DM_GEOFENCE_GROUP_MAPPING +( + ID INT NOT NULL AUTO_INCREMENT, + FENCE_ID INT NOT NULL, + GROUP_ID INT NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_geofence_group_mapping_geofence FOREIGN KEY (FENCE_ID) REFERENCES + DM_GEOFENCE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_geofence_group_mapping_group FOREIGN KEY (GROUP_ID) REFERENCES + DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); +-- END OF DM_GEOFENCE_GROUP_MAPPING TABLE-- + +-- DM_DEVICE_EVENT TABLE -- +CREATE TABLE IF NOT EXISTS DM_DEVICE_EVENT +( + ID INT NOT NULL AUTO_INCREMENT, + EVENT_SOURCE VARCHAR(100) NOT NULL, + EVENT_LOGIC VARCHAR(100) NOT NULL, + ACTIONS TEXT DEFAULT NULL, + CREATED_TIMESTAMP TIMESTAMP NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) +); +-- END OF DM_DEVICE_EVENT TABLE -- + +-- DM_DEVICE_EVENT_GROUP_MAPPING TABLE-- +CREATE TABLE IF NOT EXISTS DM_DEVICE_EVENT_GROUP_MAPPING +( + ID INT NOT NULL AUTO_INCREMENT, + EVENT_ID INT NOT NULL, + GROUP_ID INT NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_event_group_mapping_event FOREIGN KEY (EVENT_ID) REFERENCES + DM_DEVICE_EVENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_event_group_mapping_group FOREIGN KEY (GROUP_ID) REFERENCES + DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); +-- END OF DM_DEVICE_EVENT_GROUP_MAPPING TABLE-- + CREATE TABLE IF NOT EXISTS DM_OPERATION ( ID INTEGER AUTO_INCREMENT NOT NULL, TYPE VARCHAR(50) NOT NULL, @@ -82,6 +141,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml index 86ab9fe65d..093a8444d6 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml @@ -22,7 +22,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql index a1cf506655..a67b29fa20 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql @@ -68,6 +68,10 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( CREATED_TIMESTAMP BIGINT NOT NULL, RECEIVED_TIMESTAMP BIGINT NULL, OPERATION_CODE VARCHAR(1000) NOT NULL, + INITIATED_BY VARCHAR(100) NULL, + OPERATION_DETAILS BLOB DEFAULT NULL, + ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml index 3fb64a0407..6cb6789f7f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml @@ -23,7 +23,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json index d17c6c8a4e..0d6874aa66 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json @@ -68,103 +68,103 @@ "copyrightSuffix": " All Rights Reserved." }, "scopes": [ - "perm:sign-csr", - "perm:admin:devices:view", - "perm:admin:topics:view", - "perm:roles:add", - "perm:roles:add-users", - "perm:roles:update", - "perm:roles:permissions", - "perm:roles:details", - "perm:roles:view", - "perm:roles:create-combined-role", - "perm:roles:delete", - "perm:dashboard:vulnerabilities", - "perm:dashboard:non-compliant-count", - "perm:dashboard:non-compliant", - "perm:dashboard:by-groups", - "perm:dashboard:device-counts", - "perm:dashboard:feature-non-compliant", - "perm:dashboard:count-overview", - "perm:dashboard:filtered-count", - "perm:dashboard:details", - "perm:get-activity", - "perm:devices:delete", - "perm:devices:applications", - "perm:devices:effective-policy", - "perm:devices:compliance-data", - "perm:devices:features", - "perm:devices:operations", - "perm:devices:search", - "perm:devices:details", - "perm:devices:update", - "perm:devices:view", - "perm:view-configuration", - "perm:manage-configuration", - "perm:policies:remove", - "perm:policies:priorities", - "perm:policies:deactivate", - "perm:policies:get-policy-details", - "perm:policies:manage", - "perm:policies:activate", - "perm:policies:update", - "perm:policies:changes", - "perm:policies:get-details", - "perm:users:add", - "perm:users:details", - "perm:users:count", - "perm:users:delete", - "perm:users:roles", - "perm:users:user-details", - "perm:users:credentials", - "perm:users:search", - "perm:users:is-exist", - "perm:users:update", - "perm:users:send-invitation", - "perm:admin-users:view", - "perm:admin:devices:update-enrollment", - "perm:groups:devices", - "perm:groups:update", - "perm:groups:add", - "perm:groups:device", - "perm:groups:devices-count", - "perm:groups:remove", - "perm:groups:groups", - "perm:groups:groups-view", - "perm:groups:share", - "perm:groups:count", - "perm:groups:roles", - "perm:groups:devices-remove", - "perm:groups:devices-add", - "perm:groups:assign", - "perm:device-types:configs", - "perm:device-types:features", - "perm:device-types:types", - "perm:applications:install", - "perm:applications:uninstall", - "perm:admin-groups:count", - "perm:admin-groups:view", - "perm:notifications:mark-checked", - "perm:notifications:view", - "perm:admin:certificates:delete", - "perm:admin:certificates:details", - "perm:admin:certificates:view", - "perm:admin:certificates:add", - "perm:admin:certificates:verify", - "perm:admin", - "perm:devicetype:deployment", - "perm:device-types:events", - "perm:device-types:events:view", - "perm:admin:device-type", - "perm:admin:device-type:view", - "perm:admin:device-type:configs", - "perm:device:enroll", - "perm:geo-service:analytics-view", - "perm:geo-service:alerts-manage", - "perm:devices:permanent-delete", + "dm:sign-csr", + "dm:admin:devices:view", + "dm:admin:topics:view", + "rm:roles:add", + "rm:users:add", + "rm:roles:update", + "rm:roles:permissions:view", + "rm:roles:details:view", + "rm:roles:view", + "rm:roles:combined:add", + "rm:roles:delete", + "an:db:vulnerabilities", + "an:db:non-compliant:count", + "an:db:non-compliant", + "an:db:by-groups", + "an:db:device:count", + "an:db:feature-non-compliant", + "an:db:overview:count", + "an:db:filtered-count", + "an:db:details", + "dm:activity:get", + "dm:devices:delete", + "dm:devices:app:view", + "dm:devices:policy:view", + "dm:devices:compliance:view", + "dm:devices:features:view", + "dm:devices:ops:view", + "dm:devices:search", + "dm:devices:details", + "dm:devices:update", + "dm:devices:view", + "dm:conf:view", + "dm:conf:manage", + "pm:policies:remove", + "pm:policies:priorities:update", + "pm:policies:deactivate", + "pm:policies:details:view", + "pm:policies:add", + "pm:policies:activate", + "pm:policies:update", + "pm:policies:change", + "dm:policies:view", + "um:users:add", + "um:users:details:view", + "um:users:count", + "um:users:delete", + "um:roles:view", + "um:users:user-details:view", + "um:users:cred:change", + "um:users:search", + "um:users:is-exist", + "um:users:update", + "um:users:invite", + "um:admin:users:view", + "dm:admin:enrollment:update", + "gm:devices:view", + "gm:groups:update", + "gm:groups:add", + "gm:groups:device:view", + "gm:devices:count", + "gm:groups:remove", + "gm:groups:view", + "gm:groups:groups-view", + "gm:roles:share", + "gm:groups:count", + "gm:roles:view", + "gm:devices:remove", + "gm:devices:add", + "gm:devices:assign", + "dm:device-type:conf:view", + "dm:device-type:features:view", + "dm:device-type:view", + "am:admin:app:install", + "am:admin:app:uninstall", + "gm:admin:groups:count", + "gm:admin:groups:view", + "dm:notif:mark-checked", + "dm:notifications:view", + "cm:cert:delete", + "cm:cert:details:get", + "cm:cert:view", + "cm:cert:add", + "cm:cert:verify", + "dm:admin", + "dm:device-type:deploy", + "dm:device-type:event:modify", + "dm:device-type:event:view", + "dm:admin:device-type:modify", + "dm:admin:device-type:view", + "dm:admin:device-type:conf:add", + "dm:device:enroll", + "dm:geo:an:view", + "dm:geo:alerts:manage", + "dm:admin:devices:permanent-delete", "appm:read", - "perm:enterprise:modify", - "perm:enterprise:view" + "and:enterprise:modify", + "and:enterprise:view" ], "isOAuthEnabled": true, "backendRestEndpoints": { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js index 2e604c3ad1..b01afcbf25 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js @@ -408,8 +408,8 @@ deviceModule = function () { //noinspection JSUnresolvedFunction var jwtClient = JWTClientManagerService.getJWTClient(); // returning access token by JWT grant type - var deviceScope = "device_" + type.replace(" ", "") + "_" + deviceId + " perm:device:enroll " + - "perm:device:disenroll perm:device:modify perm:device:operations perm:device:publish-event"; + var deviceScope = "device_" + type.replace(" ", "") + "_" + deviceId + " dm:device:enroll " + + "dm:device:disenroll dm:device:modify dm:devices:ops:view dm:device:event:publish"; var tokenInfo = jwtClient.getAccessToken(config.clientId, config.clientSecret, userName, deviceScope); config.accessToken = tokenInfo.getAccessToken(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.type-view/private/config.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.type-view/private/config.json index f5d01d0d77..9596bc2838 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.type-view/private/config.json +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.type-view/private/config.json @@ -3,14 +3,14 @@ "label": "Windows", "category": "mobile", "scopes" : [ - "perm:windows:enroll", - "perm:windows:lock-devices", - "perm:windows:ring", - "perm:windows:wipe", - "perm:windows:lock-reset", - "perm:windows:reboot", - "perm:windows:location", - "perm:windows:disenroll" + "win:devices:enroll", + "win:ops:lock-devices", + "win:ops:ring", + "win:ops:wipe", + "win:ops:lock-reset", + "win:ops:reboot", + "win:ops:location", + "win:ops:disenroll" ], "analyticsEnabled": "false", "groupingEnabled": "false", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.type-view/type-view.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.type-view/type-view.hbs index d93197ede7..b94dd02644 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.type-view/type-view.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.type-view/type-view.hbs @@ -120,7 +120,7 @@ -d '{ "applicationName":"testme", "isAllowedToAllDomains":false, "tags":["device_agent"]}'
  • Generate Token

    - curl -k -d "grant_type=password&username=%username%&password=%password%&scope=perm:device:enroll perm:device:disenroll perm:device:modify perm:device:operations perm:device:publish-event" + curl -k -d "grant_type=password&username=%username%&password=%password%&scope=dm:device:enroll dm:device:disenroll dm:device:modify dm:devices:ops:view dm:device:event:publish" -H "Authorization: Basic Base64(client_id:client_secret)" -H "Content-Type: application/x-www-form-urlencoded" {{httpsGateway}}/token
  • diff --git a/components/device-mgt/pom.xml b/components/device-mgt/pom.xml index e2a1396447..d5d99ff127 100644 --- a/components/device-mgt/pom.xml +++ b/components/device-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml index 7f246dab5d..7565c33587 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core heartbeat-management - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml @@ -82,6 +82,7 @@ !io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.internal, io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.* + * diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java index e7df3d8468..ca3cc09610 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java @@ -22,6 +22,7 @@ import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.HeartBeatBeaconC import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.HeartBeatBeaconUtils; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.InvalidConfigurationStateException; +import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.ClusterFormationChangedNotifier; import org.w3c.dom.Document; import org.wso2.carbon.utils.CarbonUtils; @@ -29,8 +30,10 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import java.io.File; +import java.util.List; @XmlRootElement(name = "HeartBeatBeaconConfig") public class HeartBeatBeaconConfig { @@ -50,6 +53,7 @@ public class HeartBeatBeaconConfig { private static final String SERVER_UUID_FILE_LOCATION = CarbonUtils.getCarbonConfigDirPath() + File.separator + "server-credentials.properties"; + private List notifiers; private HeartBeatBeaconConfig() { } @@ -135,4 +139,13 @@ public class HeartBeatBeaconConfig { } } + @XmlElementWrapper(name = "ClusterFormationChangedNotifiers", required = true) + @XmlElement(name = "Notifier", required = true) + public List getNotifiers() { + return notifiers; + } + + public void setNotifiers(List notifiers) { + this.notifiers = notifiers; + } } diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java index b170ffde5d..9d09ae699d 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java @@ -22,14 +22,18 @@ import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.HeartBeatBeaconU import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.config.HeartBeatBeaconConfig; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dao.HeartBeatBeaconDAOFactory; +import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.ClusterFormationChangedNotifierRepository; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementServiceImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; import org.osgi.service.component.annotations.*; +import org.wso2.carbon.core.ServerStartupObserver; import org.wso2.carbon.ndatasource.core.DataSourceService; +import java.util.List; + @Component( name = "io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.internal.HeartBeatBeaconComponent", immediate = true) @@ -53,10 +57,25 @@ public class HeartBeatBeaconComponent { DataSourceConfig dsConfig = HeartBeatBeaconConfig.getInstance().getDataSourceConfig(); HeartBeatBeaconDAOFactory.init(dsConfig); + ClusterFormationChangedNotifierRepository clusterFormationChangedNotifierRepository + = new ClusterFormationChangedNotifierRepository(); + List notifiers = HeartBeatBeaconConfig.getInstance().getNotifiers(); + if (notifiers != null && notifiers.size() > 0) { + for (String notifier : notifiers) { + clusterFormationChangedNotifierRepository.addNotifier(notifier); + } + } + HeartBeatBeaconDataHolder.getInstance().setClusterFormationChangedNotifierRepository( + clusterFormationChangedNotifierRepository); + //Setting up executors to notify heart beat status */ - HeartBeatExecutor.setUpNotifiers(HeartBeatBeaconUtils.getServerDetails()); + HeartBeatExecutor heartBeatExecutor = new HeartBeatExecutor(); + componentContext.getBundleContext().registerService( + ServerStartupObserver.class.getName(), heartBeatExecutor, null); } + + if (log.isDebugEnabled()) { log.debug("Heart Beat Notifier bundle has been successfully initialized"); } diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java index bde95e33c4..a3119d6064 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.internal; +import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.ClusterFormationChangedNotifierRepository; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; public class HeartBeatBeaconDataHolder { @@ -27,6 +28,7 @@ public class HeartBeatBeaconDataHolder { private static HeartBeatBeaconDataHolder thisInstance = new HeartBeatBeaconDataHolder(); + private ClusterFormationChangedNotifierRepository clusterFormationChangedNotifierRepository; private HeartBeatBeaconDataHolder() {} public static HeartBeatBeaconDataHolder getInstance() { @@ -48,4 +50,12 @@ public class HeartBeatBeaconDataHolder { public void setLocalServerUUID(String localServerUUID) { this.localServerUUID = localServerUUID; } + + public ClusterFormationChangedNotifierRepository getClusterFormationChangedNotifierRepository() { + return clusterFormationChangedNotifierRepository; + } + + public void setClusterFormationChangedNotifierRepository(ClusterFormationChangedNotifierRepository clusterFormationChangedNotifierRepository) { + this.clusterFormationChangedNotifierRepository = clusterFormationChangedNotifierRepository; + } } diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java index 81be3a999f..bcadf4afe7 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java @@ -26,13 +26,16 @@ import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dto.ServerContex import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.core.ServerStartupObserver; import java.io.IOException; +import java.net.SocketException; +import java.net.UnknownHostException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -public class HeartBeatExecutor { +public class HeartBeatExecutor implements ServerStartupObserver { private static Log log = LogFactory.getLog(HeartBeatExecutor.class); private static final int DEFAULT__NOTIFIER_INTERVAL = 5; @@ -43,6 +46,20 @@ public class HeartBeatExecutor { CONFIG = HeartBeatBeaconConfig.getInstance(); } + @Override + public void completingServerStartup() { + + } + + @Override + public void completedServerStartup() { + try { + setUpNotifiers(HeartBeatBeaconUtils.getServerDetails()); + } catch (HeartBeatBeaconConfigurationException | UnknownHostException | SocketException e) { + throw new RuntimeException(e); + } + } + static void setUpNotifiers(ServerContext ctx) throws HeartBeatBeaconConfigurationException { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); @@ -69,6 +86,7 @@ public class HeartBeatExecutor { try { recordHeartBeat(designatedUUID); electDynamicTaskExecutionCandidate(cumilativeTimeOut); + notifyClusterFormationChanged(cumilativeTimeOut); } catch (Exception e) { log.error("Error while executing record heart beat task. This will result in schedule operation malfunction.", e); } @@ -98,5 +116,8 @@ public class HeartBeatExecutor { HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().electCandidate(cumilativeTimeOut); } + static void notifyClusterFormationChanged(int cumilativeTimeOut) throws HeartBeatManagementException { + HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().notifyClusterFormationChanged(cumilativeTimeOut); + } } diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/ClusterFormationChangedNotifier.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/ClusterFormationChangedNotifier.java new file mode 100644 index 0000000000..ecd53d98ef --- /dev/null +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/ClusterFormationChangedNotifier.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service; + +public interface ClusterFormationChangedNotifier { + + String getType(); + + void notifyClusterFormationChanged(int hashIndex, int activeServerCount); +} diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/ClusterFormationChangedNotifierRepository.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/ClusterFormationChangedNotifierRepository.java new file mode 100644 index 0000000000..bb0c7726de --- /dev/null +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/ClusterFormationChangedNotifierRepository.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class ClusterFormationChangedNotifierRepository { + + private Map notifiers; + private static final Log log = LogFactory.getLog(ClusterFormationChangedNotifierRepository.class); + + public ClusterFormationChangedNotifierRepository() { + this.notifiers = new ConcurrentHashMap<>(); + } + + public void addNotifier(ClusterFormationChangedNotifier notifier) { + notifiers.put(notifier.getType(), notifier); + } + + public void addNotifier(String className) { + try { + if (!StringUtils.isEmpty(className)) { + Class clz = Class.forName(className); + ClusterFormationChangedNotifier notifier = (ClusterFormationChangedNotifier) clz.newInstance(); + notifiers.put(notifier.getType(), notifier); + } + } catch (ClassNotFoundException e) { + log.error("Provided ClusterFormationChangedNotifier implementation '" + className + "' cannot be found", e); + } catch (InstantiationException e) { + log.error("Error occurred while instantiating ClusterFormationChangedNotifier implementation '" + + className + "'", e); + } catch (IllegalAccessException e) { + log.error("Error occurred while adding ClusterFormationChangedNotifier implementation '" + className + "'", e); + } + } + + public ClusterFormationChangedNotifier getNotifier(String type) { + return notifiers.get(type); + } + + public Map getNotifiers() { + return notifiers; + } +} diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java index 14ae7d2648..afe54139ad 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java @@ -36,6 +36,7 @@ public interface HeartBeatManagementService { boolean recordHeartBeat(HeartBeatEvent event) throws HeartBeatManagementException; void electCandidate(int elapsedTimeInSeconds) throws HeartBeatManagementException; + void notifyClusterFormationChanged(int elapsedTimeInSeconds) throws HeartBeatManagementException; boolean updateTaskExecutionAcknowledgement(String newTask) throws HeartBeatManagementException; diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index 7c9b39f4ca..c2eb7bb037 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -43,6 +43,9 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic private final HeartBeatDAO heartBeatDAO; + private static int lastActiveCount = -1; + private static int lastHashIndex = -1; + public HeartBeatManagementServiceImpl() { this.heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); } @@ -227,6 +230,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } } else { //first time execution, elect if not present + heartBeatDAO.purgeCandidates(); electCandidate(servers); } HeartBeatBeaconDAOFactory.commitTransaction(); @@ -249,6 +253,62 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic throw new HeartBeatManagementException(msg); } } + @Override + public void notifyClusterFormationChanged(int elapsedTimeInSeconds) throws HeartBeatManagementException { + if (HeartBeatBeaconConfig.getInstance().isEnabled()) { + try { + HeartBeatBeaconDAOFactory.beginTransaction(); + Map servers = heartBeatDAO.getActiveServerDetails(elapsedTimeInSeconds); + HeartBeatBeaconDAOFactory.commitTransaction(); + if (servers != null && !servers.isEmpty()) { + String serverUUID = HeartBeatBeaconDataHolder.getInstance().getLocalServerUUID(); + ServerContext serverContext = servers.get(serverUUID); + + if (log.isDebugEnabled()) { + log.debug("HashIndex (previous, current) : " + lastHashIndex + ", " + serverContext.getIndex()); + log.debug("ActiveServerCount (previous, current) : " + lastActiveCount + ", " + servers.size()); + } + // cluster change can be identified, either by changing hash index or changing active server count + if ((lastHashIndex != serverContext.getIndex()) || (lastActiveCount != servers.size())) { + lastHashIndex = serverContext.getIndex(); + lastActiveCount = servers.size(); + + ClusterFormationChangedNotifierRepository repository = HeartBeatBeaconDataHolder.getInstance().getClusterFormationChangedNotifierRepository(); + Map notifiers = repository.getNotifiers(); + for (String type : notifiers.keySet()) { + ClusterFormationChangedNotifier notifier = notifiers.get(type); + Runnable r = new Runnable() { + @Override + public void run() { + if (log.isDebugEnabled()) { + log.debug("notify cluster formation changed : " + notifier.getType()); + } + notifier.notifyClusterFormationChanged(lastHashIndex, lastActiveCount); + } + }; + new Thread(r).start(); + } + } + } + } catch (HeartBeatDAOException e) { + String msg = "Error occurred while notifyClusterFormationChanged."; + log.error(msg, e); + throw new HeartBeatManagementException(msg, e); + } catch (TransactionManagementException e) { + HeartBeatBeaconDAOFactory.rollbackTransaction(); + String msg = "Error occurred while electing candidate for dynamic task execution. Issue in opening a connection to the underlying data source"; + log.error(msg, e); + throw new HeartBeatManagementException(msg, e); + } finally { + HeartBeatBeaconDAOFactory.closeConnection(); + } + } else { + String msg = "Heart Beat Configuration Disabled. Error while notifyClusterFormationChanged."; + log.error(msg); + throw new HeartBeatManagementException(msg); + } + } + private void electCandidate(Map servers) throws HeartBeatDAOException { String electedCandidate = getRandomElement(servers.keySet()); diff --git a/components/heartbeat-management/pom.xml b/components/heartbeat-management/pom.xml index bc020852a5..5bf8605825 100644 --- a/components/heartbeat-management/pom.xml +++ b/components/heartbeat-management/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml index fe664fe9c0..46a8b15955 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml +++ b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core identity-extensions - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml index 182d44cb46..0c872c556e 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core identity-extensions - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/identity-extensions/pom.xml b/components/identity-extensions/pom.xml index 2006d41b86..c46e433f55 100644 --- a/components/identity-extensions/pom.xml +++ b/components/identity-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml b/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml index b529e080d4..7774776d42 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core logger - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT io.entgra.device.mgt.core.notification.logger diff --git a/components/logger/pom.xml b/components/logger/pom.xml index 5c9d5d4aff..61e4bb82c7 100644 --- a/components/logger/pom.xml +++ b/components/logger/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml index adbd697680..aefe1407de 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core operation-template-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml @@ -69,7 +69,6 @@ io.entgra.device.mgt.core.operation.template.impl, io.entgra.device.mgt.core.operation.template.spi, io.entgra.device.mgt.core.operation.template.util, - javax.naming, javax.sql, javax.xml.bind;version="[2.3,3)", javax.xml.bind.annotation;version="[2.3,3)", @@ -78,6 +77,30 @@ org.apache.commons.logging;version="[1.2,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.apache.commons.logging, + org.apache.commons.lang, + javax.xml, + javax.xml.stream, + javax.xml.bind.*;version="${javax.xml.bind.imp.pkg.version}", + + org.w3c.dom, + com.google.gson.*, + javax.naming, + org.wso2.carbon.context, + org.wso2.carbon.base, + org.wso2.carbon.utils.*, + io.entgra.device.mgt.core.device.mgt.common.*, + io.entgra.device.mgt.core.device.mgt.core.*, + org.wso2.carbon.ndatasource.core, + org.wso2.carbon.registry.core, + org.wso2.carbon.registry.core.session, + org.wso2.carbon.registry.core.service, + org.wso2.carbon.registry.api, + io.entgra.device.mgt.core.device.mgt.extensions.license.mgt.registry, + javax.net.ssl, + org.wso2.carbon.core.util, + okhttp3, + com.google.common.cache.*, org.w3c.dom,org.wso2.carbon.ndatasource.core;version="[4.8,5)", org.wso2.carbon.registry.core.service;version="[1.0,2)", org.wso2.carbon.utils;version="[4.8,5)" @@ -299,6 +322,8 @@ com.google.guava guava + ${guava.version} + provided io.github.openfeign diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql index df3277920d..929eb1738a 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql @@ -90,6 +90,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); diff --git a/components/operation-template-mgt/pom.xml b/components/operation-template-mgt/pom.xml index be9af17775..16ed95de0b 100644 --- a/components/operation-template-mgt/pom.xml +++ b/components/operation-template-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml index 5faace82e2..ed44f640a0 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core policy-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml index 5839d7f1ac..ce1c3fb600 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core policy-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml index 0cde7266ce..81151e26cb 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core policy-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml index e978a1e1ec..4e4e734e66 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core policy-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TestHeartBeatManagementService.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TestHeartBeatManagementService.java index 7dae55b96b..305368ac79 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TestHeartBeatManagementService.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TestHeartBeatManagementService.java @@ -66,4 +66,9 @@ public class TestHeartBeatManagementService implements HeartBeatManagementServic @Override public Map getActiveServers() throws HeartBeatManagementException { return null; } + + @Override + public void notifyClusterFormationChanged(int elapsedTimeInSeconds) throws HeartBeatManagementException { + + } } diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql index e3ed0cd6ec..2a8c24a2df 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql @@ -137,6 +137,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); diff --git a/components/policy-mgt/pom.xml b/components/policy-mgt/pom.xml index 7f503a7932..83a54c18c3 100644 --- a/components/policy-mgt/pom.xml +++ b/components/policy-mgt/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml index b814a433d4..4941cff12b 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml @@ -20,7 +20,7 @@ io.entgra.device.mgt.core subtype-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/GetDeviceSubTypeCacheLoader.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/GetDeviceSubTypeCacheLoader.java index 6510eb26c5..6a598bf1f6 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/GetDeviceSubTypeCacheLoader.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/GetDeviceSubTypeCacheLoader.java @@ -47,7 +47,7 @@ public class GetDeviceSubTypeCacheLoader extends CacheLoader getAllDeviceSubTypes(int tenantId, DeviceSubType.DeviceType deviceType) + List getAllDeviceSubTypes(int tenantId, String deviceType) throws SubTypeMgtDAOException; - int getDeviceSubTypeCount(DeviceSubType.DeviceType deviceType) throws SubTypeMgtDAOException; + int getDeviceSubTypeCount(String deviceType) throws SubTypeMgtDAOException; - boolean checkDeviceSubTypeExist(String subTypeId, int tenantId, DeviceSubType.DeviceType deviceType) + boolean checkDeviceSubTypeExist(String subTypeId, int tenantId, String deviceType) throws SubTypeMgtDAOException; - DeviceSubType getDeviceSubTypeByProvider(String subTypeName, int tenantId, DeviceSubType.DeviceType deviceType) + DeviceSubType getDeviceSubTypeByProvider(String subTypeName, int tenantId, String deviceType) throws SubTypeMgtDAOException; } diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/DeviceSubTypeDAOFactory.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/DeviceSubTypeDAOFactory.java index baef7f9c3e..7c1d951859 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/DeviceSubTypeDAOFactory.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/DeviceSubTypeDAOFactory.java @@ -26,10 +26,14 @@ import io.entgra.device.mgt.core.subtype.mgt.dao.util.ConnectionManagerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import javax.sql.DataSource; +import java.sql.SQLException; + public class DeviceSubTypeDAOFactory { private static final Log log = LogFactory.getLog(DeviceSubTypeDAOFactory.class); private static String databaseEngine; + private static DataSource dataSource; public static void init(DataSourceConfig dataSourceConfiguration) { if (log.isDebugEnabled()) { log.debug("Initializing Device SubType Mgt Data Source"); @@ -38,6 +42,17 @@ public class DeviceSubTypeDAOFactory { databaseEngine = ConnectionManagerUtil.getDatabaseType(); } + public static void init(DataSource dtSource) { + dataSource = dtSource; + + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException var2) { + log.error("Error occurred while retrieving config.datasource connection", var2); + } + + } + public static DeviceSubTypeDAO getDeviceSubTypeDAO() { if (databaseEngine != null) { //noinspection SwitchStatementWithTooFewBranches diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/impl/DeviceSubTypeDAOImpl.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/impl/DeviceSubTypeDAOImpl.java index 7e903e22f2..755476b423 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/impl/DeviceSubTypeDAOImpl.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/impl/DeviceSubTypeDAOImpl.java @@ -67,7 +67,7 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { } @Override - public boolean updateDeviceSubType(String subTypeId, int tenantId, DeviceSubType.DeviceType deviceType, + public boolean updateDeviceSubType(String subTypeId, int tenantId, String deviceType, String subTypeName, String typeDefinition) throws SubTypeMgtDAOException { try { @@ -80,7 +80,7 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { stmt.setString(2, subTypeName); stmt.setString(3, subTypeId); stmt.setInt(4, tenantId); - stmt.setString(5, deviceType.toString()); + stmt.setString(5, deviceType); return stmt.executeUpdate() > 0; } @@ -98,7 +98,7 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { } @Override - public DeviceSubType getDeviceSubType(String subTypeId, int tenantId, DeviceSubType.DeviceType deviceType) + public DeviceSubType getDeviceSubType(String subTypeId, int tenantId, String deviceType) throws SubTypeMgtDAOException { try { String sql = "SELECT * FROM DM_DEVICE_SUB_TYPE WHERE SUB_TYPE_ID = ? AND TENANT_ID = ? AND DEVICE_TYPE = ?"; @@ -107,7 +107,7 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, subTypeId); stmt.setInt(2, tenantId); - stmt.setString(3, deviceType.toString()); + stmt.setString(3, deviceType); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { return DAOUtil.loadDeviceSubType(rs); @@ -130,7 +130,7 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { } @Override - public List getAllDeviceSubTypes(int tenantId, DeviceSubType.DeviceType deviceType) + public List getAllDeviceSubTypes(int tenantId, String deviceType) throws SubTypeMgtDAOException { try { String sql = "SELECT * FROM DM_DEVICE_SUB_TYPE WHERE TENANT_ID = ? AND DEVICE_TYPE = ? ORDER BY " + @@ -139,7 +139,7 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { Connection conn = ConnectionManagerUtil.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, tenantId); - stmt.setString(2, deviceType.toString()); + stmt.setString(2, deviceType); try (ResultSet rs = stmt.executeQuery()) { return DAOUtil.loadDeviceSubTypes(rs); } @@ -159,13 +159,13 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { } @Override - public int getDeviceSubTypeCount(DeviceSubType.DeviceType deviceType) throws SubTypeMgtDAOException { + public int getDeviceSubTypeCount(String deviceType) throws SubTypeMgtDAOException { try { String sql = "SELECT COUNT(*) as DEVICE_COUNT FROM DM_DEVICE_SUB_TYPE WHERE DEVICE_TYPE = ? "; Connection conn = ConnectionManagerUtil.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setString(1, deviceType.toString()); + stmt.setString(1, deviceType); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { return rs.getInt("DEVICE_COUNT"); @@ -188,7 +188,7 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { } @Override - public boolean checkDeviceSubTypeExist(String subTypeId, int tenantId, DeviceSubType.DeviceType deviceType) + public boolean checkDeviceSubTypeExist(String subTypeId, int tenantId, String deviceType) throws SubTypeMgtDAOException { try { String sql = "SELECT * FROM DM_DEVICE_SUB_TYPE WHERE SUB_TYPE_ID = ? AND TENANT_ID = ? AND DEVICE_TYPE " + @@ -198,7 +198,7 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, subTypeId); stmt.setInt(2, tenantId); - stmt.setString(3, deviceType.toString()); + stmt.setString(3, deviceType); try (ResultSet rs = stmt.executeQuery()) { return rs.next(); } @@ -219,7 +219,7 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { @Override public DeviceSubType getDeviceSubTypeByProvider(String subTypeName, int tenantId, - DeviceSubType.DeviceType deviceType) + String deviceType) throws SubTypeMgtDAOException { try { String sql = "SELECT * FROM DM_DEVICE_SUB_TYPE WHERE SUB_TYPE_NAME = ? AND TENANT_ID = ? AND DEVICE_TYPE " + @@ -229,7 +229,7 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, subTypeName); stmt.setInt(2, tenantId); - stmt.setString(3, deviceType.toString()); + stmt.setString(3, deviceType); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { return DAOUtil.loadDeviceSubType(rs); diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/util/DAOUtil.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/util/DAOUtil.java index 9473a88c6b..34e108a4a6 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/util/DAOUtil.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/util/DAOUtil.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.subtype.mgt.dao.util; +import com.fasterxml.jackson.core.JsonProcessingException; import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubType; import java.sql.ResultSet; @@ -30,17 +31,19 @@ public class DAOUtil { public static DeviceSubType loadDeviceSubType(ResultSet rs) throws SQLException { DeviceSubType deviceSubType = new DeviceSubType() { @Override - public DeviceSubType setDeviceSubType(T objType, String typeDef) { + public DeviceSubType convertToDeviceSubType() { return null; } @Override - public String parseSubTypeToJson(Object objType) { return null; } + public String parseSubTypeToJson() throws JsonProcessingException { + return null; + } }; deviceSubType.setTenantId(rs.getInt("TENANT_ID")); deviceSubType.setSubTypeId(rs.getString("SUB_TYPE_ID")); deviceSubType.setSubTypeName(rs.getString("SUB_TYPE_NAME")); - deviceSubType.setDeviceType(DeviceSubType.DeviceType.valueOf(rs.getString("DEVICE_TYPE"))); + deviceSubType.setDeviceType(rs.getString("DEVICE_TYPE")); deviceSubType.setTypeDefinition(rs.getString("TYPE_DEFINITION")); return deviceSubType; } diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dto/DeviceSubType.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dto/DeviceSubType.java index f914bf9930..84eaa124c6 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dto/DeviceSubType.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dto/DeviceSubType.java @@ -26,10 +26,21 @@ public abstract class DeviceSubType { private String subTypeId; private int tenantId; - private DeviceType deviceType; + private String deviceType; private String subTypeName; private String typeDefinition; + public DeviceSubType() { + } + + public DeviceSubType(String subTypeId, int tenantId, String deviceType, String subTypeName, String typeDefinition) { + this.subTypeId = subTypeId; + this.tenantId = tenantId; + this.deviceType = deviceType; + this.subTypeName = subTypeName; + this.typeDefinition = typeDefinition; + } + public String getSubTypeId() { return subTypeId; } @@ -46,11 +57,11 @@ public abstract class DeviceSubType { this.tenantId = tenantId; } - public DeviceType getDeviceType() { + public String getDeviceType() { return deviceType; } - public void setDeviceType(DeviceType deviceType) { + public void setDeviceType(String deviceType) { this.deviceType = deviceType; } @@ -70,11 +81,8 @@ public abstract class DeviceSubType { this.typeDefinition = typeDefinition; } - public abstract DeviceSubType setDeviceSubType(T objType, String typeDef); + public abstract DeviceSubType convertToDeviceSubType(); - public abstract String parseSubTypeToJson(Object objType) throws JsonProcessingException; + public abstract String parseSubTypeToJson() throws JsonProcessingException; - public enum DeviceType { - COM, METER, SIM - } } diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dto/DeviceSubTypeCacheKey.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dto/DeviceSubTypeCacheKey.java index eb66f92a46..2834300d5f 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dto/DeviceSubTypeCacheKey.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dto/DeviceSubTypeCacheKey.java @@ -21,7 +21,7 @@ package io.entgra.device.mgt.core.subtype.mgt.dto; public class DeviceSubTypeCacheKey { int tenantId; String subTypeId; - DeviceSubType.DeviceType deviceType; + String deviceType; public int getTenantId() { return tenantId; @@ -39,11 +39,11 @@ public class DeviceSubTypeCacheKey { this.subTypeId = subTypeId; } - public DeviceSubType.DeviceType getDeviceType() { + public String getDeviceType() { return deviceType; } - public void setDeviceType(DeviceSubType.DeviceType deviceType) { + public void setDeviceType(String deviceType) { this.deviceType = deviceType; } } diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/impl/DeviceSubTypeServiceImpl.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/impl/DeviceSubTypeServiceImpl.java index f1e44e325c..ceefa3f1e7 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/impl/DeviceSubTypeServiceImpl.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/impl/DeviceSubTypeServiceImpl.java @@ -93,7 +93,7 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { } @Override - public boolean updateDeviceSubType(String subTypeId, int tenantId, DeviceSubType.DeviceType deviceType, + public boolean updateDeviceSubType(String subTypeId, int tenantId, String deviceType, String subTypeName, String typeDefinition) throws SubTypeMgtPluginException { String msg = ""; @@ -139,13 +139,13 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { } @Override - public DeviceSubType getDeviceSubType(String subTypeId, int tenantId, DeviceSubType.DeviceType deviceType) + public DeviceSubType getDeviceSubType(String subTypeId, int tenantId, String deviceType) throws SubTypeMgtPluginException { try { String key = DeviceSubTypeMgtUtil.setDeviceSubTypeCacheKey(tenantId, subTypeId, deviceType); return deviceSubTypeCache.get(key); } catch (CacheLoader.InvalidCacheLoadException e) { - String msg = "Not having any sim subtype for subtype id: " + subTypeId; + String msg = "Not having any" + deviceType + " subtype for subtype id: " + subTypeId; log.error(msg, e); return null; } catch (ExecutionException e) { @@ -156,7 +156,7 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { } @Override - public List getAllDeviceSubTypes(int tenantId, DeviceSubType.DeviceType deviceType) + public List getAllDeviceSubTypes(int tenantId, String deviceType) throws SubTypeMgtPluginException { try { ConnectionManagerUtil.openDBConnection(); @@ -177,20 +177,14 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { } @Override - public int getDeviceSubTypeCount(DeviceSubType.DeviceType deviceType) throws SubTypeMgtPluginException { + public int getDeviceSubTypeCount(String deviceType) throws SubTypeMgtPluginException { try { - ConnectionManagerUtil.openDBConnection(); int result = deviceSubTypeDAO.getDeviceSubTypeCount(deviceType); if (result <= 0) { String msg = "There are no any subtypes for device type: " + deviceType; log.error(msg); } return result; - } catch (DBConnectionException e) { - String msg = "Error occurred while obtaining the database connection to retrieve device subtypes count " + - "for " + deviceType + " subtypes"; - log.error(msg); - throw new SubTypeMgtPluginException(msg, e); } catch (SubTypeMgtDAOException e) { String msg = "Error occurred in the database level while retrieving device subtypes count for " + deviceType + " subtypes"; @@ -203,16 +197,10 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { @Override public DeviceSubType getDeviceSubTypeByProvider(String subTypeName, int tenantId, - DeviceSubType.DeviceType deviceType) + String deviceType) throws SubTypeMgtPluginException { try { - ConnectionManagerUtil.openDBConnection(); return deviceSubTypeDAO.getDeviceSubTypeByProvider(subTypeName, tenantId, deviceType); - } catch (DBConnectionException e) { - String msg = "Error occurred while obtaining the database connection to retrieve device subtype for " + - deviceType + " subtype & subtype name: " + subTypeName; - log.error(msg); - throw new SubTypeMgtPluginException(msg, e); } catch (SubTypeMgtDAOException e) { String msg = "Error occurred in the database level while retrieving device subtype for " + deviceType + " subtype & subtype name: " + subTypeName; @@ -224,16 +212,10 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { } @Override - public boolean checkDeviceSubTypeExist(String subTypeId, int tenantId, DeviceSubType.DeviceType deviceType) + public boolean checkDeviceSubTypeExist(String subTypeId, int tenantId, String deviceType) throws SubTypeMgtPluginException { try { - ConnectionManagerUtil.openDBConnection(); return deviceSubTypeDAO.checkDeviceSubTypeExist(subTypeId, tenantId, deviceType); - } catch (DBConnectionException e) { - String msg = "Error occurred while obtaining the database connection to check device subtype exist for " + - deviceType + " subtype & subtype id: " + subTypeId; - log.error(msg); - throw new SubTypeMgtPluginException(msg, e); } catch (SubTypeMgtDAOException e) { String msg = "Error occurred in the database level while checking device subtype exist for " + deviceType + " subtype & subtype id: " + subTypeId; diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/spi/DeviceSubTypeService.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/spi/DeviceSubTypeService.java index f5bb01d6e2..45d8b2715c 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/spi/DeviceSubTypeService.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/spi/DeviceSubTypeService.java @@ -27,20 +27,20 @@ public interface DeviceSubTypeService { boolean addDeviceSubType(DeviceSubType deviceSubType) throws SubTypeMgtPluginException; - boolean updateDeviceSubType(String subTypeId, int tenantId, DeviceSubType.DeviceType deviceType, String subTypeName, + boolean updateDeviceSubType(String subTypeId, int tenantId, String deviceType, String subTypeName, String typeDefinition) throws SubTypeMgtPluginException; - DeviceSubType getDeviceSubType(String subTypeId, int tenantId, DeviceSubType.DeviceType deviceType) + DeviceSubType getDeviceSubType(String subTypeId, int tenantId, String deviceType) throws SubTypeMgtPluginException; - List getAllDeviceSubTypes(int tenantId, DeviceSubType.DeviceType deviceType) + List getAllDeviceSubTypes(int tenantId, String deviceType) throws SubTypeMgtPluginException; - int getDeviceSubTypeCount(DeviceSubType.DeviceType deviceType) throws SubTypeMgtPluginException; + int getDeviceSubTypeCount(String deviceType) throws SubTypeMgtPluginException; - DeviceSubType getDeviceSubTypeByProvider(String subTypeName, int tenantId, DeviceSubType.DeviceType deviceType) + DeviceSubType getDeviceSubTypeByProvider(String subTypeName, int tenantId, String deviceType) throws SubTypeMgtPluginException; - boolean checkDeviceSubTypeExist(String subTypeId, int tenantId, DeviceSubType.DeviceType deviceType) + boolean checkDeviceSubTypeExist(String subTypeId, int tenantId, String deviceType) throws SubTypeMgtPluginException; } diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/util/DeviceSubTypeMgtUtil.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/util/DeviceSubTypeMgtUtil.java index 8b19b37dcb..4ed402739c 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/util/DeviceSubTypeMgtUtil.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/util/DeviceSubTypeMgtUtil.java @@ -22,7 +22,7 @@ import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubType; import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubTypeCacheKey; public class DeviceSubTypeMgtUtil { - public static String setDeviceSubTypeCacheKey(int tenantId, String subTypeId, DeviceSubType.DeviceType deviceType) { + public static String setDeviceSubTypeCacheKey(int tenantId, String subTypeId, String deviceType) { return tenantId + "|" + subTypeId + "|" + deviceType.toString(); } @@ -30,7 +30,7 @@ public class DeviceSubTypeMgtUtil { String[] keys = key.split("\\|"); int tenantId = Integer.parseInt(keys[0]); String subTypeId = keys[1]; - DeviceSubType.DeviceType deviceType = DeviceSubType.DeviceType.valueOf(keys[2]); + String deviceType = keys[2]; DeviceSubTypeCacheKey deviceSubTypesCacheKey = new DeviceSubTypeCacheKey(); deviceSubTypesCacheKey.setTenantId(tenantId); diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/DAONegativeTest.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/DAONegativeTest.java index 421fb804ae..e0492ace14 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/DAONegativeTest.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/DAONegativeTest.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.subtype.mgt; +import com.fasterxml.jackson.core.JsonProcessingException; import io.entgra.device.mgt.core.subtype.mgt.dao.DeviceSubTypeDAO; import io.entgra.device.mgt.core.subtype.mgt.dao.DeviceSubTypeDAOFactory; import io.entgra.device.mgt.core.subtype.mgt.dao.util.ConnectionManagerUtil; @@ -48,12 +49,12 @@ public class DAONegativeTest extends BaseDeviceSubTypePluginTest { public void testAddDeviceSubType() throws SubTypeMgtDAOException { DeviceSubType deviceSubType = new DeviceSubType() { @Override - public DeviceSubType setDeviceSubType(T objType, String typeDef) { + public DeviceSubType convertToDeviceSubType() { return null; } @Override - public String parseSubTypeToJson(Object objType) { + public String parseSubTypeToJson() throws JsonProcessingException { return null; } }; @@ -85,18 +86,18 @@ public class DAONegativeTest extends BaseDeviceSubTypePluginTest { String subTypeName = "TestSubType"; DeviceSubType deviceSubType = new DeviceSubType() { @Override - public DeviceSubType setDeviceSubType(T objType, String typeDef) { + public DeviceSubType convertToDeviceSubType() { return null; } @Override - public String parseSubTypeToJson(Object objType) { + public String parseSubTypeToJson() throws JsonProcessingException { return null; } }; deviceSubType.setSubTypeId(subTypeId); deviceSubType.setSubTypeName(subTypeName); - deviceSubType.setDeviceType(DeviceSubType.DeviceType.COM); + deviceSubType.setDeviceType("COM"); try { ConnectionManagerUtil.beginDBTransaction(); deviceSubTypeDAO.addDeviceSubType(deviceSubType); @@ -127,17 +128,17 @@ public class DAONegativeTest extends BaseDeviceSubTypePluginTest { String typeDefinition = TestUtils.createNewDeviceSubType(subTypeId); DeviceSubType deviceSubType = new DeviceSubType() { @Override - public DeviceSubType setDeviceSubType(T objType, String typeDef) { + public DeviceSubType convertToDeviceSubType() { return null; } @Override - public String parseSubTypeToJson(Object objType) { + public String parseSubTypeToJson() throws JsonProcessingException { return null; } }; deviceSubType.setSubTypeName(subTypeName); - deviceSubType.setDeviceType(DeviceSubType.DeviceType.COM); + deviceSubType.setDeviceType("COM"); deviceSubType.setTenantId(tenantId); deviceSubType.setTypeDefinition(typeDefinition); try { diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/DAOTest.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/DAOTest.java index f4c51ab6d1..89d5797491 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/DAOTest.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/DAOTest.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.subtype.mgt; +import com.fasterxml.jackson.core.JsonProcessingException; import io.entgra.device.mgt.core.subtype.mgt.dao.DeviceSubTypeDAO; import io.entgra.device.mgt.core.subtype.mgt.dao.DeviceSubTypeDAOFactory; import io.entgra.device.mgt.core.subtype.mgt.dao.util.ConnectionManagerUtil; @@ -50,14 +51,14 @@ public class DAOTest extends BaseDeviceSubTypePluginTest { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); ConnectionManagerUtil.openDBConnection(); DeviceSubType subTypeActual = deviceSubTypeDAO.getDeviceSubType("1", tenantId, - DeviceSubType.DeviceType.COM); + "COM"); ConnectionManagerUtil.closeDBConnection(); Assert.assertNotNull(subTypeActual, "Should not be null"); } @Test(dependsOnMethods = "testAddDeviceSubType") public void testGetAllDeviceSubTypes() throws DBConnectionException, SubTypeMgtDAOException { - DeviceSubType.DeviceType deviceType = DeviceSubType.DeviceType.COM; + String deviceType = "COM"; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); ConnectionManagerUtil.openDBConnection(); List subTypesActual = deviceSubTypeDAO.getAllDeviceSubTypes(tenantId, deviceType); @@ -71,17 +72,17 @@ public class DAOTest extends BaseDeviceSubTypePluginTest { String subTypeId = "1"; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); String subTypeName = "TestSubType"; - DeviceSubType.DeviceType deviceType = DeviceSubType.DeviceType.COM; + String deviceType = "COM"; String typeDefinition = TestUtils.createNewDeviceSubType(subTypeId); DeviceSubType deviceSubType = new DeviceSubType() { @Override - public DeviceSubType setDeviceSubType(T objType, String typeDef) { + public DeviceSubType convertToDeviceSubType() { return null; } @Override - public String parseSubTypeToJson(Object objType) { + public String parseSubTypeToJson() throws JsonProcessingException { return null; } }; @@ -104,7 +105,7 @@ public class DAOTest extends BaseDeviceSubTypePluginTest { public void testUpdateDeviceSubType() throws DBConnectionException, SubTypeMgtDAOException { String subTypeId = "1"; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - DeviceSubType.DeviceType deviceType = DeviceSubType.DeviceType.COM; + String deviceType = "COM"; String subTypeName = "TestSubType"; String subTypeExpected = TestUtils.createUpdateDeviceSubType(subTypeId); @@ -121,7 +122,7 @@ public class DAOTest extends BaseDeviceSubTypePluginTest { @Test(dependsOnMethods = "testAddDeviceSubType") public void testGetDeviceTypeByProvider() throws DBConnectionException, SubTypeMgtDAOException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - DeviceSubType.DeviceType deviceType = DeviceSubType.DeviceType.COM; + String deviceType = "COM"; String subTypeName = "TestSubType"; ConnectionManagerUtil.openDBConnection(); DeviceSubType subTypeActual = deviceSubTypeDAO.getDeviceSubTypeByProvider(subTypeName, tenantId, deviceType); @@ -131,7 +132,7 @@ public class DAOTest extends BaseDeviceSubTypePluginTest { @Test(dependsOnMethods = "testAddDeviceSubType") public void testGetDeviceTypeCount() throws DBConnectionException, SubTypeMgtDAOException { - DeviceSubType.DeviceType deviceType = DeviceSubType.DeviceType.COM; + String deviceType = "COM"; ConnectionManagerUtil.openDBConnection(); int subTypeCount = deviceSubTypeDAO.getDeviceSubTypeCount(deviceType); ConnectionManagerUtil.closeDBConnection(); diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/ServiceNegativeTest.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/ServiceNegativeTest.java index 0c1d15e382..0624cd0afd 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/ServiceNegativeTest.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/ServiceNegativeTest.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.subtype.mgt; +import com.fasterxml.jackson.core.JsonProcessingException; import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubType; import io.entgra.device.mgt.core.subtype.mgt.exception.SubTypeMgtPluginException; import io.entgra.device.mgt.core.subtype.mgt.impl.DeviceSubTypeServiceImpl; @@ -45,12 +46,12 @@ public class ServiceNegativeTest extends BaseDeviceSubTypePluginTest { public void testAddDeviceSubType() throws SubTypeMgtPluginException { DeviceSubType deviceSubType = new DeviceSubType() { @Override - public DeviceSubType setDeviceSubType(T objType, String typeDef) { + public DeviceSubType convertToDeviceSubType() { return null; } @Override - public String parseSubTypeToJson(Object objType) { + public String parseSubTypeToJson() throws JsonProcessingException { return null; } }; @@ -65,16 +66,16 @@ public class ServiceNegativeTest extends BaseDeviceSubTypePluginTest { public void testAddDeviceSubTypes() throws SubTypeMgtPluginException { String subTypeId = "1"; String subTypeName = "TestSubType"; - DeviceSubType.DeviceType deviceType = DeviceSubType.DeviceType.SIM; + String deviceType = "SIM"; DeviceSubType deviceSubType = new DeviceSubType() { @Override - public DeviceSubType setDeviceSubType(T objType, String typeDef) { + public DeviceSubType convertToDeviceSubType() { return null; } @Override - public String parseSubTypeToJson(Object objType) { + public String parseSubTypeToJson() throws JsonProcessingException { return null; } }; @@ -91,7 +92,7 @@ public class ServiceNegativeTest extends BaseDeviceSubTypePluginTest { public void testUpdateDeviceSubTypes() throws SubTypeMgtPluginException { String subTypeId = "15"; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - DeviceSubType.DeviceType deviceType = DeviceSubType.DeviceType.SIM; + String deviceType = "SIM"; String subTypeName = "TestSubType"; String subTypeExpected = TestUtils.createUpdateDeviceSubType(subTypeId); diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/ServiceTest.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/ServiceTest.java index d5e3b96556..8d800a2c69 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/ServiceTest.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/ServiceTest.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.subtype.mgt; +import com.fasterxml.jackson.core.JsonProcessingException; import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubType; import io.entgra.device.mgt.core.subtype.mgt.exception.SubTypeMgtPluginException; import io.entgra.device.mgt.core.subtype.mgt.impl.DeviceSubTypeServiceImpl; @@ -48,13 +49,13 @@ public class ServiceTest extends BaseDeviceSubTypePluginTest { public void testGetDeviceType() throws SubTypeMgtPluginException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); DeviceSubType subTypeActual = deviceSubTypeService.getDeviceSubType("1", tenantId, - DeviceSubType.DeviceType.METER); + "METER"); TestUtils.verifyDeviceSubType(subTypeActual); } @Test(dependsOnMethods = "testAddDeviceSubType") public void testGetAllDeviceTypes() throws SubTypeMgtPluginException { - DeviceSubType.DeviceType deviceType = DeviceSubType.DeviceType.METER; + String deviceType = "METER"; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); List subTypesActual = deviceSubTypeService.getAllDeviceSubTypes(tenantId, deviceType); log.info(deviceType + " sub types count should be " + subTypesActual.size()); @@ -66,17 +67,17 @@ public class ServiceTest extends BaseDeviceSubTypePluginTest { String subTypeId = "1"; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); String subTypeName = "TestSubType"; - DeviceSubType.DeviceType deviceType = DeviceSubType.DeviceType.METER; + String deviceType = "METER"; String typeDefinition = TestUtils.createNewDeviceSubType(subTypeId); DeviceSubType deviceSubType = new DeviceSubType() { @Override - public DeviceSubType setDeviceSubType(T objType, String typeDef) { + public DeviceSubType convertToDeviceSubType() { return null; } @Override - public String parseSubTypeToJson(Object objType) { + public String parseSubTypeToJson() throws JsonProcessingException { return null; } }; @@ -96,7 +97,7 @@ public class ServiceTest extends BaseDeviceSubTypePluginTest { public void testUpdateDeviceSubType() throws SubTypeMgtPluginException { String subTypeId = "1"; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - DeviceSubType.DeviceType deviceType = DeviceSubType.DeviceType.METER; + String deviceType = "METER"; String subTypeName = "TestSubType"; String subTypeExpected = TestUtils.createUpdateDeviceSubType(subTypeId); @@ -111,7 +112,7 @@ public class ServiceTest extends BaseDeviceSubTypePluginTest { @Test(dependsOnMethods = "testAddDeviceSubType") public void testGetDeviceTypeByProvider() throws SubTypeMgtPluginException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - DeviceSubType.DeviceType deviceType = DeviceSubType.DeviceType.METER; + String deviceType = "METER"; String subTypeName = "TestSubType"; DeviceSubType subTypeActual = deviceSubTypeService.getDeviceSubTypeByProvider(subTypeName, tenantId, deviceType); @@ -120,7 +121,7 @@ public class ServiceTest extends BaseDeviceSubTypePluginTest { @Test(dependsOnMethods = "testAddDeviceSubType") public void testGetDeviceTypeCount() throws SubTypeMgtPluginException { - DeviceSubType.DeviceType deviceType = DeviceSubType.DeviceType.METER; + String deviceType = "METER"; int subTypeCount = deviceSubTypeService.getDeviceSubTypeCount(deviceType); log.info(deviceType + " Device subtypes count: " + subTypeCount); } diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/TestUtils.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/TestUtils.java index b5b8011e76..24f70a7afd 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/TestUtils.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/TestUtils.java @@ -47,7 +47,7 @@ public class TestUtils { public static void verifyDeviceSubType(DeviceSubType deviceSubType) { String typeDefExpected = TestUtils.createNewDeviceSubType("1"); Assert.assertEquals(deviceSubType.getSubTypeId(), "1"); - Assert.assertEquals(deviceSubType.getDeviceType(), DeviceSubType.DeviceType.valueOf("METER")); + Assert.assertEquals(deviceSubType.getDeviceType(), "METER"); Assert.assertEquals(deviceSubType.getSubTypeName(), "TestSubType"); Assert.assertEquals(deviceSubType.getTypeDefinition(), typeDefExpected); } @@ -55,7 +55,7 @@ public class TestUtils { public static void verifyDeviceSubTypeDAO(DeviceSubType deviceSubType) { String typeDefExpected = TestUtils.createNewDeviceSubType("1"); Assert.assertEquals(deviceSubType.getSubTypeId(), "1"); - Assert.assertEquals(deviceSubType.getDeviceType(), DeviceSubType.DeviceType.valueOf("COM")); + Assert.assertEquals(deviceSubType.getDeviceType(), "COM"); Assert.assertEquals(deviceSubType.getSubTypeName(), "TestSubType"); Assert.assertEquals(deviceSubType.getTypeDefinition(), typeDefExpected); } @@ -63,7 +63,7 @@ public class TestUtils { public static void verifyUpdatedDeviceSubType(DeviceSubType deviceSubType) { String typeDefExpected = TestUtils.createUpdateDeviceSubType("1"); Assert.assertEquals(deviceSubType.getSubTypeId(), "1"); - Assert.assertEquals(deviceSubType.getDeviceType(), DeviceSubType.DeviceType.valueOf("METER")); + Assert.assertEquals(deviceSubType.getDeviceType(), "METER"); Assert.assertEquals(deviceSubType.getSubTypeName(), "TestSubType"); Assert.assertEquals(deviceSubType.getTypeDefinition(), typeDefExpected); } @@ -71,7 +71,7 @@ public class TestUtils { public static void verifyUpdatedDeviceSubTypeDAO(DeviceSubType deviceSubType) { String typeDefExpected = TestUtils.createUpdateDeviceSubType("1"); Assert.assertEquals(deviceSubType.getSubTypeId(), "1"); - Assert.assertEquals(deviceSubType.getDeviceType(), DeviceSubType.DeviceType.valueOf("COM")); + Assert.assertEquals(deviceSubType.getDeviceType(), "COM"); Assert.assertEquals(deviceSubType.getSubTypeName(), "TestSubType"); Assert.assertEquals(deviceSubType.getTypeDefinition(), typeDefExpected); } diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql index df3277920d..929eb1738a 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql @@ -90,6 +90,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); diff --git a/components/subtype-mgt/pom.xml b/components/subtype-mgt/pom.xml index 6aa8dde6c9..19bacdf54d 100644 --- a/components/subtype-mgt/pom.xml +++ b/components/subtype-mgt/pom.xml @@ -20,7 +20,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/task-mgt/pom.xml b/components/task-mgt/pom.xml index f61896efe1..3fc9ee0375 100755 --- a/components/task-mgt/pom.xml +++ b/components/task-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml index ca65b80686..2c01f24966 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml @@ -20,7 +20,7 @@ task-manager io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml index a1cb463453..ee69355b97 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core task-manager - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/common/TaskManagementDAOFactory.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/common/TaskManagementDAOFactory.java index 11d2ef208e..e332342814 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/common/TaskManagementDAOFactory.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/common/TaskManagementDAOFactory.java @@ -48,6 +48,7 @@ public class TaskManagementDAOFactory { public static DynamicTaskDAO getDynamicTaskDAO() { if (databaseEngine != null) { switch (databaseEngine) { + case TaskMgtConstants.DataBaseTypes.DB_TYPE_MSSQL: case TaskMgtConstants.DataBaseTypes.DB_TYPE_H2: case TaskMgtConstants.DataBaseTypes.DB_TYPE_MYSQL: return new DynamicTaskDAOImpl(); @@ -61,6 +62,7 @@ public class TaskManagementDAOFactory { public static DynamicTaskPropDAO getDynamicTaskPropDAO() { if (databaseEngine != null) { switch (databaseEngine) { + case TaskMgtConstants.DataBaseTypes.DB_TYPE_MSSQL: case TaskMgtConstants.DataBaseTypes.DB_TYPE_H2: case TaskMgtConstants.DataBaseTypes.DB_TYPE_MYSQL: return new DynamicTaskPropDAOImpl(); diff --git a/components/task-mgt/task-manager/pom.xml b/components/task-mgt/task-manager/pom.xml index 2c32e8fa3c..83a3462056 100755 --- a/components/task-mgt/task-manager/pom.xml +++ b/components/task-mgt/task-manager/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core task-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml b/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml index 54475a5583..a2ce469206 100755 --- a/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml +++ b/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core task-watcher - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/task-mgt/task-watcher/pom.xml b/components/task-mgt/task-watcher/pom.xml index 74c6286d30..ebc0ec502c 100755 --- a/components/task-mgt/task-watcher/pom.xml +++ b/components/task-mgt/task-watcher/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core task-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml index 831cc31062..caed6c8c97 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml @@ -20,7 +20,7 @@ tenant-mgt io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml index f33fa5ddb1..7c78186739 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml @@ -20,7 +20,7 @@ tenant-mgt io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/tenant-mgt/pom.xml b/components/tenant-mgt/pom.xml index 48bcd27692..3b1cbd62c7 100644 --- a/components/tenant-mgt/pom.xml +++ b/components/tenant-mgt/pom.xml @@ -20,7 +20,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml index b154858308..d852a1ef09 100644 --- a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml +++ b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core email-sender - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/email-sender/pom.xml b/components/transport-mgt/email-sender/pom.xml index 1a4e74d7b4..c57dd3e521 100644 --- a/components/transport-mgt/email-sender/pom.xml +++ b/components/transport-mgt/email-sender/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core transport-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/pom.xml b/components/transport-mgt/pom.xml index e5c2e9cfbf..00911ea4e6 100644 --- a/components/transport-mgt/pom.xml +++ b/components/transport-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml index f8f4b11059..4e46b89434 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/ConfigurationManagementService.java b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/ConfigurationManagementService.java index 388270fb3b..f13eb9fa13 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/ConfigurationManagementService.java +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/ConfigurationManagementService.java @@ -54,7 +54,7 @@ import javax.ws.rs.core.Response; @Scope( name = "View configurations", description = "", - key = "perm:sms-handler:view-configuration", + key = "conf:sms-handler:view", roles = {"Internal/devicemgt-user"}, permissions = {"/sms-handler/platform-configurations/view"} ) @@ -70,7 +70,7 @@ public interface ConfigurationManagementService { tags = "SMS Configuration Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SMSHandlerConstants.SCOPE, value = "perm:sms-handler:view-configuration") + @ExtensionProperty(name = SMSHandlerConstants.SCOPE, value = "conf:sms-handler:view") }) } ) diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml index 87d0b14aee..465f64fe9e 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml index fbd9cd0162..51e0500a75 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/pom.xml b/components/transport-mgt/sms-handler/pom.xml index adebcc43c4..abbf64776e 100644 --- a/components/transport-mgt/sms-handler/pom.xml +++ b/components/transport-mgt/sms-handler/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core transport-mgt - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml index 3fcfeea3b9..f00ed2b1de 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml @@ -21,7 +21,7 @@ ui-request-interceptor io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT 4.0.0 diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java new file mode 100644 index 0000000000..343a9c620d --- /dev/null +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2018 - 2023, 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 io.entgra.device.mgt.core.ui.request.interceptor; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; +import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; +import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.ContentType; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; + +import javax.servlet.annotation.MultipartConfig; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +@MultipartConfig +@WebServlet("/default-oauth2-credentials") +public class DefaultOauth2TokenHandler extends HttpServlet { + private static final Log log = LogFactory.getLog(DefaultTokenHandler.class); + + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) { + try { + HttpSession httpSession = req.getSession(false); + + if (httpSession != null) { + AuthData authData = (AuthData) httpSession.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY); + if (authData == null) { + HandlerUtil.sendUnAuthorizeResponse(resp); + return; + } + + AuthData defaultAuthData = (AuthData) httpSession + .getAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY); + if (defaultAuthData != null) { + HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultAuthData.getAccessToken())); + return; + } + + String clientId = authData.getClientId(); + String clientSecret = authData.getClientSecret(); + + String queryString = req.getQueryString(); + String scopeString = ""; + if (StringUtils.isNotEmpty(queryString)) { + scopeString = req.getParameter("scopes"); + if (scopeString != null) { + scopeString = "?scopes=" + scopeString; + } + } + + String iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); + String tokenUrl = iotsCoreUrl + "/api/device-mgt/v1.0/devices/" + clientId + + "/" + clientSecret + "/default-token" + scopeString; + + HttpGet defaultTokenRequest = new HttpGet(tokenUrl); + defaultTokenRequest + .setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); + defaultTokenRequest + .setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); + ProxyResponse tokenResultResponse = HandlerUtil.execute(defaultTokenRequest); + + if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { + log.error("Error occurred while invoking the API to get default token data."); + HandlerUtil.handleError(resp, tokenResultResponse); + return; + } + String tokenResult = tokenResultResponse.getData(); + if (tokenResult == null) { + log.error("Invalid default token response is received."); + HandlerUtil.handleError(resp, tokenResultResponse); + return; + } + + JsonParser jsonParser = new JsonParser(); + JsonElement jTokenResult = jsonParser.parse(tokenResult); + if (jTokenResult.isJsonObject()) { + JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); + AuthData newDefaultAuthData = new AuthData(); + newDefaultAuthData.setClientId(clientId); + newDefaultAuthData.setClientSecret(clientSecret); + + String defaultToken = jTokenResultAsJsonObject.get("accessToken").getAsString(); + newDefaultAuthData.setAccessToken(defaultToken); + newDefaultAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refreshToken").getAsString()); + newDefaultAuthData.setScope(jTokenResultAsJsonObject.get("scopes").getAsString()); + httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData); + + HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken)); + } + } else { + HandlerUtil.sendUnAuthorizeResponse(resp); + } + } catch (IOException e) { + log.error("Error occurred when processing GET request to get default token.", e); + } + } + + /** + * Get Success Proxy Response + * @param defaultAccessToken Access token which has default scope + * @return {@link ProxyResponse} + */ + private ProxyResponse constructSuccessProxyResponse (String defaultAccessToken) { + + URIBuilder ub = new URIBuilder(); + ub.setScheme(HandlerConstants.WSS_PROTOCOL); + ub.setHost(System.getProperty(HandlerConstants.IOT_REMOTE_SESSION_HOST_ENV_VAR)); + ub.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_REMOTE_SESSION_HTTPS_PORT_ENV_VAR))); + ub.setPath(HandlerConstants.REMOTE_SESSION_CONTEXT); + + URIBuilder ub2 = new URIBuilder(); + ub2.setScheme(HandlerConstants.WSS_PROTOCOL); + ub2.setHost(System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)); + ub2.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_GATEWAY_WEBSOCKET_WSS_PORT_ENV_VAR))); + + URIBuilder ub3 = new URIBuilder(); + ub3.setScheme(HandlerConstants.WS_PROTOCOL); + ub3.setHost(System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)); + ub3.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_GATEWAY_WEBSOCKET_WS_PORT_ENV_VAR))); + + JsonObject responseJsonObj = new JsonObject(); + responseJsonObj.addProperty("default-access-token", defaultAccessToken); + responseJsonObj.addProperty("remote-session-base-url", ub.toString()); + responseJsonObj.addProperty("secured-websocket-gateway-url", ub2.toString()); + responseJsonObj.addProperty("unsecured-websocket-gateway-url", ub3.toString()); + + Gson gson = new Gson(); + String payload = gson.toJson(responseJsonObj); + + ProxyResponse proxyResponse = new ProxyResponse(); + proxyResponse.setCode(HttpStatus.SC_OK); + proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); + proxyResponse.setData(payload); + return proxyResponse; + } +} diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginCallbackHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginCallbackHandler.java index 9c76af9f39..242ce38962 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginCallbackHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginCallbackHandler.java @@ -28,6 +28,7 @@ import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpHeaders; +import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; @@ -39,6 +40,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.Objects; @MultipartConfig @WebServlet("/ssoLoginCallback") @@ -47,6 +49,7 @@ public class SsoLoginCallbackHandler extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + String state = req.getParameter("state"); String code = req.getParameter("code"); HttpSession session = req.getSession(false); @@ -66,6 +69,11 @@ public class SsoLoginCallbackHandler extends HttpServlet { return; } + if (state == null || !Objects.equals(state, session.getAttribute("state").toString())) { + resp.sendError(HttpStatus.SC_BAD_REQUEST, "MismatchingStateError: CSRF Warning! State not equal in request and response"); + return; + } + String scope = session.getAttribute("scope").toString(); HttpPost tokenEndpoint = new HttpPost(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT); @@ -75,7 +83,7 @@ public class SsoLoginCallbackHandler extends HttpServlet { String loginCallbackUrl = iotsCoreUrl + req.getContextPath() + HandlerConstants.SSO_LOGIN_CALLBACK; StringEntity tokenEPPayload = new StringEntity( - "grant_type=" + HandlerConstants.CODE_GRANT_TYPE + "&code=" + code + "&state=&scope=" + scope + + "grant_type=" + HandlerConstants.CODE_GRANT_TYPE + "&code=" + code + "&scope=" + scope + "&redirect_uri=" + loginCallbackUrl, ContentType.APPLICATION_FORM_URLENCODED); tokenEndpoint.setEntity(tokenEPPayload); diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java index de037d8bc1..ca469ca7e6 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java @@ -82,6 +82,7 @@ public class SsoLoginHandler extends HttpServlet { private LoginCache loginCache; private OAuthApp oAuthApp; private OAuthAppCacheKey oAuthAppCacheKey; + private String state; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { @@ -93,6 +94,7 @@ public class SsoLoginHandler extends HttpServlet { httpSession = req.getSession(true); + state = HandlerUtil.generateStateToken(); initializeAdminCredentials(); baseContextPath = req.getContextPath(); applicationName = baseContextPath.substring(1, baseContextPath.indexOf("-ui-request-handler")); @@ -123,12 +125,11 @@ public class SsoLoginHandler extends HttpServlet { String scopesSsoString = HandlerUtil.getScopeString(scopesSsoJson); String loginCallbackUrl = iotsCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK; persistAuthSessionData(req, oAuthApp.getClientId(), oAuthApp.getClientSecret(), - oAuthApp.getEncodedClientApp(), scopesSsoString); - + oAuthApp.getEncodedClientApp(), scopesSsoString, state); resp.sendRedirect(keyManagerUrl + HandlerConstants.AUTHORIZATION_ENDPOINT + "?response_type=code" + + "&state=" + state + "&client_id=" + clientId + - "&state=" + "&scope=openid " + scopesSsoString + "&redirect_uri=" + loginCallbackUrl); } catch (IOException e) { @@ -182,7 +183,7 @@ public class SsoLoginHandler extends HttpServlet { clientSecret = jClientAppResultAsJsonObject.get("client_secret").getAsString(); encodedClientApp = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes()); String scopesString = HandlerUtil.getScopeString(scopes); - persistAuthSessionData(req, clientId, clientSecret, encodedClientApp, scopesString); + persistAuthSessionData(req, clientId, clientSecret, encodedClientApp, scopesString, state); } // cache the oauth app credentials @@ -283,13 +284,14 @@ public class SsoLoginHandler extends HttpServlet { * @param scopes - User scopes */ private void persistAuthSessionData(HttpServletRequest req, String clientId, String clientSecret, - String encodedClientApp, String scopes) { + String encodedClientApp, String scopes, String state) { httpSession = req.getSession(false); httpSession.setAttribute("clientId", clientId); httpSession.setAttribute("clientSecret", clientSecret); httpSession.setAttribute("encodedClientApp", encodedClientApp); httpSession.setAttribute("scope", scopes); httpSession.setAttribute("redirectUrl", req.getParameter("redirect")); + httpSession.setAttribute("state", state); httpSession.setMaxInactiveInterval(sessionTimeOut); } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java index cd2f1f8fe0..0fca3811c0 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java @@ -23,9 +23,7 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.cache.LoginCache; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; @@ -34,11 +32,7 @@ import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.Consts; -import org.apache.http.Header; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; +import org.apache.http.*; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; @@ -60,7 +54,9 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import org.wso2.carbon.context.PrivilegedCarbonContext; +import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; import org.xml.sax.SAXException; import javax.servlet.http.HttpServletRequest; @@ -69,7 +65,14 @@ import javax.servlet.http.HttpSession; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.math.BigInteger; +import java.security.SecureRandom; import java.util.Enumeration; import java.util.List; @@ -762,4 +765,8 @@ public class HandlerUtil { } return otpManagementService; } + + public static String generateStateToken() { + return new BigInteger(130, new SecureRandom()).toString(32); + } } diff --git a/components/ui-request-interceptor/pom.xml b/components/ui-request-interceptor/pom.xml index 10874166b4..5a5ef82b68 100644 --- a/components/ui-request-interceptor/pom.xml +++ b/components/ui-request-interceptor/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml index 4ed249d6bc..e697ebe9b6 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core webapp-authenticator-framework - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java index 696bb788ae..15a6ce3de3 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java @@ -79,11 +79,6 @@ public class PermissionAuthorizer { matchingResources.add(new MatchingResource(permission.getUrlPattern().replace(context, ""), permission.getPath())); } } - //TODO :: Temporary fix for windows bst api url mismatch error - else if ("/api/device-mgt/windows/v1.0/bst/authentication".equals(permission.getUrl())) { - requiredPermission = "/permission/admin/device-mgt/devices/enroll/windows"; - break; - } } if (requiredPermission == null) { diff --git a/components/webapp-authenticator-framework/pom.xml b/components/webapp-authenticator-framework/pom.xml index 68213a2bb0..9e81164345 100644 --- a/components/webapp-authenticator-framework/pom.xml +++ b/components/webapp-authenticator-framework/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.feature/pom.xml b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.feature/pom.xml index 9a7dc8a557..d5856bf8a4 100644 --- a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.feature/pom.xml +++ b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml index 6319131fb6..434a554741 100644 --- a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml +++ b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/analytics-mgt/grafana-mgt/pom.xml b/features/analytics-mgt/grafana-mgt/pom.xml index 79c9fb75f9..907c8e8c75 100644 --- a/features/analytics-mgt/grafana-mgt/pom.xml +++ b/features/analytics-mgt/grafana-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core analytics-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/analytics-mgt/pom.xml b/features/analytics-mgt/pom.xml index 9f1b1ba316..f7eaeaeef9 100644 --- a/features/analytics-mgt/pom.xml +++ b/features/analytics-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml index ae7b4d9109..14ba988b93 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml @@ -20,7 +20,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml index 86a4d6f913..1b5def60d3 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api.feature/pom.xml index 9e6d5d780b..9ac48cd779 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml index 8975e00d36..b64fc605b0 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml index c88e427fd5..c324ec0f69 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/pom.xml b/features/apimgt-extensions/pom.xml index 5a0d340fe4..6185c6e717 100644 --- a/features/apimgt-extensions/pom.xml +++ b/features/apimgt-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml index d591a3ce27..2f97648a4f 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core application-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml index 8913afa2b9..bb1e6144ac 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml @@ -171,6 +171,7 @@ Video Players & Editors Weather GooglePlaySyncedApp + AppleStoreSyncedApp diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 index cbd8c6f0c9..bc4d34b048 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 @@ -202,6 +202,7 @@ Video Players & Editors Weather GooglePlaySyncedApp + AppleStoreSyncedApp {% if application_mgt_conf.app_categories is defined %} {%- for app_category in application_mgt_conf.app_categories -%} {{app_category}} diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql index 961e855337..67694fa26c 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql @@ -326,3 +326,59 @@ CREATE TABLE IF NOT EXISTS AP_APP_FAVOURITES( FOREIGN KEY (AP_APP_ID) REFERENCES AP_APP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); + +-- ----------------------------------------------------- +-- Table AP_VPP_USER +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_VPP_USER ( + ID INT NOT NULL AUTO_INCREMENT, + CLIENT_USER_ID VARCHAR(255) NULL, + DM_USERNAME VARCHAR(255) NOT NULL, + TENANT_ID INT NOT NULL, + EMAIL VARCHAR(255) NULL, + INVITE_CODE VARCHAR(255) NULL, + STATUS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + MANAGED_ID VARCHAR(255) NULL, + TEMP_PASSWORD VARCHAR(255) NULL, + PRIMARY KEY (ID) +); + +-- ----------------------------------------------------- +-- Table AP_ASSETS +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_ASSETS ( + ID INT NOT NULL AUTO_INCREMENT, + APP_ID INT NULL, + TENANT_ID INT NOT NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + ADAM_ID VARCHAR(255) NULL, + ASSIGNED_COUNT VARCHAR(255) NULL, + DEVICE_ASSIGNABLE VARCHAR(255) NULL, + PRICING_PARAMS VARCHAR(255) NULL, + PRODUCT_TYPE VARCHAR(255) NULL, + RETIRED_COUNT VARCHAR(255) NULL, + REVOCABLE VARCHAR(255) NULL, + SUPPORTED_PLATFORMS VARCHAR(255) NULL, + PRIMARY KEY (ID) +); + +-- ----------------------------------------------------- +-- Table AP_VPP_ASSOCIATION +-- ----------------------------------------------------- + +CREATE TABLE IF NOT EXISTS AP_VPP_ASSOCIATION ( + ID INT NOT NULL AUTO_INCREMENT, + ASSET_ID INT, + USER_ID INT, + TENANT_ID INT NOT NULL, + ASSOCIATION_TYPE VARCHAR(255) NOT NULL, + PRICING_PARAMS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + PRIMARY KEY (ID), + CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE ON UPDATE CASCADE +); diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql index 9b2e89b3f7..0c95c74ddd 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql @@ -342,3 +342,61 @@ CREATE TABLE AP_APP_FAVOURITES( FOREIGN KEY (AP_APP_ID) REFERENCES AP_APP (ID) ); + +-- ----------------------------------------------------- +-- Table AP_VPP_USER +-- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'AP_VPP_USER') AND type in (N'U')) +CREATE TABLE AP_VPP_USER ( + ID INT NOT NULL IDENTITY(1,1), + CLIENT_USER_ID VARCHAR(255) NULL, + DM_USERNAME VARCHAR(255) NOT NULL, + TENANT_ID INT NOT NULL, + EMAIL VARCHAR(255) NULL, + INVITE_CODE VARCHAR(255) NULL, + STATUS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + MANAGED_ID VARCHAR(255) NULL, + TEMP_PASSWORD VARCHAR(255) NULL, + PRIMARY KEY (ID) +); + +-- ----------------------------------------------------- +-- Table AP_ASSETS +-- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'AP_ASSETS') AND type in (N'U')) +CREATE TABLE AP_ASSETS ( + ID INT NOT NULL IDENTITY(1,1), + APP_ID INT NULL, + TENANT_ID INT NOT NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + ADAM_ID VARCHAR(255) NULL, + ASSIGNED_COUNT VARCHAR(255) NULL, + DEVICE_ASSIGNABLE VARCHAR(255) NULL, + PRICING_PARAMS VARCHAR(255) NULL, + PRODUCT_TYPE VARCHAR(255) NULL, + RETIRED_COUNT VARCHAR(255) NULL, + REVOCABLE VARCHAR(255) NULL, + SUPPORTED_PLATFORMS VARCHAR(255) NULL, + PRIMARY KEY (ID) +); + +-- ----------------------------------------------------- +-- Table AP_VPP_ASSOCIATION +-- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'AP_VPP_ASSOCIATION') AND type in (N'U')) +CREATE TABLE AP_VPP_ASSOCIATION ( + ID INT NOT NULL IDENTITY(1,1), + ASSET_ID INT, + USER_ID INT, + TENANT_ID INT NOT NULL, + ASSOCIATION_TYPE VARCHAR(255) NOT NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + PRICING_PARAMS VARCHAR(255) NULL, + PRIMARY KEY (ID), + CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE ON UPDATE CASCADE +); diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql index 54ba58a9fe..448c249b85 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql @@ -272,4 +272,60 @@ CREATE TABLE IF NOT EXISTS AP_APP_FAVOURITES( TENANT_ID INTEGER NOT NULL, PRIMARY KEY(ID), CONSTRAINT AP_APP_FAVOURITES_AP_APP_ID_fk FOREIGN KEY (AP_APP_ID) REFERENCES AP_APP (ID) +); + +-- ----------------------------------------------------- +-- Table AP_VPP_USER +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_VPP_USER ( + ID INT NOT NULL AUTO_INCREMENT, + CLIENT_USER_ID VARCHAR(255) NULL, + DM_USERNAME VARCHAR(255) NOT NULL, + TENANT_ID INT NOT NULL, + EMAIL VARCHAR(255) NULL, + INVITE_CODE VARCHAR(255) NULL, + STATUS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + MANAGED_ID VARCHAR(255) NULL, + TEMP_PASSWORD VARCHAR(255) NULL, + PRIMARY KEY (ID) +); + +-- ----------------------------------------------------- +-- Table AP_ASSETS +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_ASSETS ( + ID INT NOT NULL AUTO_INCREMENT, + APP_ID INT NULL, + TENANT_ID INT NOT NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + ADAM_ID VARCHAR(255) NULL, + ASSIGNED_COUNT VARCHAR(255) NULL, + DEVICE_ASSIGNABLE VARCHAR(255) NULL, + PRICING_PARAMS VARCHAR(255) NULL, + PRODUCT_TYPE VARCHAR(255) NULL, + RETIRED_COUNT VARCHAR(255) NULL, + REVOCABLE VARCHAR(255) NULL, + SUPPORTED_PLATFORMS VARCHAR(255) NULL, + PRIMARY KEY (ID) +); + +-- ----------------------------------------------------- +-- Table AP_VPP_ASSOCIATION +-- ----------------------------------------------------- + +CREATE TABLE IF NOT EXISTS AP_VPP_ASSOCIATION ( + ID INT NOT NULL AUTO_INCREMENT, + ASSET_ID INT, + USER_ID INT, + TENANT_ID INT NOT NULL, + ASSOCIATION_TYPE VARCHAR(255) NOT NULL, + PRICING_PARAMS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + PRIMARY KEY (ID), + CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE ON UPDATE CASCADE ); \ No newline at end of file diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql index 79c5b1345f..66e518a59e 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql @@ -420,3 +420,52 @@ CREATE TABLE IF NOT EXISTS AP_APP_FAVOURITES( REFERENCES AP_APP (ID) ) / + +CREATE TABLE AP_VPP_USER ( + ID number GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL, + CLIENT_USER_ID VARCHAR2(255) NULL, + DM_USERNAME VARCHAR2(255) NOT NULL, + TENANT_ID INT NOT NULL, + EMAIL VARCHAR2(255) NULL, + INVITE_CODE VARCHAR2(255) NULL, + STATUS VARCHAR2(255) NULL, + CREATED_TIME NUMBER(19) NULL, + LAST_UPDATED_TIME NUMBER(19) NULL, + MANAGED_ID VARCHAR2(255) NULL, + TEMP_PASSWORD VARCHAR2(255) NULL, + PRIMARY KEY (ID) +) +/ + +CREATE TABLE AP_ASSETS ( + ID number GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL, + APP_ID INT NULL, + TENANT_ID INT NOT NULL, + CREATED_TIME NUMBER(19) NULL, + LAST_UPDATED_TIME NUMBER(19) NULL, + ADAM_ID VARCHAR2(255) NULL, + ASSIGNED_COUNT VARCHAR2(255) NULL, + DEVICE_ASSIGNABLE VARCHAR2(255) NULL, + PRICING_PARAMS VARCHAR2(255) NULL, + PRODUCT_TYPE VARCHAR2(255) NULL, + RETIRED_COUNT VARCHAR2(255) NULL, + REVOCABLE VARCHAR2(255) NULL, + SUPPORTED_PLATFORMS VARCHAR2(255) NULL, + PRIMARY KEY (ID) +) +/ + +CREATE TABLE AP_VPP_ASSOCIATION ( + ID number GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL, + ASSET_ID INT, + USER_ID INT, + TENANT_ID INT NOT NULL, + ASSOCIATION_TYPE VARCHAR2(255) NOT NULL, + PRICING_PARAMS VARCHAR2(255) NULL, + CREATED_TIME NUMBER(19) NULL, + LAST_UPDATED_TIME NUMBER(19) NULL, + PRIMARY KEY (ID), + CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE, + CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE +) +/ diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql index e8e1dbb225..7f51f6e935 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql @@ -352,3 +352,58 @@ CREATE TABLE IF NOT EXISTS AP_APP_FAVOURITES( FOREIGN KEY (AP_APP_ID) REFERENCES AP_APP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); + +-- ----------------------------------------------------- +-- Table AP_VPP_USER +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_VPP_USER ( + ID INTEGER NOT NULL DEFAULT NEXTVAL('AP_VPP_USER_seq'), + CLIENT_USER_ID VARCHAR(255) NULL, + DM_USERNAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL VARCHAR(255) NULL, + INVITE_CODE VARCHAR(255) NULL, + STATUS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + MANAGED_ID VARCHAR(255) NULL, + TEMP_PASSWORD VARCHAR(255) NULL, + PRIMARY KEY (ID) + ); + +-- ----------------------------------------------------- +-- Table AP_ASSETS +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_ASSETS ( + ID INTEGER NOT NULL DEFAULT NEXTVAL('AP_ASSETS_seq'), + APP_ID INTEGER NULL, + TENANT_ID INTEGER NOT NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + ADAM_ID VARCHAR(255) NULL, + ASSIGNED_COUNT VARCHAR(255) NULL, + DEVICE_ASSIGNABLE VARCHAR(255) NULL, + PRICING_PARAMS VARCHAR(255) NULL, + PRODUCT_TYPE VARCHAR(255) NULL, + RETIRED_COUNT VARCHAR(255) NULL, + REVOCABLE VARCHAR(255) NULL, + SUPPORTED_PLATFORMS VARCHAR(255) NULL, + PRIMARY KEY (ID) + ); + +-- ----------------------------------------------------- +-- Table AP_VPP_ASSOCIATION +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_VPP_ASSOCIATION ( + ID INTEGER NOT NULL DEFAULT NEXTVAL('AP_VPP_ASSOCIATION_seq'), + ASSET_ID INTEGER, + USER_ID INTEGER, + TENANT_ID INTEGER NOT NULL, + ASSOCIATION_TYPE VARCHAR(255) NOT NULL, + PRICING_PARAMS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + PRIMARY KEY (ID), + CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE ON UPDATE CASCADE + ); diff --git a/features/application-mgt/pom.xml b/features/application-mgt/pom.xml index 21cfa686de..b64abe8da0 100644 --- a/features/application-mgt/pom.xml +++ b/features/application-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml index 8e3ce588d7..8a657b1c99 100644 --- a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml +++ b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core certificate-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml index 5c0496a632..62f45f14ec 100644 --- a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml +++ b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core certificate-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml index 7133dbe33a..3b0db3bc67 100644 --- a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml +++ b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core certificate-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/pom.xml b/features/certificate-mgt/pom.xml index 8838cd5e1d..2569c1e359 100644 --- a/features/certificate-mgt/pom.xml +++ b/features/certificate-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml index f9a794fe45..ddaee9f6de 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml index a950905f9b..e357207773 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml index 04428e901d..217ec3584d 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml index 7abd0965b5..edbc130ef2 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml index ad3cc61fcf..f0ccefe68d 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml index 50ef3918b8..e629f48373 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml index e3d10ade01..81199586f5 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml index 50d7797a53..94a86548d7 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/pom.xml b/features/device-mgt-extensions/pom.xml index 7b36adfb3a..5b1f2d321a 100644 --- a/features/device-mgt-extensions/pom.xml +++ b/features/device-mgt-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml index 44bbfca4c6..fe04b7692c 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml index 6475c92638..74e160d442 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml index c40cefc413..97c4ca9a3e 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml @@ -211,5 +211,87 @@ false Replace with mail + + + /permission/admin/device-mgt/devices/any-device/permitted-actions-under-owning-device + + Apply permitted actions on any device + dm:devices:any:permitted + Internal/devicemgt-user + + + + /permission/admin/device-mgt/device/api/subscribe + + Subscribe APIs + dm:device:api:subscribe + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/approve + + Approve Applications + am:admin:lc:app:approve + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/create + + Create Applications + am:admin:lc:app:create + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/reject + + Reject Applications + am:admin:lc:app:reject + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/block + + Block Applications + am:admin:lc:app:block + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/review + + Review Applications + am:admin:lc:app:review + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/retire + + Retire Applications + am:admin:lc:app:retire + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/deprecate + + Deprecate Application + am:admin:lc:app:deprecate + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/publish + + Publish Applications + am:admin:lc:app:publish + Internal/devicemgt-user + + + diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml index b16935562d..aada3c5255 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml @@ -40,6 +40,128 @@ false true + + + name + label_device + default + + + type + label_type + default + + + owner + label_owner + default + + + serial + label_serialNumber + default + + + ownership + label_ownership + default + + + status + label_status + default + + + dateOfLastUpdate + label_last_updated + default + + + actions + label_actions + default + + + batteryLevel + label_battery_leve + deviceInfo + + + deviceModel + label_deviceModel + deviceInfo + + + osVersion + label_os_version + deviceInfo + + + vendor + label_vendor + deviceInfo + + + availableRAMMemory + label_available_ram_memory + deviceInfo + + + connectionType + label_connection_type + deviceInfo + + + cpuUsage + label_cpu_usage + deviceInfo + + + externalAvailableMemory + label_external_available_memory + deviceInfo + + + externalTotalMemory + label_external_tot_memory + deviceInfo + + + internalAvailableMemory + label_internal_available_memory + deviceInfo + + + internalTotalMemory + label_internal_tot_memory + deviceInfo + + + osBuildDate + label_os_build_date + deviceInfo + + + pluggedIn + label_plugged_in + deviceInfo + + + ssid + label_ssid + deviceInfo + + + totalRAMMemory + label_tot_ram_memory + deviceInfo + + + updatedTime + label_updated_time + deviceInfo + + analytics_management @@ -51,195 +173,185 @@ true - perm:grafana:api:view - perm:app:review:view - perm:app:review:update - perm:app:publisher:service-provider:view - perm:app:publisher:service-provider:create - perm:app:publisher:service-provider:attach - perm:app:publisher:service-provider:detach - perm:app:publisher:service-provider:connect - perm:app:publisher:view - perm:app:publisher:update - perm:app:store:view - perm:app:store:modify - perm:app:subscription:install - perm:app:subscription:uninstall - perm:admin:app:review:update - perm:admin:app:review:view - perm:admin:app:publisher:update - perm:admin:app:review:update - perm:admin:app:subscription:view - perm:admin:app:subscription:modify - perm:device-types:types - perm:enterprise:modify - perm:enterprise:view - perm:android-work:customer - perm:android-work:admin - perm:application-command:modify - perm:sign-csr - perm:admin:devices:view - perm:admin:topics:view - perm:roles:add - perm:roles:add-users - perm:roles:update - perm:roles:permissions - perm:roles:details - perm:roles:view - perm:roles:create-combined-role - perm:roles:delete - perm:dashboard:vulnerabilities - perm:dashboard:non-compliant-count - perm:dashboard:non-compliant - perm:dashboard:by-groups - perm:dashboard:device-counts - perm:dashboard:feature-non-compliant - perm:dashboard:count-overview - perm:dashboard:filtered-count - perm:dashboard:details - perm:get-activity - perm:devices:delete - perm:devices:applications - perm:devices:effective-policy - perm:devices:compliance-data - perm:devices:features - perm:devices:operations - perm:devices:search - perm:devices:details - perm:devices:update - perm:devices:view - perm:devices:enrollment-guide:view - perm:view-configuration - perm:manage-configuration - perm:policies:remove - perm:policies:priorities - perm:policies:deactivate - perm:policies:get-policy-details - perm:policies:manage - perm:policies:activate - perm:policies:update - perm:policies:changes - perm:policies:get-details - perm:users:add - perm:users:details - perm:users:count - perm:users:delete - perm:users:roles - perm:users:user-details - perm:users:credentials - perm:users:search - perm:users:is-exist - perm:users:update - perm:users:send-invitation - perm:admin-users:view - perm:admin:devices:update-enrollment - perm:groups:devices - perm:groups:update - perm:groups:add - perm:groups:device - perm:groups:devices-count - perm:groups:devices-types - perm:groups:remove - perm:groups:groups - perm:groups:groups-view - perm:groups:share - perm:groups:count - perm:groups:roles - perm:groups:devices-remove - perm:groups:devices-add - perm:groups:assign - perm:device-types:configs - perm:device-types:features - perm:device-types:types - perm:applications:install - perm:applications:uninstall - perm:admin-groups:count - perm:admin-groups:view - perm:admin-groups:add - perm:notifications:mark-checked - perm:notifications:view - perm:admin:certificates:delete - perm:admin:certificates:details - perm:admin:certificates:view - perm:admin:certificates:add - perm:admin:certificates:verify - perm:admin - perm:devicetype:deployment - perm:device-types:events - perm:device-types:events:view - perm:admin:device-type - perm:admin:device-type:view - perm:admin:device-type:configs - perm:device:enroll - perm:geo-service:analytics-view - perm:geo-service:alerts-manage - appm:read - perm:devices:permanent-delete - perm:android:manage-configuration - perm:android:view-configuration - perm:user:permission-view - perm:ios:view-configuration - perm:ios:manage-configuration - perm:ios:dep-view - perm:ios:dep-add - perm:windows:view-configuration - perm:windows:manage-configuration - perm:android:lock-devices - perm:android:unlock-devices - perm:android:location - perm:android:clear-password - perm:android:control-camera - perm:android:enterprise-wipe - perm:android:wipe - perm:android:ring - perm:android:applications - perm:android:reboot - perm:android:change-LockTask - perm:android:mute - perm:android:configure-display-message - perm:android:send-app-restrictions - perm:android:file-transfer - perm:android:set-webclip - perm:android:set-password-policy - perm:android:change-lock-code - perm:android:upgrade-firmware - perm:android:send-notification - perm:geo-service:geo-fence - perm:whitelabel:view - perm:whitelabel:update - perm:metadata:view - perm:metadata:create - perm:metadata:update - perm:android:google-account - perm:android:update-default-sim - perm:android:google-account - perm:android:info - perm:windows:lock-devices - perm:windows:disenroll - perm:windows:wipe - perm:windows:ring - perm:windows:lock-reset - perm:windows:reboot - perm:windows:location - perm:admin:tenant:view - perm:admin:metadata:view - perm:admin:usage:view - perm:android:clear-application - perm:android:suspend-package - perm:android:alternate-install - perm:ios:lock - perm:ios:location - perm:ios:ring - perm:ios:clear-passcode - perm:ios:enterprise-wipe - perm:ios:notification - perm:ios:wipe-data - perm:ios:boolean-setting - perm:ios:wallpaper - perm:ios:app-attributes - perm:ios:app-configurations - perm:mac-os:restart - perm:mac-os:shut-down + grafana:api:view + am:store:app:review:view + am:store:app:review:update + am:pub:sp:app:view + am:pub:sp:create + am:pub:sp:attach + am:pub:sp:detach + am:pub:sp:connect + am:pub:app:view + am:pub:app:update + am:store:app:view + am:store:app:modify + am:store:app:sub:install + am:store:app:sub:uninstall + am:admin:pub:app:review:view + am:admin:pub:app:update + am:admin:store:app:review:update + am:admin:store:app:sub:view + am:admin:store:app:sub:modify + dm:device-type:view + and:enterprise:modify + and:enterprise:view + dm:sign-csr + dm:admin:devices:view + rm:roles:add + rm:users:add + rm:roles:update + rm:roles:permissions:view + rm:roles:details:view + rm:roles:view + rm:roles:combined:add + rm:roles:delete + dm:activity:get + dm:devices:delete + dm:devices:app:view + dm:devices:policy:view + dm:devices:compliance:view + dm:devices:features:view + dm:devices:ops:view + dm:devices:search + dm:devices:details + dm:devices:update + dm:devices:view + dm:devices:enrollment-guide:view + dm:conf:view + dm:conf:manage + pm:policies:remove + pm:policies:priorities:update + pm:policies:deactivate + pm:policies:details:view + pm:policies:add + pm:policies:activate + pm:policies:update + pm:policies:change + dm:policies:view + um:users:add + um:users:details:view + um:users:count + um:users:delete + um:roles:view + um:users:user-details:view + um:users:cred:change + um:users:search + um:users:is-exist + um:users:update + um:users:invite + um:admin:users:view + dm:admin:enrollment:update + gm:devices:view + gm:groups:update + gm:groups:add + gm:groups:device:view + gm:devices:count + gm:devices-types:view + gm:groups:remove + gm:groups:view + gm:groups:groups-view + gm:roles:share + gm:groups:count + gm:roles:view + gm:devices:remove + gm:devices:add + gm:devices:assign + dm:device-type:conf:view + dm:device-type:features:view + dm:device-type:view + am:admin:app:install + am:admin:app:uninstall + gm:admin:groups:count + gm:admin:groups:view + gm:admin:groups:add + dm:notif:mark-checked + dm:notifications:view + cm:cert:delete + cm:cert:details:get + cm:cert:view + cm:cert:add + cm:cert:verify + dm:admin + dm:device-type:deploy + dm:device-type:event:modify + dm:device-type:event:view + dm:admin:device-type:modify + dm:admin:device-type:view + dm:admin:device-type:conf:add + dm:device:enroll + dm:geo:an:view + dm:geo:alerts:manage + dm:admin:devices:permanent-delete + and:conf:manage + and:conf:view + um:users:permission:view + ios:conf:view + ios:conf:manage + ios:dep:view + ios:dep:add + win:conf:view + win:conf:manage + and:ops:lock-devices + and:ops:unlock-devices + and:ops:location + and:ops:clear-password + and:ops:control-camera + and:ops:enterprise-wipe + and:ops:wipe + and:ops:ring + and:ops:app-list + and:ops:reboot + and:ops:change-LockTask + and:ops:mute + and:ops:conf-display-msg + and:ops:send-app-restrictions + and:ops:file-transfer + and:ops:set-webclip + and:ops:password-policy + and:ops:change-lock-code + and:ops:upgrade-firmware + and:ops:send-notif + dm:geo:geo-fence:manage + dm:whitelable:view + dm:whitelable:update + dm:metadata:view + dm:metadata:create + dm:metadata:update + and:ops:add-google-acc + and:ops:update-default-sim + and:ops:add-google-acc + and:ops:device-info + win:ops:lock-devices + win:devices:enroll + win:ops:disenroll + win:ops:wipe + win:ops:ring + win:ops:lock-reset + win:ops:reboot + win:ops:location + admin:tenant:view + dm:admin:devices:usage:view + and:ops:clear-app + and:ops:suspend-package + and:ops:alternate-install + ios:ops:lock + ios:ops:location + ios:ops:ring + ios:ops:clear-passcode + ios:ops:enterprise-wipe + ios:ops:notif + ios:ops:wipe + ios:ops:boolean-setting + ios:ops:wallpaper + ios:ops:app-attributes + ios:ops:app-conf + mac:ops:restart + mac:ops:shutdown + am:store:vpp:user:modify + am:store:vpp:user:view + am:store:vpp:assets:modify + am:store:vpp:assets:view + and:devices:enroll device-mgt diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 index 2152b1814f..bd6961e7d8 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 @@ -353,7 +353,7 @@ - + {% if device_mgt_conf.operation_timeout_conf is defined %} @@ -383,5 +383,87 @@ Replace with mail {% endif %} + + + /permission/admin/device-mgt/devices/any-device/permitted-actions-under-owning-device + + Apply permitted actions on any device + dm:devices:any:permitted + Internal/devicemgt-user + + + + /permission/admin/device-mgt/device/api/subscribe + + Subscribe APIs + dm:device:api:subscribe + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/approve + + Approve Applications + am:admin:lc:app:approve + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/create + + Create Applications + am:admin:lc:app:create + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/reject + + Reject Applications + am:admin:lc:app:reject + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/block + + Block Applications + am:admin:lc:app:block + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/review + + Review Applications + am:admin:lc:app:review + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/retire + + Retire Applications + am:admin:lc:app:retire + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/deprecate + + Deprecate Application + am:admin:lc:app:deprecate + Internal/devicemgt-user + + + + /permission/admin/app-mgt/life-cycle/application/publish + + Publish Applications + am:admin:lc:app:publish + Internal/devicemgt-user + + + diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql index f2adc989b1..b0e746297c 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -92,6 +92,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TENANT_ID INT NOT NULL, PRIMARY KEY (ID) ); @@ -593,7 +594,7 @@ CREATE TABLE IF NOT EXISTS DM_METADATA ( METADATA_ID INT AUTO_INCREMENT NOT NULL, DATA_TYPE VARCHAR(16) NOT NULL, METADATA_KEY VARCHAR(128) NOT NULL, - METADATA_VALUE VARCHAR(8000) NOT NULL, + METADATA_VALUE TEXT NOT NULL, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (METADATA_ID), CONSTRAINT METADATA_KEY_TENANT_ID UNIQUE (METADATA_KEY, TENANT_ID) @@ -608,7 +609,7 @@ CREATE TABLE IF NOT EXISTS DM_OTP_DATA ( USERNAME VARCHAR(500) DEFAULT NOT NULL, EMAIL VARCHAR(100) NOT NULL, EMAIL_TYPE VARCHAR(20) NOT NULL, - META_INFO VARCHAR(20000) NOT NULL, + META_INFO VARCHAR(20000) NULL, CREATED_AT TIMESTAMP NOT NULL, EXPIRY_TIME INT NOT NULL DEFAULT 3600, IS_EXPIRED BOOLEAN DEFAULT false, @@ -803,8 +804,8 @@ CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( CREATE TABLE IF NOT EXISTS DM_DEVICE_SUB_TYPE ( TENANT_ID INT DEFAULT 0, SUB_TYPE_ID VARCHAR(45) NOT NULL, - DEVICE_TYPE VARCHAR(25) NOT NULL, - SUB_TYPE_NAME VARCHAR(45) NOT NULL, + DEVICE_TYPE VARCHAR(45) NOT NULL, + SUB_TYPE_NAME VARCHAR(100) NOT NULL, TYPE_DEFINITION TEXT NOT NULL, PRIMARY KEY (SUB_TYPE_ID,DEVICE_TYPE) ); diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql index 34ff7ef1a7..7090ca20ff 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -126,9 +126,17 @@ CREATE TABLE DM_OPERATION ( INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS VARBINARY(MAX) DEFAULT NULL, ENABLED BIT NOT NULL DEFAULT 0, + TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); +IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_OP_CREATED' AND OBJECT_ID = OBJECT_ID('DM_OPERATION')) +CREATE INDEX IDX_OP_CREATED ON DM_OPERATION(CREATED_TIMESTAMP); +IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_OP_CODE' AND OBJECT_ID = OBJECT_ID('DM_OPERATION')) +CREATE INDEX IDX_OP_CODE ON DM_OPERATION(OPERATION_CODE); +IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_OP_INITIATED_BY' AND OBJECT_ID = OBJECT_ID('DM_OPERATION')) +CREATE INDEX IDX_OP_INITIATED_BY ON DM_OPERATION(INITIATED_BY); + IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_ENROLMENT]') AND TYPE IN (N'U')) CREATE TABLE DM_ENROLMENT ( ID INTEGER IDENTITY(1,1) NOT NULL, @@ -196,6 +204,8 @@ IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_EN_OP_MAPPING_OP_ID' CREATE INDEX IDX_EN_OP_MAPPING_OP_ID ON DM_ENROLMENT_OP_MAPPING(OPERATION_ID); IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_EN_OP_MAPPING_EN_ID_STATUS' AND OBJECT_ID = OBJECT_ID('DM_ENROLMENT_OP_MAPPING')) CREATE INDEX IDX_EN_OP_MAPPING_EN_ID_STATUS ON DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID, STATUS); +IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_ENROLMENT_OP_MAPPING_CREATED_TS' AND OBJECT_ID = OBJECT_ID('DM_ENROLMENT_OP_MAPPING')) +CREATE INDEX IDX_ENROLMENT_OP_MAPPING_CREATED_TS ON DM_ENROLMENT_OP_MAPPING(CREATED_TIMESTAMP); IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_DEVICE_OPERATION_RESPONSE]') AND TYPE IN (N'U')) CREATE TABLE DM_DEVICE_OPERATION_RESPONSE ( @@ -464,7 +474,7 @@ CREATE INDEX IDX_DM_APPLICATION ON DM_APPLICATION(DEVICE_ID, ENROLMENT_ID, TENAN -- POLICY RELATED TABLES FINISHED -- -IF NOT EXISTS (SELECT * SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_APP_ICONS]') AND TYPE IN (N'U')) +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_APP_ICONS]') AND TYPE IN (N'U')) CREATE TABLE DM_APP_ICONS ( ID INTEGER IDENTITY(1,1) NOT NULL, ICON_PATH VARCHAR(150) DEFAULT NULL, @@ -654,7 +664,7 @@ CREATE TABLE DM_METADATA ( METADATA_ID INTEGER IDENTITY(1,1) NOT NULL, DATA_TYPE VARCHAR(16) NOT NULL, METADATA_KEY VARCHAR(128) NOT NULL, - METADATA_VALUE VARCHAR(8000) NOT NULL, + METADATA_VALUE TEXT NOT NULL, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (METADATA_ID), CONSTRAINT METADATA_KEY_TENANT_ID UNIQUE(METADATA_KEY, TENANT_ID) @@ -662,6 +672,7 @@ CREATE TABLE DM_METADATA ( -- END OF METADATA TABLE -- -- DM_OTP_DATA TABLE -- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_OTP_DATA]') AND TYPE IN (N'U')) CREATE TABLE DM_OTP_DATA ( ID INT IDENTITY NOT NULL, OTP_TOKEN VARCHAR(100) NOT NULL, @@ -669,7 +680,7 @@ CREATE TABLE DM_OTP_DATA ( USERNAME VARCHAR(500) NOT NULL, EMAIL VARCHAR(100) NOT NULL, EMAIL_TYPE VARCHAR(20) NOT NULL, - META_INFO VARCHAR(8000) NOT NULL, + META_INFO VARCHAR(8000) NULL, CREATED_AT DATETIME2(0) NOT NULL, EXPIRY_TIME INT NOT NULL DEFAULT 3600, IS_EXPIRED BIT DEFAULT 0, @@ -711,7 +722,7 @@ DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID ORDER BY DEVICE_INFO.DEVICE_ID'); -IF NOT EXISTS (SELECT * FROM SYS.VIEWS WHERE NAME = 'CREATE VIEW FEATURE_NON_COMPLIANCE_INFO') +IF NOT EXISTS (SELECT * FROM SYS.VIEWS WHERE NAME = 'FEATURE_NON_COMPLIANCE_INFO') exec('CREATE VIEW FEATURE_NON_COMPLIANCE_INFO AS SELECT TOP 100 PERCENT DM_DEVICE.ID AS DEVICE_ID, @@ -866,15 +877,16 @@ IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[D CREATE TABLE DM_DEVICE_SUB_TYPE ( TENANT_ID INT DEFAULT 0, SUB_TYPE_ID VARCHAR(45) NOT NULL, - DEVICE_TYPE VARCHAR(25) NOT NULL, - SUB_TYPE_NAME VARCHAR(45) NOT NULL, + DEVICE_TYPE VARCHAR(45) NOT NULL, + SUB_TYPE_NAME VARCHAR(100) NOT NULL, TYPE_DEFINITION TEXT NOT NULL, PRIMARY KEY (SUB_TYPE_ID,DEVICE_TYPE) ); -- END OF DM_DEVICE_SUB_TYPE TABLE-- -- DM_TRACCAR_UNSYNCED_DEVICES TABLE -- -CREATE TABLE IF NOT EXISTS DM_TRACCAR_UNSYNCED_DEVICES ( +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_TRACCAR_UNSYNCED_DEVICES]') AND TYPE IN (N'U')) +CREATE TABLE DM_TRACCAR_UNSYNCED_DEVICES ( ID INT NOT NULL IDENTITY(1,1), DEVICE_NAME VARCHAR(100) NOT NULL, IOTS_DEVICE_IDENTIFIER VARCHAR(300) NULL UNIQUE, @@ -893,7 +905,7 @@ CREATE TABLE SUB_OPERATION_TEMPLATE ( OPERATION_DEFINITION VARCHAR(MAX) NOT NULL, OPERATION_CODE varchar(100) NOT NULL, SUB_TYPE_ID VARCHAR(45) NOT NULL, - DEVICE_TYPE VARCHAR(25) NOT NULL, + DEVICE_TYPE VARCHAR(45) NOT NULL, CREATE_TIMESTAMP BIGINT NULL DEFAULT NULL, UPDATE_TIMESTAMP BIGINT NULL DEFAULT NULL, PRIMARY KEY (SUB_OPERATION_TEMPLATE_ID), @@ -901,4 +913,4 @@ CREATE TABLE SUB_OPERATION_TEMPLATE ( CONSTRAINT fk_SUB_OPERATION_TEMPLATE_DM_DEVICE_SUB_TYPE FOREIGN KEY (SUB_TYPE_ID, DEVICE_TYPE) REFERENCES DM_DEVICE_SUB_TYPE (SUB_TYPE_ID, DEVICE_TYPE) ); --- END SUB_OPERATION_TEMPLATE TABLE-- \ No newline at end of file +-- END SUB_OPERATION_TEMPLATE TABLE-- diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql index e55274e49f..5e33d6b2b4 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -107,9 +107,14 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TENANT_ID INT NOT NULL, PRIMARY KEY (ID) )ENGINE = InnoDB; +CREATE INDEX IDX_OP_CREATED ON DM_OPERATION (CREATED_TIMESTAMP ASC); +CREATE INDEX IDX_OP_CODE ON DM_OPERATION (OPERATION_CODE ASC); +CREATE INDEX IDX_OP_INITIATED_BY ON DM_OPERATION (INITIATED_BY ASC); + CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( ID INTEGER AUTO_INCREMENT NOT NULL, DEVICE_ID INTEGER NOT NULL, @@ -170,6 +175,7 @@ CREATE INDEX IDX_ENROLMENT_OP_MAPPING ON DM_ENROLMENT_OP_MAPPING (UPDATED_TIMEST CREATE INDEX IDX_EN_OP_MAPPING_EN_ID ON DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID); CREATE INDEX IDX_EN_OP_MAPPING_OP_ID ON DM_ENROLMENT_OP_MAPPING(OPERATION_ID); CREATE INDEX IDX_EN_OP_MAPPING_EN_ID_STATUS ON DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID, STATUS); +CREATE INDEX IDX_ENROLMENT_OP_MAPPING_CREATED_TS ON DM_ENROLMENT_OP_MAPPING (CREATED_TIMESTAMP ASC); CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( @@ -650,7 +656,7 @@ CREATE TABLE IF NOT EXISTS DM_METADATA ( METADATA_ID INTEGER NOT NULL AUTO_INCREMENT, DATA_TYPE VARCHAR(16) NOT NULL, METADATA_KEY VARCHAR(128) NOT NULL, - METADATA_VALUE VARCHAR(8000) NOT NULL, + METADATA_VALUE TEXT NOT NULL, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (METADATA_ID), UNIQUE KEY METADATA_KEY_TENANT_ID (METADATA_KEY,TENANT_ID) @@ -665,7 +671,7 @@ CREATE TABLE IF NOT EXISTS DM_OTP_DATA ( USERNAME VARCHAR(500) NOT NULL, EMAIL VARCHAR(100) NOT NULL, EMAIL_TYPE VARCHAR(20) NOT NULL, - META_INFO VARCHAR(20000) NOT NULL, + META_INFO VARCHAR(20000) NULL, CREATED_AT TIMESTAMP NOT NULL, EXPIRY_TIME INT NOT NULL DEFAULT 3600, IS_EXPIRED BOOLEAN DEFAULT false, @@ -867,8 +873,8 @@ CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( CREATE TABLE IF NOT EXISTS DM_DEVICE_SUB_TYPE ( TENANT_ID INT DEFAULT 0, SUB_TYPE_ID VARCHAR(45) NOT NULL, - DEVICE_TYPE VARCHAR(25) NOT NULL, - SUB_TYPE_NAME VARCHAR(45) NOT NULL, + DEVICE_TYPE VARCHAR(45) NOT NULL, + SUB_TYPE_NAME VARCHAR(100) NOT NULL, TYPE_DEFINITION TEXT NOT NULL, PRIMARY KEY (SUB_TYPE_ID,DEVICE_TYPE) ) ENGINE=InnoDB; diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql index 708f135b78..035f31d31d 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -181,6 +181,7 @@ CREATE TABLE DM_OPERATION ( INITIATED_BY VARCHAR2(100) NULL, ENABLED NUMBER(10) DEFAULT 0 NOT NULL, OPERATION_DETAILS BLOB DEFAULT NULL, + TENANT_ID INTEGER NOT NULL, CONSTRAINT PK_DM_OPERATION PRIMARY KEY (ID) ) / @@ -997,7 +998,8 @@ CREATE TABLE DM_METADATA ( METADATA_ID NUMBER(10) NOT NULL, DATA_TYPE VARCHAR2(16) NOT NULL, METADATA_KEY VARCHAR2(128) NOT NULL, - METADATA_VALUE VARCHAR2(8000) NOT NULL, + -- Can be upgrade to 32767 bytes if the MAX_STRING_SIZE initialization parameter is set to EXTENDED -- + METADATA_VALUE TEXT NOT NULL, TENANT_ID INTEGER NOT NULL, CONSTRAINT PK_DM_METADATA PRIMARY KEY (METADATA_ID), CONSTRAINT METADATA_KEY_TENANT_ID UNIQUE (METADATA_KEY, TENANT_ID) @@ -1026,7 +1028,7 @@ CREATE TABLE DM_OTP_DATA ( USERNAME VARCHAR(500) NOT NULL, EMAIL VARCHAR2(100) NOT NULL, EMAIL_TYPE VARCHAR2(20) NOT NULL, - META_INFO VARCHAR2(20000) NOT NULL, + META_INFO VARCHAR2(20000) NULL, CREATED_AT TIMESTAMP(0) NOT NULL, EXPIRY_TIME NUMBER(10) DEFAULT 3600 NOT NULL, IS_EXPIRED CHAR(1) DEFAULT false, @@ -1147,8 +1149,8 @@ CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( CREATE TABLE IF NOT EXISTS DM_DEVICE_SUB_TYPE ( TENANT_ID INT DEFAULT 0, SUB_TYPE_ID VARCHAR(45) NOT NULL, - DEVICE_TYPE VARCHAR(25) NOT NULL, - SUB_TYPE_NAME VARCHAR(45) NOT NULL, + DEVICE_TYPE VARCHAR(45) NOT NULL, + SUB_TYPE_NAME VARCHAR(100) NOT NULL, TYPE_DEFINITION TEXT NOT NULL, PRIMARY KEY (SUB_TYPE_ID,DEVICE_TYPE) ) ENGINE=InnoDB; diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql index 3ff77c0242..1b9393885c 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -100,10 +100,13 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BYTEA DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); - +CREATE INDEX IDX_OP_CREATED ON DM_OPERATION (CREATED_TIMESTAMP); +CREATE INDEX IDX_OP_CODE ON DM_OPERATION (OPERATION_CODE); +CREATE INDEX IDX_OP_INITIATED_BY ON DM_OPERATION (INITIATED_BY); CREATE SEQUENCE DM_ENROLMENT_seq; @@ -161,6 +164,7 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( CREATE INDEX fk_dm_device_operation_mapping_operation ON DM_ENROLMENT_OP_MAPPING (OPERATION_ID); CREATE INDEX IDX_DM_ENROLMENT_OP_MAPPING ON DM_ENROLMENT_OP_MAPPING (ENROLMENT_ID,OPERATION_ID); CREATE INDEX ID_DM_ENROLMENT_OP_MAPPING_UPDATED_TIMESTAMP ON DM_ENROLMENT_OP_MAPPING (UPDATED_TIMESTAMP); +CREATE INDEX IDX_ENROLMENT_OP_MAPPING_CREATED_TS ON DM_ENROLMENT_OP_MAPPING (CREATED_TIMESTAMP); ALTER TABLE DM_ENROLMENT_OP_MAPPING ADD OPERATION_CODE VARCHAR(50) NOT NULL, @@ -656,7 +660,7 @@ CREATE TABLE IF NOT EXISTS DM_METADATA ( METADATA_ID BIGSERIAL PRIMARY KEY, DATA_TYPE VARCHAR(16) NOT NULL, METADATA_KEY VARCHAR(128) NOT NULL, - METADATA_VALUE VARCHAR(8000) NOT NULL, + METADATA_VALUE TEXT NOT NULL, TENANT_ID INTEGER NOT NULL, CONSTRAINT METADATA_KEY_TENANT_ID UNIQUE(METADATA_KEY, TENANT_ID) ); @@ -672,7 +676,7 @@ CREATE TABLE IF NOT EXISTS DM_OTP_DATA ( USERNAME VARCHAR(500) NOT NULL, EMAIL VARCHAR(100) NOT NULL, EMAIL_TYPE VARCHAR(20) NOT NULL, - META_INFO VARCHAR(20000) NOT NULL, + META_INFO VARCHAR(20000) NULL, CREATED_AT TIMESTAMP(0) NOT NULL, EXPIRY_TIME INT NOT NULL DEFAULT 3600, IS_EXPIRED BOOLEAN DEFAULT false, @@ -791,8 +795,8 @@ CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( CREATE TABLE IF NOT EXISTS DM_DEVICE_SUB_TYPE ( TENANT_ID INT DEFAULT 0, SUB_TYPE_ID VARCHAR(45) NOT NULL, - DEVICE_TYPE VARCHAR(25) NOT NULL, - SUB_TYPE_NAME VARCHAR(45) NOT NULL, + DEVICE_TYPE VARCHAR(45) NOT NULL, + SUB_TYPE_NAME VARCHAR(100) NOT NULL, TYPE_DEFINITION TEXT NOT NULL, PRIMARY KEY (SUB_TYPE_ID,DEVICE_TYPE) ) ENGINE=InnoDB; diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml index 27021a2438..6380d8e790 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml index 3a59ab333c..2e6fce0d35 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml index 807a532624..a72a21fbbe 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/pom.xml b/features/device-mgt/pom.xml index 99cfbf9851..040af5111a 100644 --- a/features/device-mgt/pom.xml +++ b/features/device-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml index dd42eccd92..10d1a4e1ff 100644 --- a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml +++ b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core heart-beat-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml index a434001e72..afdc9b3971 100644 --- a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml +++ b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml @@ -49,4 +49,7 @@ 300 5 600 + + + diff --git a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/heart-beat-config.xml.j2 b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/heart-beat-config.xml.j2 index f128b56c19..a294c876e3 100644 --- a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/heart-beat-config.xml.j2 +++ b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/heart-beat-config.xml.j2 @@ -51,11 +51,21 @@ {{heart_beat_beacon_conf.notifier_frequency_in_seconds}} {{heart_beat_beacon_conf.time_skew_in_seconds}} {{heart_beat_beacon_conf.sever_timeout_interval_in_seconds}} + {% if heart_beat_beacon_conf.cluster_formation_changed_configs.cluster_formation_changed_notifiers is defined %} + + {%- for cluster_formation_changed_notifier in heart_beat_beacon_conf.cluster_formation_changed_configs.cluster_formation_changed_notifiers -%} + {{cluster_formation_changed_notifier}} + {% endfor %} + + {% endif %} {% else %} false 30 300 5 600 + + + {% endif %} diff --git a/features/heartbeat-management/pom.xml b/features/heartbeat-management/pom.xml index 8cbf3eeb8e..4d2ab7d267 100644 --- a/features/heartbeat-management/pom.xml +++ b/features/heartbeat-management/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml b/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml index c50cdd8d20..a99f12315b 100644 --- a/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml +++ b/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core jwt-client-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/jwt-client/pom.xml b/features/jwt-client/pom.xml index 884f3ab23f..f4a32ee6af 100644 --- a/features/jwt-client/pom.xml +++ b/features/jwt-client/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml b/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml index 3382386a83..bd5400e510 100644 --- a/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml +++ b/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core logger-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/logger/pom.xml b/features/logger/pom.xml index 726a7256f3..bedf8aac4b 100644 --- a/features/logger/pom.xml +++ b/features/logger/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml b/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml index 4c5493a008..851a7d5509 100644 --- a/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml +++ b/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core operation-template-mgt-plugin-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/operation-template-mgt-plugin-feature/pom.xml b/features/operation-template-mgt-plugin-feature/pom.xml index 8f6b7be783..a3791b2afd 100644 --- a/features/operation-template-mgt-plugin-feature/pom.xml +++ b/features/operation-template-mgt-plugin-feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml b/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml index 33d36963e9..108ee60d0d 100644 --- a/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml +++ b/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core policy-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/policy-mgt/pom.xml b/features/policy-mgt/pom.xml index 9f5a616630..c7762786d0 100644 --- a/features/policy-mgt/pom.xml +++ b/features/policy-mgt/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml b/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml index d1907ce749..2df461bcd7 100644 --- a/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml +++ b/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../../pom.xml diff --git a/features/subtype-mgt/pom.xml b/features/subtype-mgt/pom.xml index f20e1e179e..3d388bd0b6 100644 --- a/features/subtype-mgt/pom.xml +++ b/features/subtype-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml b/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml index 3e5138ff62..60af9a0bb4 100755 --- a/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml +++ b/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../../pom.xml diff --git a/features/task-mgt/pom.xml b/features/task-mgt/pom.xml index 792a4c642b..fca80b6ce9 100755 --- a/features/task-mgt/pom.xml +++ b/features/task-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml b/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml index f7bdb9edad..9b90307dd6 100644 --- a/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml +++ b/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml @@ -20,7 +20,7 @@ tenant-mgt-feature io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/tenant-mgt/pom.xml b/features/tenant-mgt/pom.xml index bfb68a1d0f..6007c3d4af 100644 --- a/features/tenant-mgt/pom.xml +++ b/features/tenant-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml index ed01b32a32..ab4a1627a5 100644 --- a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml +++ b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core email-sender-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/email-sender/pom.xml b/features/transport-mgt/email-sender/pom.xml index d2d2d848c1..7bea1a0af6 100644 --- a/features/transport-mgt/email-sender/pom.xml +++ b/features/transport-mgt/email-sender/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core transport-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/pom.xml b/features/transport-mgt/pom.xml index 64eaa579c1..2403e63301 100644 --- a/features/transport-mgt/pom.xml +++ b/features/transport-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api.feature/pom.xml b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api.feature/pom.xml index 700f203300..6f8e76a66e 100644 --- a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api.feature/pom.xml +++ b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml index c4205aac44..4b908eb03f 100644 --- a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml +++ b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/sms-handler/pom.xml b/features/transport-mgt/sms-handler/pom.xml index 736902011c..f5209b00b5 100644 --- a/features/transport-mgt/sms-handler/pom.xml +++ b/features/transport-mgt/sms-handler/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core transport-mgt-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor.feature/pom.xml b/features/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor.feature/pom.xml index 24c673bfdb..014bf54fd9 100644 --- a/features/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor.feature/pom.xml +++ b/features/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor.feature/pom.xml @@ -21,7 +21,7 @@ ui-request-interceptor-feature io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT 4.0.0 diff --git a/features/ui-request-interceptor/pom.xml b/features/ui-request-interceptor/pom.xml index ec03b2a611..0c614753c6 100644 --- a/features/ui-request-interceptor/pom.xml +++ b/features/ui-request-interceptor/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml b/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml index 33ecdc5a35..ddac272f6f 100644 --- a/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml +++ b/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core webapp-authenticator-framework-feature - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../pom.xml diff --git a/features/webapp-authenticator-framework/pom.xml b/features/webapp-authenticator-framework/pom.xml index 72001d4378..1de6a5a14b 100644 --- a/features/webapp-authenticator-framework/pom.xml +++ b/features/webapp-authenticator-framework/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index 35f338c22e..e404ebb436 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent pom - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT WSO2 Carbon - Device Management - Parent https://entgra.io WSO2 Connected Device Manager Components @@ -1996,7 +1996,7 @@ 1.2.11-wso2v25 - 5.0.29-SNAPSHOT + 5.0.31-SNAPSHOT 4.9.2 @@ -2026,6 +2026,11 @@ 1.1.wso2v1 1.9.13 + + 20220924 + 2.4.5 + 27.0.1-jre + 1.70.0.wso2v1 1.70.0.wso2v1 @@ -2043,7 +2048,7 @@ 11.0 1.1.1 1.2 - 4.5.6 + 4.5.13 4.4.13 4.5.10