diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.api/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.api/pom.xml index 748108ec60..9d4d76223d 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.api/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.api/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt grafana-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.common/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.common/pom.xml index 45a1ab1381..402e68a706 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.common/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.common/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt grafana-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/pom.xml index 15bce92123..a66ba64fff 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt grafana-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/grafana-mgt/pom.xml b/components/analytics-mgt/grafana-mgt/pom.xml index 781fa794db..92bc7f1721 100644 --- a/components/analytics-mgt/grafana-mgt/pom.xml +++ b/components/analytics-mgt/grafana-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt analytics-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/pom.xml b/components/analytics-mgt/pom.xml index 21f5069a74..533b60c989 100644 --- a/components/analytics-mgt/pom.xml +++ b/components/analytics-mgt/pom.xml @@ -3,7 +3,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml index 1783073616..e9137ae00a 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml index 95cc7dbf4b..2e7f50e997 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml @@ -21,7 +21,7 @@ apimgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml index e7a8040eef..1c29c246e5 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java index 4ef90936b2..41ee18da8a 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java @@ -256,10 +256,14 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe keyManagerId = keyManagerConfigurationDTO.getUuid(); } } + String applicationAccessTokenExpiryTime = "N/A"; + if (!StringUtils.isEmpty(validityTime)) { + applicationAccessTokenExpiryTime = validityTime; + } String jsonString = "{\"grant_types\":\"refresh_token,access_token," + "urn:ietf:params:oauth:grant-type:saml2-bearer," + "password,client_credentials,iwa:ntlm,urn:ietf:params:oauth:grant-type:jwt-bearer\"," + - "\"additionalProperties\":\"{\\\"application_access_token_expiry_time\\\":\\\"N\\/A\\\"," + + "\"additionalProperties\":\"{\\\"application_access_token_expiry_time\\\":\\\"" + applicationAccessTokenExpiryTime + "\\\"," + "\\\"user_access_token_expiry_time\\\":\\\"N\\/A\\\"," + "\\\"refresh_token_expiry_time\\\":\\\"N\\/A\\\"," + "\\\"id_token_expiry_time\\\":\\\"N\\/A\\\"}\"," + diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/pom.xml index 03da5eb4af..dd957864f2 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/pom.xml @@ -3,7 +3,7 @@ apimgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT 4.0.0 diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/DCRRequest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/DCRRequest.java index 5054e2220d..7d45e71ef6 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/DCRRequest.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/DCRRequest.java @@ -40,6 +40,9 @@ public class DCRRequest { @XmlElement private boolean isSaasApp; + @XmlElement + private int validityPeriod; + public String getApplicationName() { return applicationName; } @@ -87,4 +90,12 @@ public class DCRRequest { public void setIsSaasApp(boolean saasApp) { isSaasApp = saasApp; } + + public int getValidityPeriod() { + return validityPeriod; + } + + public void setValidityPeriod(int validityPeriod) { + this.validityPeriod = validityPeriod; + } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerService.java index dfd6af295a..3775d6d9f1 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerService.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerService.java @@ -46,5 +46,6 @@ public interface KeyManagerService { @FormParam("assertion") String assertion, @FormParam("admin_access_token") String admin_access_token, @FormParam("username") String username, - @FormParam("password") String password); + @FormParam("password") String password, + @FormParam("validityPeriod") int validityPeriod); } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java index 961951f865..59d93912b0 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java @@ -51,7 +51,7 @@ public class KeyManagerServiceImpl implements KeyManagerService { try { KeyMgtService keyMgtService = new KeyMgtServiceImpl(); DCRResponse resp = keyMgtService.dynamicClientRegistration(dcrRequest.getApplicationName(), dcrRequest.getUsername(), - dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), dcrRequest.getIsSaasApp()); + dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), dcrRequest.getIsSaasApp(), dcrRequest.getValidityPeriod()); return Response.status(Response.Status.CREATED).entity(gson.toJson(resp)).build(); } catch (KeyMgtException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); @@ -69,7 +69,8 @@ public class KeyManagerServiceImpl implements KeyManagerService { @FormParam("assertion") String assertion, @FormParam("admin_access_token") String admin_access_token, @FormParam("username") String username, - @FormParam("password") String password) { + @FormParam("password") String password, + @FormParam("validityPeriod") int validityPeriod) { try { if (basicAuthHeader == null) { String msg = "Invalid credentials. Make sure your API call is invoked with a Basic Authorization header."; @@ -80,7 +81,7 @@ public class KeyManagerServiceImpl implements KeyManagerService { TokenResponse resp = keyMgtService.generateAccessToken( new TokenRequest(encodedClientCredentials.split(":")[0], encodedClientCredentials.split(":")[1], refreshToken, scope, - grantType, assertion, admin_access_token, username, password)); + grantType, assertion, admin_access_token, username, password, validityPeriod)); return Response.status(Response.Status.OK).entity(gson.toJson(resp)).build(); } catch (KeyMgtException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/pom.xml index 1d064a5656..4379709bef 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/pom.xml @@ -3,7 +3,7 @@ apimgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/TokenRequest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/TokenRequest.java index 860b267161..6bddd30d0b 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/TokenRequest.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/TokenRequest.java @@ -29,8 +29,10 @@ public class TokenRequest { private String username; private String password; + private int validityPeriod; + public TokenRequest(String clientId, String clientSecret, String refreshToken, String scope, String grantType, - String assertion, String admin_access_token, String username, String password) { + String assertion, String admin_access_token, String username, String password, int validityPeriod) { this.clientId = clientId; this.clientSecret = clientSecret; this.refreshToken = refreshToken; @@ -40,6 +42,7 @@ public class TokenRequest { this.admin_access_token = admin_access_token; this.username = username; this.password = password; + this.validityPeriod = validityPeriod; } public String getClientId() { @@ -113,4 +116,12 @@ public class TokenRequest { public void setPassword(String password) { this.password = password; } + + public int getValidityPeriod() { + return validityPeriod; + } + + public void setValidityPeriod(int validityPeriod) { + this.validityPeriod = validityPeriod; + } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtService.java index a9aa2d346a..4e185d2f4d 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtService.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtService.java @@ -39,7 +39,7 @@ public interface KeyMgtService { * @throws KeyMgtException if any error occurs during DCR process */ DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl, - String[] tags, boolean isSaasApp) throws KeyMgtException; + String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException; /*** * This method will handle the access token requests diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java index 4640fc9a57..1a564e1246 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java @@ -77,7 +77,7 @@ public class KeyMgtServiceImpl implements KeyMgtService { String subTenantUserUsername, subTenantUserPassword, keyManagerName, msg = null; public DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl, - String[] tags, boolean isSaasApp) throws KeyMgtException { + String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException { if (owner == null) { PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); @@ -105,13 +105,13 @@ public class KeyMgtServiceImpl implements KeyMgtService { kmConfig = getKeyManagerConfig(); if (KeyMgtConstants.SUPER_TENANT.equals(tenantDomain)) { - OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags); + OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags, validityPeriod); return new DCRResponse(dcrApplication.getClientId(), dcrApplication.getClientSecret()); } else { // super-tenant admin dcr and token generation OAuthApplication superTenantOauthApp = createOauthApplication( KeyMgtConstants.RESERVED_OAUTH_APP_NAME_PREFIX + KeyMgtConstants.SUPER_TENANT, - kmConfig.getAdminUsername(), null); + kmConfig.getAdminUsername(), null, validityPeriod); String superAdminAccessToken = createAccessToken(superTenantOauthApp); // create new key manager for the tenant, under super-tenant space @@ -133,7 +133,7 @@ public class KeyMgtServiceImpl implements KeyMgtService { createUserIfNotExists(subTenantUserUsername, subTenantUserPassword); // DCR for the requesting user - OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags); + OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags, validityPeriod); String requestingUserAccessToken = createAccessToken(dcrApplication); // get application id @@ -167,7 +167,8 @@ public class KeyMgtServiceImpl implements KeyMgtService { case "client_credentials": appTokenPayload = new FormBody.Builder() .add("grant_type", "client_credentials") - .add("scope", tokenRequest.getScope()).build(); + .add("scope", tokenRequest.getScope()) + .add("validityPeriod", String.valueOf(tokenRequest.getValidityPeriod())).build(); break; case "password": appTokenPayload = new FormBody.Builder() @@ -322,8 +323,8 @@ public class KeyMgtServiceImpl implements KeyMgtService { * @return @{@link OAuthApplication} OAuth application object * @throws KeyMgtException if any error occurs while creating response object */ - private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags) throws KeyMgtException { - String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags); + private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags, int validityPeriod) throws KeyMgtException { + String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags, validityPeriod); RequestBody oauthAppCreationPayload = RequestBody.Companion.create(oauthAppCreationPayloadStr, JSON); kmConfig = getKeyManagerConfig(); String dcrEndpoint = kmConfig.getServerUrl() + KeyMgtConstants.DCR_ENDPOINT; @@ -442,11 +443,12 @@ public class KeyMgtServiceImpl implements KeyMgtService { } } - private String createOauthAppCreationPayload(String clientName, String owner, String[] tags) { + private String createOauthAppCreationPayload(String clientName, String owner, String[] tags, int validityPeriod) { JSONObject jsonObject = new JSONObject(); jsonObject.put("applicationName", clientName); jsonObject.put("username", owner); jsonObject.put("tags", tags); + jsonObject.put("validityPeriod", validityPeriod); return jsonObject.toString(); } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml index 20525b5142..1e9e44a4a5 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index c09f37daa4..ba99795a04 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/components/application-mgt/io.entgra.application.mgt.addons/pom.xml b/components/application-mgt/io.entgra.application.mgt.addons/pom.xml index 26c496befd..66df7e582b 100644 --- a/components/application-mgt/io.entgra.application.mgt.addons/pom.xml +++ b/components/application-mgt/io.entgra.application.mgt.addons/pom.xml @@ -20,7 +20,7 @@ application-mgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/application-mgt/io.entgra.application.mgt.api/pom.xml b/components/application-mgt/io.entgra.application.mgt.api/pom.xml index 93e0c641b4..f869b39c73 100644 --- a/components/application-mgt/io.entgra.application.mgt.api/pom.xml +++ b/components/application-mgt/io.entgra.application.mgt.api/pom.xml @@ -22,7 +22,7 @@ application-mgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/application-mgt/io.entgra.application.mgt.common/pom.xml b/components/application-mgt/io.entgra.application.mgt.common/pom.xml index 54ddd889e8..d753086d86 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/pom.xml +++ b/components/application-mgt/io.entgra.application.mgt.common/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.devicemgt application-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/application-mgt/io.entgra.application.mgt.core/pom.xml b/components/application-mgt/io.entgra.application.mgt.core/pom.xml index 2c882ffc3c..ec9127ea06 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/pom.xml +++ b/components/application-mgt/io.entgra.application.mgt.core/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.devicemgt application-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java index 9ad0b9d4c0..bfce4e31fa 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java @@ -94,6 +94,7 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl { || StringUtils.isNotEmpty(filter.getAppReleaseType())) { sql += "LEFT JOIN AP_APP_RELEASE ON AP_APP.ID = AP_APP_RELEASE.AP_APP_ID "; } + sql += "WHERE AP_APP.TENANT_ID = ? "; if (StringUtils.isNotEmpty(filter.getAppType()) && !Constants.ALL.equalsIgnoreCase(filter.getAppType())) { sql += "AND AP_APP.TYPE = ? "; } @@ -128,7 +129,7 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl { sql += filter.getSortBy() +" "; } if (filter.getLimit() != -1) { - sql += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "; + sql += "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "; } sql += ") AS app_data ON app_data.ID = AP_APP.ID " + "LEFT JOIN (" @@ -145,6 +146,7 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { int paramIndex = 1; + stmt.setInt(paramIndex++, tenantId); if (StringUtils.isNotEmpty(filter.getAppType()) && !Constants.ALL.equalsIgnoreCase(filter.getAppType())) { stmt.setString(paramIndex++, filter.getAppType()); } diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/pom.xml b/components/application-mgt/io.entgra.application.mgt.publisher.api/pom.xml index f246e392fa..80e1bd83ea 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/pom.xml +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/pom.xml @@ -22,7 +22,7 @@ application-mgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/application-mgt/io.entgra.application.mgt.store.api/pom.xml b/components/application-mgt/io.entgra.application.mgt.store.api/pom.xml index 3cc8edac9a..760accf4ba 100644 --- a/components/application-mgt/io.entgra.application.mgt.store.api/pom.xml +++ b/components/application-mgt/io.entgra.application.mgt.store.api/pom.xml @@ -22,7 +22,7 @@ application-mgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/application-mgt/pom.xml b/components/application-mgt/pom.xml index 58475ac289..9ac074925c 100644 --- a/components/application-mgt/pom.xml +++ b/components/application-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml index 156ccf9cb0..36b4e164f1 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml @@ -22,7 +22,7 @@ certificate-mgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml index f617559454..ee2ac87f57 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml @@ -22,7 +22,7 @@ certificate-mgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml index 8521489c1c..dbd94e3b22 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml @@ -38,7 +38,7 @@ org.wso2.carbon.devicemgt certificate-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml index a780123240..1bd757ac9b 100644 --- a/components/certificate-mgt/pom.xml +++ b/components/certificate-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.defaultrole.manager/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.defaultrole.manager/pom.xml index 21986acdcc..5ede05302d 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.defaultrole.manager/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.defaultrole.manager/pom.xml @@ -23,7 +23,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/pom.xml index 4153e2c337..37dcc4ec1b 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/src/main/java/io/entgra/device/mgt/extensions/logger/spi/EntgraLogger.java b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/src/main/java/io/entgra/device/mgt/extensions/logger/spi/EntgraLogger.java index c959eb4885..2ffa6ffa8d 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/src/main/java/io/entgra/device/mgt/extensions/logger/spi/EntgraLogger.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/src/main/java/io/entgra/device/mgt/extensions/logger/spi/EntgraLogger.java @@ -48,6 +48,22 @@ public interface EntgraLogger extends Log { void warn(Object object, Throwable t, LogContext logContext); + void info(String message, LogContext logContext); + + void debug(String message, LogContext logContext); + + void error(String message, LogContext logContext); + + void error(String message, Throwable t, LogContext logContext); + + void warn(String message, LogContext logContext); + + void warn(String message, Throwable t, LogContext logContext); + + void trace(String message, LogContext logContext); + + void fatal(String message, LogContext logContext); + void clearLogContext(); } diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.stateengine/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.stateengine/pom.xml index 2dd1025f8b..ef88e49a2a 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.stateengine/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.stateengine/pom.xml @@ -23,7 +23,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml index 65c27150c0..1641e9e38d 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml index a6f43d0f7d..b35311d91b 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml index 7687af14ec..9cb045b700 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml index 250d1b2755..cab4f2afbe 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml index 27e81b2086..9536f5e514 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml index ac1d9433db..354033a4c3 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/pom.xml b/components/device-mgt-extensions/pom.xml index 61cc474096..250815e9ba 100644 --- a/components/device-mgt-extensions/pom.xml +++ b/components/device-mgt-extensions/pom.xml @@ -22,7 +22,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/pom.xml b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/pom.xml index 6173c124e8..4888ed0155 100644 --- a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/pom.xml +++ b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/pom.xml @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml index d232be71b8..f43128fc6c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml @@ -425,5 +425,30 @@ io.entgra.application.mgt.core provided + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.keymgt.extension + provided + + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.stream.core + provided + + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.receiver.core + provided + + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.publisher.core + provided + + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.output.adapter.rdbms + provided + \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceConfig.java new file mode 100644 index 0000000000..158153fd91 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceConfig.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 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 org.wso2.carbon.device.mgt.jaxrs.beans; + +import io.swagger.annotations.ApiModel; +import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; + +import java.util.List; + +@ApiModel(value = "DeviceConfig", description = "Device config") +public class DeviceConfig { + private String clientId; + private String clientSecret; + private String deviceId; + private String type; + private String accessToken; + private String refreshToken; + private String mqttGateway; + private String httpsGateway; + private String httpGateway; + private PlatformConfiguration platformConfiguration; + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientSecret() { + return clientSecret; + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public String getRefreshToken() { + return refreshToken; + } + + public void setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + } + + public String getMqttGateway() { + return mqttGateway; + } + + public void setMqttGateway(String mqttGateway) { + this.mqttGateway = mqttGateway; + } + + public String getHttpsGateway() { + return httpsGateway; + } + + public void setHttpsGateway(String httpsGateway) { + this.httpsGateway = httpsGateway; + } + + public String getHttpGateway() { + return httpGateway; + } + + public void setHttpGateway(String httpGateway) { + this.httpGateway = httpGateway; + } + + public PlatformConfiguration getPlatformConfiguration() { + return platformConfiguration; + } + + public void setPlatformConfiguration(PlatformConfiguration platformConfiguration) { + this.platformConfiguration = platformConfiguration; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/DeviceTypeEvent.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/DeviceTypeEvent.java index b8e07df6d5..b5a715135e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/DeviceTypeEvent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/DeviceTypeEvent.java @@ -20,14 +20,18 @@ package org.wso2.carbon.device.mgt.jaxrs.beans.analytics; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; +import java.util.List; + /** * This hold stats data record */ public class DeviceTypeEvent { + private String eventName; private EventAttributeList eventAttributes; private TransportType transport; + private String eventTopicStructure; @ApiModelProperty(value = "Attributes related to device type event") @JsonProperty("eventAttributes") public EventAttributeList getEventAttributeList() { @@ -48,5 +52,25 @@ public class DeviceTypeEvent { public void setTransportType(TransportType transport) { this.transport = transport; } + + @ApiModelProperty(value = "event topic structure") + @JsonProperty("eventTopicStructure") + public String getEventTopicStructure() { + return eventTopicStructure; + } + + public void setEventTopicStructure(String eventTopicStructure) { + this.eventTopicStructure = eventTopicStructure; + } + + @ApiModelProperty(value = "event topic name") + @JsonProperty("eventName") + public String getEventName() { + return eventName; + } + + public void setEventName(String eventName) { + this.eventName = eventName; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceEventManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceEventManagementService.java index 82e0cdb897..83503248fc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceEventManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceEventManagementService.java @@ -29,6 +29,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import java.util.List; @SwaggerDefinition( info = @Info( @@ -69,64 +70,64 @@ import javax.ws.rs.core.Response; @Consumes(MediaType.APPLICATION_JSON) public interface DeviceEventManagementService { -// @POST -// @Path("/{type}") -// @ApiOperation( -// produces = MediaType.APPLICATION_JSON, -// httpMethod = "POST", -// value = "Adding the Event Type Definition", -// notes = "Add the event definition for a device.", -// tags = "Device Event Management", -// extensions = { -// @Extension(properties = { -// @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events") -// }) -// } -// ) -// @ApiResponses( -// value = { -// @ApiResponse( -// code = 200, -// message = "OK. \n Successfully added the event defintion.", -// 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 was last modified.\n" + -// "Used by caches, or in conditional requests."), -// } -// ), -// @ApiResponse( -// code = 400, -// message = -// "Bad Request. \n"), -// @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 " + -// "list of supported device types.", -// response = ErrorResponse.class) -// } -// ) -// Response deployDeviceTypeEventDefinition( -// @ApiParam(name = "type", value = "The device type, such as android, ios, and windows.") -// @PathParam("type")String deviceType, -// @ApiParam(name = "skipPersist", value = "Is it required to persist the data or not") -// @QueryParam("skipPersist") boolean skipPersist, -// @ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants") -// @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, -// @ApiParam(name = "deviceTypeEvent", value = "Add the data to complete the DeviceTypeEvent object.", -// required = true) -// @Valid DeviceTypeEvent deviceTypeEvent); + @POST + @Path("/{type}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Adding the Event Type Definition", + notes = "Add the event definition for a device.", + tags = "Device Event Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully added the event defintion.", + 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 was last modified.\n" + + "Used by caches, or in conditional requests."), + } + ), + @ApiResponse( + code = 400, + message = + "Bad Request. \n"), + @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 " + + "list of supported device types.", + response = ErrorResponse.class) + } + ) + Response deployDeviceTypeEventDefinition( + @ApiParam(name = "type", value = "The device type, such as android, ios, and windows.") + @PathParam("type")String deviceType, + @ApiParam(name = "skipPersist", value = "Is it required to persist the data or not") + @QueryParam("skipPersist") boolean skipPersist, + @ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants") + @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, + @ApiParam(name = "deviceTypeEvents", value = "Add the data to complete the DeviceTypeEvent object.", + required = true) + @Valid List deviceTypeEvent); @DELETE @Path("/{type}") diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index 585e4ffecf..a080208de2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -188,6 +188,13 @@ import java.util.List; 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", + roles = {"Internal/devicemgt-user"}, + permissions = {"/device-mgt/devices/enrollment-guide/view"} + ), } ) @Path("/devices") @@ -553,12 +560,12 @@ public interface DeviceManagementService { required = false, defaultValue = "0") @QueryParam("offset") int offset, - @ApiParam( - name = "limit", - value = "Provide how many device details you require from the starting pagination index/offset.", - required = false, - defaultValue = "100") - @QueryParam("limit") int limit + @ApiParam( + name = "limit", + value = "Provide how many device details you require from the starting pagination index/offset.", + required = false, + defaultValue = "100") + @QueryParam("limit") int limit ); @GET @@ -802,6 +809,59 @@ public interface DeviceManagementService { @QueryParam("requireDeviceInfo") boolean requireDeviceInfo); + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Path("/enrollment/guide") + @ApiOperation( + consumes = MediaType.MULTIPART_FORM_DATA, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Sending Enrollment Mode chosen by customer", + notes = "Enrollment mode selected and path is sent as parameters", + tags = "Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:enrollment-guide:view") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully mailed the Enrollment Guide of customer.", + response = Device.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 was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while sending mail of the Enrollment Guide.", + response = ErrorResponse.class) + }) + Response sendEnrollmentGuide( + @ApiParam( + name = "enrolmentGuide", + value = "The details of the enrolment path suggested.", + required = true) + String enrolmentGuide); + @POST @Produces(MediaType.APPLICATION_JSON) @Path("/type/any/list") @@ -1059,6 +1119,82 @@ public interface DeviceManagementService { @HeaderParam("If-Modified-Since") String ifModifiedSince); + @GET + @Produces(MediaType.APPLICATION_JSON) + @Path("/{type}/{id}/config") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting the Configuration of a Device", + notes = "Get the configuration of a device by specifying the device type and device identifier.", + tags = "Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the configuration of the device.", + response = DeviceInfo.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 was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. Empty body because the client already has the latest version" + + " of the requested resource.\n"), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n Location data for the specified device was not found.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while retrieving the device details.", + response = ErrorResponse.class) + }) + Response getDeviceConfiguration( + @ApiParam( + name = "type", + value = "The device type name, such as ios, android, windows, or fire-alarm.", + required = true) + @PathParam("type") + @Size(max = 45) + String type, + @ApiParam( + name = "id", + value = "The device identifier of the device you want ot get details.", + required = true) + @PathParam("id") + @Size(max = 45) + String id, + @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); + //device rename request would looks like follows //POST devices/type/virtual_firealarm/id/us06ww93auzp/rename @POST @@ -1209,7 +1345,7 @@ public interface DeviceManagementService { @GET @Produces(MediaType.APPLICATION_JSON) - @Path("/{type}/{id}/features") + @Path("/device-type/{type}/features") @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", @@ -1280,14 +1416,6 @@ public interface DeviceManagementService { @PathParam("type") @Size(max = 45) String type, - @ApiParam( - name = "id", - value = "The device identifier of the device.\n" + - "INFO: Make sure to add the ID of a device that is already registered with WSO2 IoTS.", - required = true) - @PathParam("id") - @Size(max = 45) - String id, @ApiParam( name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time. \n" + @@ -1407,15 +1535,15 @@ public interface DeviceManagementService { @ResponseHeader( name = "ETag", description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), @ResponseHeader( name = "Last-Modified", description = "Date and time the resource was last modified. \n" + - "Used by caches, or in conditional requests.")}), + "Used by caches, or in conditional requests.")}), @ApiResponse( code = 304, message = "Not Modified. \n " + - "Empty body because the client already has the latest version of the requested resource.\n"), + "Empty body because the client already has the latest version of the requested resource.\n"), @ApiResponse( code = 400, message = "Bad Request. \n Invalid request or validation error.", @@ -1433,7 +1561,7 @@ public interface DeviceManagementService { @ApiResponse( code = 500, message = "Internal Server Error. \n " + - "Server error occurred while getting the device details.", + "Server error occurred while getting the device details.", response = ErrorResponse.class) }) Response queryDevicesByProperties( @@ -1455,7 +1583,7 @@ public interface DeviceManagementService { name = "device property map", value = "properties by which devices need filtered", required = true) - PropertyMap map); + PropertyMap map); @GET @Produces(MediaType.APPLICATION_JSON) @@ -1881,140 +2009,141 @@ public interface DeviceManagementService { @Size(max = 45) String id); - @GET - @Produces(MediaType.APPLICATION_JSON) - @Path("/{type}/{id}/getstatushistory") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Get Device status history", - notes = "Get a list of status history associated with the device type and id", - tags = "Device Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse( - code = 200, - message = "OK. \n Successfully fetched the status history of matching devices.", - response = List.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 was last modified.\n" + - "Used by caches, or in conditional requests."), - }), - @ApiResponse( - code = 304, - message = "Not Modified. Empty body because the client already has the latest version" + - " of the requested resource.\n"), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error.", - response = ErrorResponse.class), - @ApiResponse( - code = 404, - message = "Not Found. \n A device with the specified device type and id was not found.", - response = ErrorResponse.class), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while retrieving the device details.", - response = ErrorResponse.class) - }) + @GET + @Produces(MediaType.APPLICATION_JSON) + @Path("/{type}/{id}/status-history") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get Device status history", + notes = "Get a list of status history associated with the device type and id", + tags = "Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the status history of matching devices.", + response = List.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 was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. Empty body because the client already has the latest version" + + " of the requested resource.\n"), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n A device with the specified device type and id was not found.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while retrieving the device details.", + response = ErrorResponse.class) + }) Response getDeviceStatusHistory( - @ApiParam( - name = "type", - value = "The device type, such as ios, android, or windows.", - required = true) - @PathParam("type") - @Size(max = 45) - String type, - @ApiParam( - name = "id", - value = "Device ID.", - required = true) - @PathParam("id") - @Size(max = 45) - String id); - @GET - @Produces(MediaType.APPLICATION_JSON) - @Path("/{type}/{id}/getenrolmentstatushistory") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Get Device Current Enrolment status history", - notes = "Get a list of status history associated with the device type and id for the current enrolment", - tags = "Device Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse( - code = 200, - message = "OK. \n Successfully fetched the status history of matching devices.", - response = List.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 was last modified.\n" + - "Used by caches, or in conditional requests."), - }), - @ApiResponse( - code = 304, - message = "Not Modified. Empty body because the client already has the latest version" + - " of the requested resource.\n"), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error.", - response = ErrorResponse.class), - @ApiResponse( - code = 404, - message = "Not Found. \n A device with the specified device type and id was not found.", - response = ErrorResponse.class), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while retrieving the device details.", - response = ErrorResponse.class) - }) + @ApiParam( + name = "type", + value = "The device type, such as ios, android, or windows.", + required = true) + @PathParam("type") + @Size(max = 45) + String type, + @ApiParam( + name = "id", + value = "Device ID.", + required = true) + @PathParam("id") + @Size(max = 45) + String id); + + @GET + @Produces(MediaType.APPLICATION_JSON) + @Path("/{type}/{id}/enrolment-status-history") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get Device Current Enrolment status history", + notes = "Get a list of status history associated with the device type and id for the current enrolment", + tags = "Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the status history of matching devices.", + response = List.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 was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. Empty body because the client already has the latest version" + + " of the requested resource.\n"), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n A device with the specified device type and id was not found.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while retrieving the device details.", + response = ErrorResponse.class) + }) Response getCurrentEnrolmentDeviceStatusHistory( - @ApiParam( - name = "type", - value = "The device type, such as ios, android, or windows.", - required = true) - @PathParam("type") - @Size(max = 45) - String type, - @ApiParam( - name = "id", - value = "Device ID.", - required = true) - @PathParam("id") - @Size(max = 45) - String id); + @ApiParam( + name = "type", + value = "The device type, such as ios, android, or windows.", + required = true) + @PathParam("type") + @Size(max = 45) + String type, + @ApiParam( + name = "id", + value = "Device ID.", + required = true) + @PathParam("id") + @Size(max = 45) + String id); @PUT @Produces(MediaType.APPLICATION_JSON) @@ -2179,16 +2308,16 @@ public interface DeviceManagementService { @ResponseHeader( name = "ETag", description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), @ResponseHeader( name = "Last-Modified", description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), }), @ApiResponse( code = 304, message = "Not Modified. Empty body because the client already has the latest version" + - " of the requested resource.\n"), + " of the requested resource.\n"), @ApiResponse( code = 400, message = "Bad Request. \n Invalid request or validation error.", @@ -2200,7 +2329,7 @@ public interface DeviceManagementService { @ApiResponse( code = 500, message = "Internal Server Error. \n " + - "Server error occurred while retrieving the device details.", + "Server error occurred while retrieving the device details.", response = ErrorResponse.class) }) Response getDeviceCountByStatus( @@ -2248,16 +2377,16 @@ public interface DeviceManagementService { @ResponseHeader( name = "ETag", description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), @ResponseHeader( name = "Last-Modified", description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), }), @ApiResponse( code = 304, message = "Not Modified. Empty body because the client already has the latest version" + - " of the requested resource.\n"), + " of the requested resource.\n"), @ApiResponse( code = 400, message = "Bad Request. \n Invalid request or validation error.", @@ -2269,7 +2398,7 @@ public interface DeviceManagementService { @ApiResponse( code = 500, message = "Internal Server Error. \n " + - "Server error occurred while retrieving the device details.", + "Server error occurred while retrieving the device details.", response = ErrorResponse.class) }) Response getDeviceIdentifiersByStatus( @@ -2318,16 +2447,16 @@ public interface DeviceManagementService { @ResponseHeader( name = "ETag", description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), + "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."), + "Used by caches, or in conditional requests."), }), @ApiResponse( code = 304, message = "Not Modified. Empty body because the client already has the latest " + - "version of the requested resource."), + "version of the requested resource."), @ApiResponse( code = 400, message = "Bad Request. \n Invalid request or validation error.", @@ -2339,7 +2468,7 @@ public interface DeviceManagementService { @ApiResponse( code = 500, message = "Internal Server Error. \n " + - "Server error occurred while retrieving information requested device.", + "Server error occurred while retrieving information requested device.", response = ErrorResponse.class) }) Response bulkUpdateDeviceStatus( @@ -2650,11 +2779,11 @@ public interface DeviceManagementService { @ResponseHeader( name = "ETag", description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), @ResponseHeader( name = "Last-Modified", description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), }), @ApiResponse( code = 500, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java index 1162c55f45..96b3188f70 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java @@ -192,6 +192,13 @@ import java.util.List; key = "perm:groups:device", roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/groups/devices/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", + roles = {"Internal/devicemgt-user"}, + permissions = {"/device-mgt/groups/devices/types"} ) } ) @@ -1185,4 +1192,58 @@ public interface GroupManagementService { @QueryParam("requireGroupProps") boolean requireGroupProps); + @Path("/device-types") + @POST + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_GET, + value = "Getting Details whether the groups has relevant device type or not", + notes = "Getting Details whether the groups has relevant device type or not.", + tags = "Device Group Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:devices-types") + }) + }, + nickname = "getGroupByGroupNameFilter" + ) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the device types of groups.", + response = DeviceGroup.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 = "Error occurred", + 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 details.", + response = ErrorResponse.class) + }) + Response getGroupHasDeviceTypes( + @ApiParam( + name = "identifiers", + value = "GET list of identifiers.", + required = true) + List identifiers); + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceEventManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceEventManagementServiceImpl.java index 4cba178f12..49cbdae59a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceEventManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceEventManagementServiceImpl.java @@ -1,12 +1,30 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl; +import edu.emory.mathcs.backport.java.util.Arrays; import org.apache.axis2.AxisFault; import org.apache.axis2.client.Stub; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.velocity.util.ArrayListWrapper; +import org.json.JSONObject; +import org.opensaml.xml.signature.J; +import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminService; +import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException; +import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub; +import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTable; +import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTableRecord; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.databridge.commons.StreamDefinition; +import org.wso2.carbon.databridge.commons.exception.MalformedStreamDefinitionException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.Attribute; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.AttributeType; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.DeviceTypeEvent; @@ -15,26 +33,50 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.TransportType; import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceEventManagementService; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import org.wso2.carbon.event.input.adapter.core.InputEventAdapterConfiguration; +import org.wso2.carbon.event.input.adapter.core.MessageType; +import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration; +import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService; +import org.wso2.carbon.event.output.adapter.rdbms.RDBMSEventAdapter; +import org.wso2.carbon.event.output.adapter.rdbms.internal.ds.RDBMSEventAdapterServiceDS; +import org.wso2.carbon.event.processor.manager.core.EventProcessorManagementService; +import org.wso2.carbon.event.processor.manager.core.EventPublisherManagementService; +import org.wso2.carbon.event.publisher.core.EventPublisherService; +import org.wso2.carbon.event.publisher.core.config.EventPublisherConfiguration; +import org.wso2.carbon.event.publisher.core.config.mapping.JSONOutputMapping; +import org.wso2.carbon.event.publisher.core.config.mapping.MapOutputMapping; +import org.wso2.carbon.event.publisher.core.exception.EventPublisherConfigurationException; +import org.wso2.carbon.event.publisher.core.internal.ds.EventPublisherServiceDS; import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceCallbackHandler; import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub; +import org.wso2.carbon.event.receiver.core.EventReceiverService; +import org.wso2.carbon.event.receiver.core.config.EventReceiverConfiguration; +import org.wso2.carbon.event.receiver.core.config.InputMapping; +import org.wso2.carbon.event.receiver.core.config.mapping.JSONInputMapping; +import org.wso2.carbon.event.receiver.core.config.mapping.WSO2EventInputMapping; +import org.wso2.carbon.event.receiver.core.exception.EventReceiverConfigurationException; import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceCallbackHandler; import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub; import org.wso2.carbon.event.receiver.stub.types.BasicInputAdapterPropertyDto; import org.wso2.carbon.event.receiver.stub.types.EventReceiverConfigurationDto; +import org.wso2.carbon.event.receiver.stub.types.InputAdapterConfigurationDto; +import org.wso2.carbon.event.stream.core.EventStreamService; +import org.wso2.carbon.event.stream.core.exception.EventStreamConfigurationException; import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto; import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.user.api.UserStoreException; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; +import javax.validation.Valid; +import javax.ws.rs.*; import javax.ws.rs.core.Response; +import java.io.IOException; import java.rmi.RemoteException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; /** @@ -173,65 +215,73 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe /** * Deploy Event Stream, Receiver, Publisher and Store Configuration. */ -// @POST -// @Path("/{type}") -// @Override -// public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType, -// @QueryParam("skipPersist") boolean skipPersist, -// @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, -// @Valid DeviceTypeEvent deviceTypeEvent) { -// TransportType transportType = deviceTypeEvent.getTransportType(); -// EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList(); -// String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); -// try { -// if (eventAttributes == null || eventAttributes.getList() == null || eventAttributes.getList().size() == 0 || -// deviceType == null || transportType == null || -// !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { -// String errorMessage = "Invalid Payload"; -// log.error(errorMessage); -// return Response.status(Response.Status.BAD_REQUEST).build(); -// } -// String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain); -// String streamNameWithVersion = streamName + ":" + Constants.DEFAULT_STREAM_VERSION; -// publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes); -// publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType); -// if (!skipPersist) { -// publishEventStore(streamName, Constants.DEFAULT_STREAM_VERSION, eventAttributes); -// } -// publishWebsocketPublisherDefinition(streamNameWithVersion, deviceType); -// try { -// PrivilegedCarbonContext.startTenantFlow(); -// PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( -// MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); -// if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { -// publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes); -// publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType); -// } -// } finally { -// PrivilegedCarbonContext.endTenantFlow(); -// } -// return Response.ok().build(); -// } catch (AxisFault e) { -// log.error("Failed to create event definitions for tenantDomain:" + tenantDomain, e); -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -// } catch (RemoteException e) { -// log.error("Failed to connect with the remote services:" + tenantDomain, e); -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -// } catch (JWTClientException e) { -// log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e); -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -// } catch (UserStoreException e) { -// log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e); -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -// } catch (DeviceManagementException e) { -// log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e); -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -// } catch (EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException e) { -// log.error("Failed to create event store for, tenantDomain: " + tenantDomain + " deviceType" + deviceType, -// e); -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -// } -// } + @POST + @Path("/{type}") + @Override + public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType, + @QueryParam("skipPersist") boolean skipPersist, + @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, + @Valid List deviceTypeEvents) { + + + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + try { + for (DeviceTypeEvent deviceTypeEvent : deviceTypeEvents) { + TransportType transportType = deviceTypeEvent.getTransportType(); + EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList(); + String eventName = deviceTypeEvent.getEventName(); + + + if (eventAttributes == null || eventAttributes.getList() == null || eventAttributes.getList().size() == 0 || + deviceType == null || transportType == null || + !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { + String errorMessage = "Invalid Payload"; + log.error(errorMessage); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain, eventName); + publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, eventAttributes); + + String receiverName = getReceiverName(deviceType, tenantDomain, transportType, eventName); + publishEventReceivers(streamName, Constants.DEFAULT_STREAM_VERSION, transportType, tenantDomain, + isSharedWithAllTenants, deviceType, deviceTypeEvent.getEventTopicStructure(), receiverName); + if (!skipPersist) { + String rdbmsPublisherName = getPublisherName(deviceType, tenantDomain, eventName) + "_rdbms_publisher"; + publishEventStore(streamName, Constants.DEFAULT_STREAM_VERSION, rdbmsPublisherName); + } + String wsPublisherName = getPublisherName(deviceType, tenantDomain, eventName) + "_ws_publisher"; + publishWebsocketPublisherDefinition(streamName, Constants.DEFAULT_STREAM_VERSION, wsPublisherName); + try { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); + if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { + publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, eventAttributes); + publishEventReceivers(streamName, Constants.DEFAULT_STREAM_VERSION, transportType, tenantDomain, + isSharedWithAllTenants, deviceType, deviceTypeEvent.getEventTopicStructure(), receiverName); + } + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } + return Response.ok().build(); + } catch (DeviceManagementException e) { + log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } catch (MalformedStreamDefinitionException e) { + log.error("Failed while creating stream definition, tenantDomain: " + tenantDomain, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } catch (EventStreamConfigurationException e) { + log.error("Failed while configuring stream definition, tenantDomain: " + tenantDomain, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } catch (EventPublisherConfigurationException e) { + log.error("Failed while configuring event publisher, tenantDomain: " + tenantDomain, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } catch (EventReceiverConfigurationException e) { + log.error("Failed while configuring event receiver, tenantDomain: " + tenantDomain, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } + } /** * Delete device type specific artifacts from DAS. @@ -498,158 +548,172 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe // return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); // } // } - - - private void publishEventReceivers(String streamNameWithVersion, TransportType transportType - , String requestedTenantDomain, boolean isSharedWithAllTenants, String deviceType) - throws RemoteException, UserStoreException, JWTClientException { - EventReceiverAdminServiceStub receiverAdminServiceStub = DeviceMgtAPIUtils.getEventReceiverAdminServiceStub(); + private void publishEventReceivers(String streamName, String version, TransportType transportType + , String requestedTenantDomain, boolean isSharedWithAllTenants, String deviceType, + String eventTopicStructure, String receiverName) throws EventReceiverConfigurationException { + EventReceiverService eventReceiverService = DeviceMgtAPIUtils.getEventReceiverService(); try { - TransportType transportTypeToBeRemoved = TransportType.HTTP; - if (transportType == TransportType.HTTP) { - transportTypeToBeRemoved = TransportType.MQTT; - } - String eventRecieverNameTobeRemoved = getReceiverName(deviceType, requestedTenantDomain, transportTypeToBeRemoved); - EventReceiverConfigurationDto eventReceiverConfigurationDto = receiverAdminServiceStub - .getActiveEventReceiverConfiguration(eventRecieverNameTobeRemoved); - if (eventReceiverConfigurationDto != null) { - EventReceiverAdminServiceCallbackHandler eventReceiverAdminServiceCallbackHandler = - new EventReceiverAdminServiceCallbackHandler() { - }; - receiverAdminServiceStub.startundeployActiveEventReceiverConfiguration(eventRecieverNameTobeRemoved - , eventReceiverAdminServiceCallbackHandler); +// TransportType transportTypeToBeRemoved = TransportType.HTTP; +// if (transportType == TransportType.HTTP) { +// transportTypeToBeRemoved = TransportType.MQTT; +// } +// String eventRecieverNameTobeRemoved = getReceiverName(deviceType, requestedTenantDomain, transportTypeToBeRemoved); + EventReceiverConfiguration eventReceiverConfiguration = + eventReceiverService.getActiveEventReceiverConfiguration(receiverName); + if (eventReceiverConfiguration != null) { + eventReceiverService.undeployActiveEventReceiverConfiguration(receiverName); } - String adapterType = OAUTH_MQTT_ADAPTER_TYPE; - BasicInputAdapterPropertyDto basicInputAdapterPropertyDtos[]; + InputEventAdapterConfiguration inputEventAdapterConfiguration = new InputEventAdapterConfiguration(); + Map propertyMap = new HashMap<>(); if (transportType == TransportType.MQTT) { - basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[3]; + inputEventAdapterConfiguration.setType(OAUTH_MQTT_ADAPTER_TYPE); String topic; - if (isSharedWithAllTenants) { - topic = "+/" + deviceType + "/+/events"; + if (!StringUtils.isEmpty(eventTopicStructure)) { + if (isSharedWithAllTenants) { + topic = eventTopicStructure.replace("${deviceId}", "+") + .replace("${deviceType}", deviceType) + .replace("${tenantDomain}", "+"); + } else { + topic = eventTopicStructure.replace("${deviceId}", "+") + .replace("${deviceType}", deviceType) + .replace("${tenantDomain}", requestedTenantDomain); + } } else { - topic = requestedTenantDomain + "/" + deviceType + "/+/events"; + if (isSharedWithAllTenants) { + topic = "+/" + deviceType + "/+/events"; + } else { + topic = requestedTenantDomain + "/" + deviceType + "/+/events"; + } } - basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("topic", topic); - basicInputAdapterPropertyDtos[1] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_TRANSFORMER_TYPE - , MQTT_CONTENT_TRANSFORMER); - basicInputAdapterPropertyDtos[2] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_VALIDATOR_TYPE - , MQTT_CONTENT_VALIDATOR); + propertyMap.put("topic", topic); + propertyMap.put(MQTT_CONTENT_TRANSFORMER_TYPE, MQTT_CONTENT_TRANSFORMER); + propertyMap.put(MQTT_CONTENT_VALIDATOR_TYPE, MQTT_CONTENT_VALIDATOR); } else { - adapterType = THRIFT_ADAPTER_TYPE; - basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[1]; - basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("events.duplicated.in.cluster", "false"); + inputEventAdapterConfiguration.setType(THRIFT_ADAPTER_TYPE); + propertyMap.put("events.duplicated.in.cluster", "false"); } - String eventRecieverName = getReceiverName(deviceType, requestedTenantDomain, transportType); - if (receiverAdminServiceStub.getActiveEventReceiverConfiguration(eventRecieverName) == null) { + inputEventAdapterConfiguration.setProperties(propertyMap); + + if (eventReceiverService.getActiveEventReceiverConfiguration(receiverName) == null) { + EventReceiverConfiguration configuration = new EventReceiverConfiguration(); + configuration.setEventReceiverName(receiverName); + configuration.setToStreamName(streamName); + configuration.setToStreamVersion(version); + configuration.setFromAdapterConfiguration(inputEventAdapterConfiguration); if (transportType == TransportType.MQTT) { - receiverAdminServiceStub.deployJsonEventReceiverConfiguration(eventRecieverName, streamNameWithVersion - , adapterType, null, basicInputAdapterPropertyDtos, false); + JSONInputMapping jsonInputMapping = new JSONInputMapping(); + jsonInputMapping.setCustomMappingEnabled(false); + configuration.setInputMapping(jsonInputMapping); + eventReceiverService.deployEventReceiverConfiguration(configuration); } else { - receiverAdminServiceStub.deployWso2EventReceiverConfiguration(eventRecieverName, streamNameWithVersion - , adapterType, null, null, null, basicInputAdapterPropertyDtos, false, null); + WSO2EventInputMapping wso2EventInputMapping = new WSO2EventInputMapping(); + wso2EventInputMapping.setCustomMappingEnabled(false); + configuration.setInputMapping(wso2EventInputMapping); + eventReceiverService.deployEventReceiverConfiguration(configuration); } } - } finally { - cleanup(receiverAdminServiceStub); + } catch (EventReceiverConfigurationException e) { + log.error("Error while publishing event receiver" , e); + throw new EventReceiverConfigurationException(e); } + } - private void publishStreamDefinitons(String streamName, String version, String deviceType - , EventAttributeList eventAttributes) - throws RemoteException, UserStoreException, JWTClientException { - EventStreamAdminServiceStub eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub(); + private void publishStreamDefinitons(String streamName, String version, EventAttributeList eventAttributes) + throws MalformedStreamDefinitionException, EventStreamConfigurationException { + EventStreamService eventStreamService = DeviceMgtAPIUtils.getEventStreamService(); + try { - EventStreamDefinitionDto eventStreamDefinitionDto = new EventStreamDefinitionDto(); - eventStreamDefinitionDto.setName(streamName); - eventStreamDefinitionDto.setVersion(version); - EventStreamAttributeDto eventStreamAttributeDtos[] = - new EventStreamAttributeDto[eventAttributes.getList().size()]; - EventStreamAttributeDto metaStreamAttributeDtos[] = - new EventStreamAttributeDto[1]; - int i = 0; + StreamDefinition streamDefinition = new StreamDefinition(streamName, version); + + List payloadDataAttributes = new ArrayList<>(); for (Attribute attribute : eventAttributes.getList()) { - EventStreamAttributeDto eventStreamAttributeDto = new EventStreamAttributeDto(); - eventStreamAttributeDto.setAttributeName(attribute.getName()); - eventStreamAttributeDto.setAttributeType(attribute.getType().toString()); - eventStreamAttributeDtos[i] = eventStreamAttributeDto; - i++; + payloadDataAttributes.add(new org.wso2.carbon.databridge.commons.Attribute(attribute.getName(), + org.wso2.carbon.databridge.commons.AttributeType.valueOf(attribute.getType().name()))); } + streamDefinition.setPayloadData(payloadDataAttributes); + + List metaDataAttributes = new ArrayList<>(); + metaDataAttributes.add(new org.wso2.carbon.databridge.commons.Attribute(DEFAULT_DEVICE_ID_ATTRIBUTE, + org.wso2.carbon.databridge.commons.AttributeType.STRING)); + streamDefinition.setMetaData(metaDataAttributes); - EventStreamAttributeDto eventStreamAttributeDto = new EventStreamAttributeDto(); - eventStreamAttributeDto.setAttributeName(DEFAULT_DEVICE_ID_ATTRIBUTE); - eventStreamAttributeDto.setAttributeType(AttributeType.STRING.toString()); - metaStreamAttributeDtos[0] = eventStreamAttributeDto; - eventStreamDefinitionDto.setPayloadData(eventStreamAttributeDtos); - eventStreamDefinitionDto.setMetaData(metaStreamAttributeDtos); - String streamId = streamName + ":" + version; - if (eventStreamAdminServiceStub.getStreamDefinitionDto(streamId) != null) { - eventStreamAdminServiceStub.editEventStreamDefinitionAsDto(eventStreamDefinitionDto, streamId); + if (eventStreamService.getStreamDefinition(streamDefinition.getStreamId()) != null) { + eventStreamService.removeEventStreamDefinition(streamName, version); + eventStreamService.addEventStreamDefinition(streamDefinition); } else { - eventStreamAdminServiceStub.addEventStreamDefinitionAsDto(eventStreamDefinitionDto); + eventStreamService.addEventStreamDefinition(streamDefinition); } - } finally { - cleanup(eventStreamAdminServiceStub); + + } catch (MalformedStreamDefinitionException e) { + log.error("Error while initializing stream definition " , e); + throw new MalformedStreamDefinitionException(e); + } catch (EventStreamConfigurationException e) { + log.error("Error while configuring stream definition " , e); + throw new EventStreamConfigurationException(e); } } + /* -// private void publishEventStore(String streamName, String version, EventAttributeList eventAttributes) -// throws RemoteException, UserStoreException, JWTClientException, -// EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException { -// EventStreamPersistenceAdminServiceStub eventStreamPersistenceAdminServiceStub = -// DeviceMgtAPIUtils.getEventStreamPersistenceAdminServiceStub(); -// try { -// AnalyticsTable analyticsTable = new AnalyticsTable(); -// analyticsTable.setRecordStoreName(DEFAULT_EVENT_STORE_NAME); -// analyticsTable.setStreamVersion(version); -// analyticsTable.setTableName(streamName); -// analyticsTable.setMergeSchema(false); -// analyticsTable.setPersist(true); -// AnalyticsTableRecord analyticsTableRecords[] = new AnalyticsTableRecord[eventAttributes.getList().size() + 1]; -// int i = 0; -// for (Attribute attribute : eventAttributes.getList()) { -// AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord(); -// analyticsTableRecord.setColumnName(attribute.getName()); -// analyticsTableRecord.setColumnType(attribute.getType().toString().toUpperCase()); -// analyticsTableRecord.setFacet(false); -// analyticsTableRecord.setIndexed(false); -// analyticsTableRecord.setPersist(true); -// analyticsTableRecord.setPrimaryKey(false); -// analyticsTableRecord.setScoreParam(false); -// analyticsTableRecords[i] = analyticsTableRecord; -// i++; -// } -// AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord(); -// analyticsTableRecord.setColumnName(DEFAULT_META_DEVICE_ID_ATTRIBUTE); -// analyticsTableRecord.setColumnType(AttributeType.STRING.toString().toUpperCase()); -// analyticsTableRecord.setFacet(false); -// analyticsTableRecord.setIndexed(true); -// analyticsTableRecord.setPersist(true); -// analyticsTableRecord.setPrimaryKey(false); -// analyticsTableRecord.setScoreParam(false); -// analyticsTableRecords[i] = analyticsTableRecord; -// analyticsTable.setAnalyticsTableRecords(analyticsTableRecords); -// eventStreamPersistenceAdminServiceStub.addAnalyticsTable(analyticsTable); -// } finally { -// cleanup(eventStreamPersistenceAdminServiceStub); -// } -// } + */ + + private void publishEventStore(String streamName, String version, String publisherName) + throws EventPublisherConfigurationException { + + EventPublisherService eventPublisherService = DeviceMgtAPIUtils.getEventPublisherService(); - private void publishWebsocketPublisherDefinition(String streamNameWithVersion, String deviceType) - throws RemoteException, UserStoreException, JWTClientException { - EventPublisherAdminServiceStub eventPublisherAdminServiceStub = DeviceMgtAPIUtils - .getEventPublisherAdminServiceStub(); try { - String eventPublisherName = deviceType.trim().replace(" ", "_") + "_websocket_publisher"; - if (eventPublisherAdminServiceStub.getActiveEventPublisherConfiguration(eventPublisherName) == null) { - eventPublisherAdminServiceStub.deployJsonEventPublisherConfiguration(eventPublisherName - , streamNameWithVersion, DEFAULT_WEBSOCKET_PUBLISHER_ADAPTER_TYPE, null, null - , null, false); + if (eventPublisherService.getActiveEventPublisherConfiguration(publisherName) == null) { + EventPublisherConfiguration configuration = new EventPublisherConfiguration(); + configuration.setEventPublisherName(publisherName); + configuration.setFromStreamName(streamName); + configuration.setFromStreamVersion(version); + MapOutputMapping mapOutputMapping = new MapOutputMapping(); + mapOutputMapping.setCustomMappingEnabled(false); + configuration.setOutputMapping(mapOutputMapping); + OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration(); + outputEventAdapterConfiguration.setType("rdbms"); + Map staticProperties = new HashMap<>(); + staticProperties.put("datasource.name", "EVENT_DB"); + staticProperties.put("execution.mode", "insert"); + staticProperties.put("table.name", "table_" + publisherName.replace(".", "")); + outputEventAdapterConfiguration.setStaticProperties(staticProperties); + configuration.setProcessEnabled(true); + configuration.setToAdapterConfiguration(outputEventAdapterConfiguration); + eventPublisherService.deployEventPublisherConfiguration(configuration); } - } finally { - cleanup(eventPublisherAdminServiceStub); + + } catch (EventPublisherConfigurationException e) { + log.error("Error while publishing to rdbms store" , e); + throw new EventPublisherConfigurationException(e); + } + } + + private void publishWebsocketPublisherDefinition(String streamName, String version, String publisherName) + throws EventPublisherConfigurationException { + EventPublisherService eventPublisherService = DeviceMgtAPIUtils.getEventPublisherService(); + + try { + if (eventPublisherService.getActiveEventPublisherConfiguration(publisherName) == null) { + EventPublisherConfiguration configuration = new EventPublisherConfiguration(); + configuration.setEventPublisherName(publisherName); + configuration.setFromStreamName(streamName); + configuration.setFromStreamVersion(version); + JSONOutputMapping jsonOutputMapping = new JSONOutputMapping(); + jsonOutputMapping.setCustomMappingEnabled(false); + configuration.setOutputMapping(jsonOutputMapping); + OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration(); + outputEventAdapterConfiguration.setType("websocket-local"); + configuration.setToAdapterConfiguration(outputEventAdapterConfiguration); + eventPublisherService.deployEventPublisherConfiguration(configuration); + } + } catch (EventPublisherConfigurationException e) { + log.error("Error while publishing to websocket-local" , e); + throw new EventPublisherConfigurationException(e); } + } private BasicInputAdapterPropertyDto getBasicInputAdapterPropertyDto(String key, String value) { @@ -667,6 +731,13 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe return deviceType.replace(" ", "_").trim() + "-" + tenantDomain + "-" + transportType.toString() + "-receiver"; } + private String getReceiverName(String deviceType, String tenantDomain, TransportType transportType, String eventName) { + return eventName + "-" + getReceiverName(deviceType, tenantDomain, transportType); + } + + private String getPublisherName(String tenantDomain, String deviceType, String eventName) { + return eventName + "_" + tenantDomain.replace(".", "_") + "_" + deviceType; + } private void cleanup(Stub stub) { if (stub != null) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 9ffece7230..6d0696df84 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -37,33 +37,26 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl; import com.google.gson.Gson; +import io.entgra.application.mgt.common.ApplicationInstallResponse; +import io.entgra.application.mgt.common.SubscriptionType; +import io.entgra.application.mgt.common.exception.SubscriptionManagementException; import io.entgra.application.mgt.common.services.ApplicationManager; +import io.entgra.application.mgt.common.services.SubscriptionManager; +import io.entgra.application.mgt.core.util.HelperUtil; 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.json.JSONException; import org.json.JSONObject; +import org.wso2.carbon.apimgt.keymgt.extension.DCRResponse; +import org.wso2.carbon.apimgt.keymgt.extension.TokenRequest; +import org.wso2.carbon.apimgt.keymgt.extension.TokenResponse; +import org.wso2.carbon.apimgt.keymgt.extension.exception.KeyMgtException; +import org.wso2.carbon.apimgt.keymgt.extension.service.KeyMgtService; +import org.wso2.carbon.apimgt.keymgt.extension.service.KeyMgtServiceImpl; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.application.mgt.common.ApplicationInstallResponse; -import io.entgra.application.mgt.common.SubscriptionType; -import io.entgra.application.mgt.common.exception.SubscriptionManagementException; -import io.entgra.application.mgt.common.services.SubscriptionManager; -import io.entgra.application.mgt.core.util.HelperUtil; -import org.wso2.carbon.device.mgt.common.DeviceFilters; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.OperationLogFilters; -import org.wso2.carbon.device.mgt.common.MDMAppConstants; -import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.common.Feature; -import org.wso2.carbon.device.mgt.common.FeatureManager; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; -import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo; +import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; @@ -72,12 +65,8 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceData; import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshotWrapper; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceTypeNotFoundException; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException; -import org.wso2.carbon.device.mgt.common.exceptions.UnAuthorizedException; +import org.wso2.carbon.device.mgt.common.exceptions.*; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; @@ -91,6 +80,8 @@ import org.wso2.carbon.device.mgt.common.search.PropertyMap; import org.wso2.carbon.device.mgt.common.search.SearchContext; import org.wso2.carbon.device.mgt.common.type.mgt.DeviceStatus; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; +import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; @@ -103,19 +94,10 @@ import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService; -import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl; import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; -import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; -import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; -import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceCompliance; -import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationList; -import org.wso2.carbon.device.mgt.jaxrs.beans.OperationStatusBean; -import org.wso2.carbon.device.mgt.jaxrs.beans.ComplianceDeviceList; -import org.wso2.carbon.device.mgt.jaxrs.beans.OperationRequest; -import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList; -import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationUninstallation; +import org.wso2.carbon.device.mgt.jaxrs.beans.*; import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; @@ -128,29 +110,17 @@ import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerSer import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import javax.validation.Valid; -import javax.ws.rs.Consumes; import javax.validation.constraints.Size; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.Response; -import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.ArrayList; import java.util.Properties; import java.util.concurrent.ExecutionException; @@ -616,9 +586,13 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { Device persistedDevice = deviceManagementProviderService.getDevice(new DeviceIdentifier (deviceId, deviceType), true); persistedDevice.setName(device.getName()); - boolean response = deviceManagementProviderService.modifyEnrollment(persistedDevice); - return Response.status(Response.Status.CREATED).entity(response).build(); + System.out.println("This is rename device"); + boolean responseOfmodifyEnrollment = deviceManagementProviderService.modifyEnrollment(persistedDevice); + boolean responseOfDeviceNameChanged = deviceManagementProviderService.sendDeviceNameChangedNotification( + persistedDevice); + boolean response = responseOfmodifyEnrollment && responseOfDeviceNameChanged; + return Response.status(Response.Status.CREATED).entity(response).build(); } catch (DeviceManagementException e) { log.error("Error encountered while updating device of type : " + deviceType + " and " + "ID : " + deviceId); @@ -812,6 +786,32 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.OK).entity(device).build(); } + @POST + @Path("/enrollment/guide") + @Override + public Response sendEnrollmentGuide(String enrolmentGuide) { + if (log.isDebugEnabled()) { + log.debug("Sending enrollment invitation mail to existing user."); + } + DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); + if (!config.getEnrollmentGuideConfiguration().isEnabled()) { + String msg = "Sending enrollment guide config is not enabled."; + log.error(msg); + return Response.status(Response.Status.FORBIDDEN).entity(msg).build(); + } + DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); + try { + dms.sendEnrolmentGuide(enrolmentGuide); + return Response.status(Response.Status.OK).entity("Invitation mails have been sent.").build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred sending mail to group in enrollment guide"; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + } + + @POST @Path("/type/any/list") @Override @@ -883,19 +883,118 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } return Response.status(Response.Status.OK).entity(deviceInfo).build(); + } + @GET + @Path("/{type}/{id}/config") + @Override + public Response getDeviceConfiguration( + @PathParam("type") @Size(max = 45) String type, + @PathParam("id") @Size(max = 45) String id, + @HeaderParam("If-Modified-Since") String ifModifiedSince) { + + DeviceConfig deviceConfig = new DeviceConfig(); + deviceConfig.setDeviceId(id); + deviceConfig.setType(type); + + // find token validity time + DeviceManagementProviderService deviceManagementProviderService = + DeviceMgtAPIUtils.getDeviceManagementService(); + int validityTime = 3600; + // add scopes for event topics + List mqttEventTopicStructure = new ArrayList<>(); + try { + DeviceType deviceType = deviceManagementProviderService.getDeviceType(type); + if (deviceType != null) { + if (deviceType.getDeviceTypeMetaDefinition().isLongLivedToken()) { + validityTime = Integer.MAX_VALUE; + } + mqttEventTopicStructure = deviceType.getDeviceTypeMetaDefinition().getMqttEventTopicStructures(); + } else { + String msg = "Device not found, device id : " + id + ", device type : " + type; + log.error(msg); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + } catch (DeviceManagementException e) { + String msg = "Error occurred while retrieving device, device id : " + id + ", device type : " + type; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + + String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + String applicationName = type.replace(" ", "").replace("_", "") + + "_" + tenantDomain; + + KeyMgtService keyMgtService = new KeyMgtServiceImpl(); + try { + DCRResponse dcrResponse = keyMgtService.dynamicClientRegistration(applicationName, username, + "client_credentials", null, new String[] {"device_management"}, false, validityTime); + deviceConfig.setClientId(dcrResponse.getClientId()); + deviceConfig.setClientSecret(dcrResponse.getClientSecret()); + + StringBuilder scopes = new StringBuilder("device_" + type.replace(" ", "") + .replace("_", "") + "_" + id); + for (String topic : mqttEventTopicStructure) { + if (topic.contains("${deviceId}")) { + topic = topic.replace("${deviceId}", id); + } + topic = topic.replace("/",":"); +// scopes.append(" perm:topic:sub:".concat(topic)); + scopes.append(" perm:topic:pub:".concat(topic)); + } + + // add scopes for retrieve operation topic /tenantDomain/deviceType/deviceId/operation/# + scopes.append(" perm:topic:sub:" + tenantDomain + ":" + type + ":" + id + ":operation"); + + // add scopes for update operation /tenantDomain/deviceType/deviceId/update/operation + scopes.append(" perm:topic:pub:" + tenantDomain + ":" + type + ":" + id + ":update:operation"); + + TokenRequest tokenRequest = new TokenRequest(dcrResponse.getClientId(), dcrResponse.getClientSecret(), + null, scopes.toString(), "client_credentials", null, + null, null, null, validityTime); + TokenResponse tokenResponse = keyMgtService.generateAccessToken(tokenRequest); + deviceConfig.setAccessToken(tokenResponse.getAccessToken()); + deviceConfig.setRefreshToken(tokenResponse.getRefreshToken()); + + try { + deviceConfig.setPlatformConfiguration(deviceManagementProviderService.getConfiguration(type)); + } catch (DeviceManagementException e) { + String msg = "Error occurred while reading platform configurations token, device id : " + id + ", device type : " + type; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + + deviceConfig.setMqttGateway("tcp://" + System.getProperty("mqtt.broker.host") + ":" + System.getProperty("mqtt.broker.port")); + deviceConfig.setHttpGateway("http://" + System.getProperty("iot.gateway.host") + ":" + System.getProperty("iot.gateway.http.port")); + deviceConfig.setHttpsGateway("https://" + System.getProperty("iot.gateway.host") + ":" + System.getProperty("iot.gateway.https.port")); + + } catch (KeyMgtException e) { + String msg = "Error occurred while creating oauth application, device id : " + id + ", device type : " + type; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (org.wso2.carbon.apimgt.keymgt.extension.exception.BadRequestException e) { + String msg = "Error occurred while generating token, device id : " + id + ", device type : " + type; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + return Response.status(Response.Status.OK).entity(deviceConfig).build(); + } @GET - @Path("/{type}/{id}/features") + @Path("/device-type/{type}/features") @Override public Response getFeaturesOfDevice( @PathParam("type") @Size(max = 45) String type, - @PathParam("id") @Size(max = 45) String id, @HeaderParam("If-Modified-Since") String ifModifiedSince) { List features = new ArrayList<>(); DeviceManagementProviderService dms; try { - RequestValidationUtil.validateDeviceIdentifier(type, id); dms = DeviceMgtAPIUtils.getDeviceManagementService(); FeatureManager fm; try { @@ -909,8 +1008,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { features = fm.getFeatures(); } } catch (DeviceManagementException e) { - String msg = "Error occurred while retrieving the list of features of '" + type + "' device, which " + - "carries the id '" + id + "'"; + String msg = "Error occurred while retrieving the list of features of '" + type + "'"; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); @@ -1261,7 +1359,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { * @return {@link Response} object */ @GET - @Path("/{type}/{id}/getstatushistory") + @Path("/{type}/{id}/status-history") public Response getDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type, @PathParam("id") @Size(max = 45) String id) { //TODO check authorization for this @@ -1293,7 +1391,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { * @return {@link Response} object */ @GET - @Path("/{type}/{id}/getenrolmentstatushistory") + @Path("/{type}/{id}/enrolment-status-history") public Response getCurrentEnrolmentDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type, @PathParam("id") @Size(max = 45) String id) { //TODO check authorization for this or current enrolment should be based on for the enrolment associated with the user diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java index 8927ea533d..898ffb6c23 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java @@ -48,6 +48,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceTypesOfGroups; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException; @@ -66,6 +67,7 @@ import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; +import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; @@ -429,4 +431,20 @@ public class GroupManagementServiceImpl implements GroupManagementService { } } + @POST + @Path("/device-types") + @Override + public Response getGroupHasDeviceTypes(List identifiers) { + try { + DeviceTypesOfGroups deviceTypesOfGroups = DeviceMgtAPIUtils.getGroupManagementProviderService() + .getDeviceTypesOfGroups(identifiers); + + return Response.status(Response.Status.OK).entity(deviceTypesOfGroups).build(); + } catch (GroupManagementException e) { + String msg = "Only numbers can exists in a group ID or Invalid Group ID provided."; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java index f319d4ce48..37a08c7e00 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java @@ -50,15 +50,12 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.analytics.api.AnalyticsDataAPI; import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub; +import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub; import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.Utils; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.MonitoringOperation; -import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; +import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; @@ -96,8 +93,11 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventAttributeList; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub; +import org.wso2.carbon.event.publisher.core.EventPublisherService; import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub; +import org.wso2.carbon.event.receiver.core.EventReceiverService; import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub; +import org.wso2.carbon.event.stream.core.EventStreamService; import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; import org.wso2.carbon.identity.claim.metadata.mgt.dto.ClaimPropertyDTO; import org.wso2.carbon.identity.jwt.client.extension.JWTClient; @@ -112,11 +112,7 @@ import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; import org.wso2.carbon.registry.core.service.RegistryService; -import org.wso2.carbon.user.api.AuthorizationManager; -import org.wso2.carbon.user.api.RealmConfiguration; -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.api.*; import org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.mgt.common.UIPermissionNode; @@ -129,11 +125,7 @@ import javax.net.ssl.TrustManagerFactory; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; +import java.security.*; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.LinkedList; @@ -173,7 +165,7 @@ public class DeviceMgtAPIUtils { private static KeyStore trustStore; private static char[] keyStorePassword; -// private static IntegrationClientService integrationClientService; + // private static IntegrationClientService integrationClientService; private static MetadataManagementService metadataManagementService; private static WhiteLabelManagementService whiteLabelManagementService; private static OTPManagementService otpManagementService; @@ -605,6 +597,36 @@ public class DeviceMgtAPIUtils { return geoService; } + public static EventStreamService getEventStreamService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + EventStreamService + eventStreamService = (EventStreamService) ctx.getOSGiService(EventStreamService.class, null); + if (eventStreamService == null) { + throw new IllegalStateException("Event Stream Service has not been initialized."); + } + return eventStreamService; + } + + public static EventReceiverService getEventReceiverService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + EventReceiverService + eventReceiverService = (EventReceiverService) ctx.getOSGiService(EventReceiverService.class, null); + if (eventReceiverService == null) { + throw new IllegalStateException("Event Receiver Service has not been initialized."); + } + return eventReceiverService; + } + + public static EventPublisherService getEventPublisherService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + EventPublisherService + eventPublisherService = (EventPublisherService) ctx.getOSGiService(EventPublisherService.class, null); + if (eventPublisherService == null) { + throw new IllegalStateException("Event Receiver Service has not been initialized."); + } + return eventPublisherService; + } + public static AnalyticsDataAPI getAnalyticsDataAPI() { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); AnalyticsDataAPI analyticsDataAPI = @@ -666,10 +688,13 @@ public class DeviceMgtAPIUtils { // return eventsPublisherService; // } + public static String getStreamDefinition(String deviceType, String tenantDomain, String eventName) { + return getStreamDefinition(deviceType, tenantDomain) + "." + eventName; + } + public static String getStreamDefinition(String deviceType, String tenantDomain) { return STREAM_DEFINITION_PREFIX + tenantDomain + "." + deviceType.replace(" ", "."); } - public static EventStreamAdminServiceStub getEventStreamAdminServiceStub() throws AxisFault, UserStoreException, JWTClientException { EventStreamAdminServiceStub eventStreamAdminServiceStub = new EventStreamAdminServiceStub( diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java index 7b995660ad..db085319f0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java @@ -590,7 +590,7 @@ public class DeviceManagementServiceImplTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); Response response = this.deviceManagementService - .getFeaturesOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); + .getFeaturesOfDevice(TEST_DEVICE_TYPE, null); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); } @@ -601,7 +601,7 @@ public class DeviceManagementServiceImplTest { Mockito.when(this.deviceManagementProviderService.getFeatureManager(Mockito.anyString())) .thenThrow(new DeviceTypeNotFoundException()); Response response = this.deviceManagementService - .getFeaturesOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); + .getFeaturesOfDevice(TEST_DEVICE_TYPE, null); Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode()); Mockito.reset(this.deviceManagementProviderService); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml index bdc879561d..8e7e132f26 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml @@ -21,7 +21,7 @@ device-mgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java index 29bb7922e9..9a24b5c7f3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java @@ -44,6 +44,7 @@ public class PaginationRequest { private Map property = new HashMap<>(); private List statusList = new ArrayList<>(); private OperationLogFilters operationLogFilters = new OperationLogFilters(); + private List sortColumn = new ArrayList<>(); public OperationLogFilters getOperationLogFilters() { return operationLogFilters; } @@ -172,11 +173,38 @@ public class PaginationRequest { this.filter = filter; } + public void setSortColumn(List sortColumn) { this.sortColumn = sortColumn; } + + public List getSortColumn() { return sortColumn; } + + /** + * Convert SortColumns field parameter and splitting string into columnName and sortType + * + * @param sortColumns which is separated by a colon(:) and first will be the columnNane and the second will be type ASC or DESC, + * if there is no colon(:) detected, ASC will be default + * (Ex: sort=col1:ASC&sort=col2:DESC, sort=col1&sort=col2:DESC) + * @return sortColumnList as a list of sortColumn + */ + public void setSortColumns(List sortColumns) { + List sortColumnList = new ArrayList<>(); + SortColumn sortColumn; + String[] sorting; + for (String sortBy: sortColumns) { + sortColumn = new SortColumn(); + sorting = sortBy.split(":"); + sortColumn.setName(sorting[0]); + sortColumn.setType(sorting.length >= 2 && (sorting[1].equalsIgnoreCase("desc")) + ? SortColumn.types.DESC : SortColumn.types.ASC); + sortColumnList.add(sortColumn); + } + setSortColumn(sortColumnList); + } + @Override public String toString() { return "Device type '" + this.deviceType + "' Device Name '" + this.deviceName + "' row count: " + this.rowCount + " Owner role '" + this.ownerRole + "' owner pattern '" + this.ownerPattern + "' ownership " + this.ownership + "' Status '" + this.statusList + "' owner '" + this.owner + "' groupId: " + this.groupId - + " start index: " + this.startIndex; + + " start index: " + this.startIndex + ", SortColumns: " + this.sortColumn; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/SortColumn.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/SortColumn.java new file mode 100644 index 0000000000..8e6d4915ea --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/SortColumn.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2023, Entgra (pvt) Ltd. (https://entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.common; + +/** + * This class holds required parameters for a querying a sort by column in pagination. + * + */ +public class SortColumn { + String name; + SortColumn.types type; + + public enum types { + ASC, DESC + } + + /** + * ColumnName setter method + * @param name of the column + */ + public void setName(String name) { this.name = name; } + + /** + * get the name of the column + * @return name + */ + public String getName() { return name; } + + /** + * Column sort type + * @param type of sort as ASC or DESC + */ + public void setType(SortColumn.types type) { this.type = type; } + + /** + * get column sort type + * @return type of sort + */ + public SortColumn.types getType() { return type; } + + @Override + public String toString() { + return "Column Name - " + this.name + ", Type - " + this.type ; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceTypesOfGroups.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceTypesOfGroups.java new file mode 100644 index 0000000000..66bde2dc83 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceTypesOfGroups.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022, Entgra (pvt) Ltd. (https://entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.common.group.mgt; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; + +@ApiModel(value = "DeviceTypesOfGroups", description = "This class carries whether the groups has device type or not.") +public class DeviceTypesOfGroups implements Serializable { + + private static final long serialVersionUID = 5562356373277828099L; + @ApiModelProperty(name = "hasAndroid", value = "groups has Android devices.") + private boolean hasAndroid; + @ApiModelProperty(name = "id", value = "groups has iOS devices.") + private boolean hasIos; + @ApiModelProperty(name = "hasAndroid", value = "groups has Windows devices.") + private boolean hasWindows; + + public boolean isHasAndroid() { + return hasAndroid; + } + + public void setHasAndroid(boolean hasAndroid) { + this.hasAndroid = hasAndroid; + } + + public boolean isHasIos() { + return hasIos; + } + + public void setHasIos(boolean hasIos) { + this.hasIos = hasIos; + } + + public boolean isHasWindows() { + return hasWindows; + } + + public void setHasWindows(boolean hasWindows) { + this.hasWindows = hasWindows; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java index dcc7ff47cd..835f450bb7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java @@ -5,6 +5,7 @@ import org.wso2.carbon.device.mgt.common.InitialOperationConfig; import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; +import java.util.ArrayList; import java.util.List; public class DeviceTypeMetaDefinition { @@ -19,6 +20,10 @@ public class DeviceTypeMetaDefinition { private String description; private boolean isSharedWithAllTenants; + private List mqttEventTopicStructures; + + private boolean longLivedToken = false; + public String getDescription() { return description; } @@ -83,4 +88,20 @@ public class DeviceTypeMetaDefinition { public void setSharedWithAllTenants(boolean sharedWithAllTenants) { isSharedWithAllTenants = sharedWithAllTenants; } + + public List getMqttEventTopicStructures() { + return mqttEventTopicStructures; + } + + public void setMqttEventTopicStructures(List mqttEventTopicStructures) { + this.mqttEventTopicStructures = mqttEventTopicStructures; + } + + public boolean isLongLivedToken() { + return longLivedToken; + } + + public void setLongLivedToken(boolean longLivedToken) { + this.longLivedToken = longLivedToken; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml index 6176c74ff5..e0ce6e82a7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml @@ -103,6 +103,7 @@ org.wso2.carbon.ndatasource.core, org.wso2.carbon.ntask.core.*, org.wso2.carbon.ntask.common, + io.entgra.task.mgt.common.*, org.apache.commons.collections;version="${commons-collections.version.range}", org.wso2.carbon.email.sender.*, io.swagger.annotations.*;resolution:=optional, @@ -112,7 +113,9 @@ org.wso2.carbon.event.processor.stub, org.wso2.carbon.identity.jwt.client.extension.service, org.apache.commons.codec.binary, - io.entgra.server.bootup.heartbeat.beacon + io.entgra.server.bootup.heartbeat.beacon, + io.entgra.device.mgt.extensions.logger.*, + io.entgra.notification.logger.* !org.wso2.carbon.device.mgt.core.internal, @@ -347,6 +350,14 @@ okhttp compile + + org.wso2.carbon.devicemgt + io.entgra.task.mgt.common + + + org.wso2.carbon.devicemgt + io.entgra.notification.logger + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java index 9ba76f99fb..0d45a2efc1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java @@ -136,6 +136,7 @@ public final class DeviceManagementConstants { public static final String POLICY_VIOLATE_TEMPLATE = "policy-violating-notifier"; public static final String USER_WELCOME_TEMPLATE = "user-welcome"; public static final String DEFAULT_ENROLLMENT_TEMPLATE = "default-enrollment-invitation"; + public static final String ENROLLMENT_GUIDE_TEMPLATE = "enrollment-guide"; } public static final class OperationAttributes { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java index 0db16ff451..7d7c3ba853 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java @@ -24,4 +24,6 @@ public class Constants { public static final String URI_SEPARATOR = "/"; public static final String BASIC_AUTH_HEADER_PREFIX = "Basic "; public static final String BEARER = "Bearer "; + public static final String SEND_USERNAME = "SEND_USERNAME"; + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java index e2d44d3f0e..891e286339 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java @@ -25,6 +25,7 @@ import org.wso2.carbon.device.mgt.core.config.cache.BillingCacheConfiguration; import org.wso2.carbon.device.mgt.core.config.cache.CertificateCacheConfiguration; import org.wso2.carbon.device.mgt.core.config.cache.DeviceCacheConfiguration; import org.wso2.carbon.device.mgt.core.config.cache.GeoFenceCacheConfiguration; +import org.wso2.carbon.device.mgt.core.config.enrollment.guide.EnrollmentGuideConfiguration; import org.wso2.carbon.device.mgt.core.config.operation.timeout.OperationTimeoutConfiguration; import org.wso2.carbon.device.mgt.core.config.metadata.mgt.MetaDataConfiguration; import org.wso2.carbon.device.mgt.core.event.config.EventOperationTaskConfiguration; @@ -72,6 +73,7 @@ public final class DeviceManagementConfig { private DefaultRoles defaultRoles; private OperationTimeoutConfiguration operationTimeoutConfiguration; private MetaDataConfiguration metaDataConfiguration; + private EnrollmentGuideConfiguration enrollmentGuideConfiguration; @XmlElement(name = "ManagementRepository", required = true) public DeviceManagementConfigRepository getDeviceManagementConfigRepository() { @@ -276,5 +278,14 @@ public final class DeviceManagementConfig { public void setMetaDataConfiguration(MetaDataConfiguration metaDataConfiguration) { this.metaDataConfiguration = metaDataConfiguration; } + + @XmlElement(name = "EnrollmentGuideConfiguration", required = true) + public EnrollmentGuideConfiguration getEnrollmentGuideConfiguration() { + return enrollmentGuideConfiguration; + } + + public void setEnrollmentGuideConfiguration(EnrollmentGuideConfiguration enrollmentGuideConfiguration) { + this.enrollmentGuideConfiguration = enrollmentGuideConfiguration; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/enrollment/guide/EnrollmentGuideConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/enrollment/guide/EnrollmentGuideConfiguration.java new file mode 100644 index 0000000000..5f54cf79d4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/enrollment/guide/EnrollmentGuideConfiguration.java @@ -0,0 +1,30 @@ +package org.wso2.carbon.device.mgt.core.config.enrollment.guide; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "EnrollmentGuideConfiguration") +public class EnrollmentGuideConfiguration { + + private boolean isEnabled; + private String mail; + + @XmlElement(name = "Enable", required = true) + public boolean isEnabled() { + return isEnabled; + } + + public void setEnabled(boolean enabled) { + isEnabled = enabled; + } + + @XmlElement(name = "Mail", required = true) + public String getMail() { + return mail; + } + + public void setMail(String mail) { + this.mail = mail; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/HubspotChat.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/HubspotChat.java new file mode 100644 index 0000000000..728176e1db --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/HubspotChat.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 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 org.wso2.carbon.device.mgt.core.config.ui; + +import javax.xml.bind.annotation.XmlElement; + +public class HubspotChat { + private boolean isEnableHubspot; + private String trackingUrl; + private String accessToken; + private String senderActorId; + private long channelAccountId; + + @XmlElement(name = "EnableHubspot") + public boolean isEnableHubspot() { + return isEnableHubspot; + } + + public void setEnableHubspot(boolean enableHubspot) { + isEnableHubspot = enableHubspot; + } + + @XmlElement(name = "TrackingUrl") + public String getTrackingUrl() { + return trackingUrl; + } + + public void setTrackingUrl(String trackingUrl) { + this.trackingUrl = trackingUrl; + } + + @XmlElement(name = "AccessToken") + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + @XmlElement(name = "SenderActorId") + public String getSenderActorId() { + return senderActorId; + } + + public void setSenderActorId(String senderActorId) { + this.senderActorId = senderActorId; + } + @XmlElement(name = "ChannelAccountId") + public long getChannelAccountId() { + return channelAccountId; + } + + public void setChannelAccountId(long channelAccountId) { + this.channelAccountId = channelAccountId; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/UIConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/UIConfiguration.java index 551c1558ea..dca4a76a6b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/UIConfiguration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/UIConfiguration.java @@ -34,6 +34,7 @@ public class UIConfiguration { private int sessionTimeOut; private int loginCacheCapacity; private Billing billing; + private HubspotChat hubspotChat; @XmlElement(name = "AppRegistration", required=true) public AppRegistration getAppRegistration() { @@ -63,6 +64,14 @@ public class UIConfiguration { isSsoEnable = ssoEnable; } + @XmlElement(name = "HubspotChat", required = true) + public HubspotChat getHubspotChat() { + return hubspotChat; + } + + public void setHubspotChat(HubspotChat hubspotChat) { + this.hubspotChat = hubspotChat; + } @XmlElement(name = "Billing", required=true) public Billing getBilling() { return billing; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index 585074894d..b293798ba2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -409,7 +409,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } if (!HttpReportingUtil.isTrackerEnabled()) { if (log.isDebugEnabled()) { - log.info("Traccar is disabled"); + log.debug("Traccar is disabled"); } } } @@ -473,7 +473,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } if (!HttpReportingUtil.isTrackerEnabled()) { if (log.isDebugEnabled()) { - log.info("Traccar is disabled"); + log.debug("Traccar is disabled"); } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/MetadataManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/MetadataManagementServiceImpl.java index 2cdf4d7ad4..5ba8888301 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/MetadataManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/MetadataManagementServiceImpl.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.metadata.mgt; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; @@ -90,8 +91,14 @@ public class MetadataManagementServiceImpl implements MetadataManagementService } try { MetadataManagementDAOFactory.openConnection(); - return metadataDAO.getMetadata( - PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true), metaKey); + int tenantId; + if (metaKey.equals("EVALUATE_TENANTS")){ + // for getting evaluate tenant list to provide the live chat feature + tenantId = MultitenantConstants.SUPER_TENANT_ID; + } else { + tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + } + return metadataDAO.getMetadata(tenantId, metaKey); } catch (MetadataManagementDAOException e) { String msg = "Error occurred while retrieving the metadata entry for metaKey:" + metaKey; log.error(msg, e); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java index 3371f8d804..4770f9fee4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java @@ -18,8 +18,9 @@ package org.wso2.carbon.device.mgt.core.notification.mgt; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import io.entgra.device.mgt.extensions.logger.spi.EntgraLogger; +import io.entgra.notification.logger.DeviceLogContext; +import io.entgra.notification.logger.impl.EntgraDeviceLoggerImpl; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; @@ -45,8 +46,8 @@ import java.util.List; */ public class NotificationManagementServiceImpl implements NotificationManagementService { - private static final Log log = LogFactory.getLog(NotificationManagementServiceImpl.class); - + private static final EntgraLogger log = new EntgraDeviceLoggerImpl(NotificationManagementServiceImpl.class); + DeviceLogContext.Builder deviceLogContexBuilder = new DeviceLogContext.Builder(); private NotificationDAO notificationDAO; public NotificationManagementServiceImpl() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index 27882f4fbd..55e9279760 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.core.operation.mgt; +import com.google.gson.Gson; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -792,9 +793,7 @@ public class OperationManagerImpl implements OperationManager { if (dtoOperation != null) { long currentTime = Calendar.getInstance().getTime().getTime(); - log.info("Current timestamp:" + currentTime); long updatedTime = Timestamp.valueOf(dtoOperation.getReceivedTimeStamp()).getTime(); - log.info("Updated timestamp: " + updatedTime); // check if notnow frequency is met and set next pending operation if not, otherwise let notnow // operation to proceed diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java index 2ee7e32032..c1bd71a2a5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java @@ -32,31 +32,10 @@ import org.wso2.carbon.device.mgt.core.task.impl.DynamicPartitionedScheduleTask; import java.util.ArrayList; import java.util.List; -import java.util.Map; public class OperationTimeoutTask extends DynamicPartitionedScheduleTask { private static final Log log = LogFactory.getLog(OperationTimeoutTask.class); - private OperationTimeout operationTimeoutConfig; - - @Override - public void setProperties(Map properties) { - super.setProperties(properties); - String operationTimeoutTaskConfigStr = properties - .get(OperationTimeoutTaskManagerServiceImpl.OPERATION_TIMEOUT_TASK_CONFIG); - Gson gson = new Gson(); - operationTimeoutConfig = gson.fromJson(operationTimeoutTaskConfigStr, OperationTimeout.class); - } - - @Override - public String getProperty(String name) { - return super.getProperty(name); - } - - @Override - public void refreshContext() { - super.refreshContext(); - } @Override protected void setup() { @@ -65,12 +44,15 @@ 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))) { + "ALL".equals(operationTimeoutConfig.getDeviceTypes().get(0))) { try { List deviceTypeList = DeviceManagementDataHolder.getInstance() .getDeviceManagementProvider().getDeviceTypes(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index adfb67f003..3dedb8d551 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -645,6 +645,8 @@ public interface DeviceManagementProviderService { void sendEnrolmentInvitation(String templateName, EmailMetaInfo metaInfo) throws DeviceManagementException, ConfigurationManagementException; + void sendEnrolmentGuide(String enrolmentGuide) throws DeviceManagementException; + void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException, ConfigurationManagementException; FeatureManager getFeatureManager(String deviceType) throws DeviceTypeNotFoundException; @@ -1030,4 +1032,6 @@ public interface DeviceManagementProviderService { */ PaginationResult getDevicesDetails(PaginationRequest request, List devicesIds, String groupName) throws DeviceManagementException; + + Boolean sendDeviceNameChangedNotification(Device device) throws DeviceManagementException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 97f58b3f3c..6257e0b34d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -123,6 +123,7 @@ import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository; import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey; import org.wso2.carbon.device.mgt.core.cache.impl.BillingCacheManagerImpl; import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl; +import org.wso2.carbon.device.mgt.core.common.Constants; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO; @@ -146,6 +147,7 @@ import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataDAO; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOException; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; +import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.email.sender.core.ContentProviderInfo; @@ -196,6 +198,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv private final ApplicationDAO applicationDAO; private MetadataDAO metadataDAO; private final DeviceStatusDAO deviceStatusDAO; + int count = 0; public DeviceManagementProviderServiceImpl() { this.pluginRepository = new DeviceManagementPluginRepository(); @@ -442,7 +445,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv //Exception was not thrown due to being conflicted with non-traccar features } } else { - log.info("Traccar is disabled"); + if (log.isDebugEnabled()) { + log.debug("Traccar is disabled"); + } } //enroll Traccar device @@ -542,7 +547,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv //Exception was not thrown due to being conflicted with non-traccar features } } else { - log.info("Traccar is disabled"); + if (log.isDebugEnabled()) { + log.debug("Traccar is disabled"); + } } //enroll Traccar device return status; @@ -1549,6 +1556,25 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } } + @Override + public void sendEnrolmentGuide(String enrolmentGuide) throws DeviceManagementException { + + DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); + String recipientMail = config.getEnrollmentGuideConfiguration().getMail(); + Properties props = new Properties(); + props.setProperty("mail-subject", "[Enrollment Guide Triggered] (#" + ++count + ")"); + props.setProperty("enrollment-guide", enrolmentGuide); + + try { + EmailMetaInfo metaInfo = new EmailMetaInfo(recipientMail, props); + sendEnrolmentInvitation(DeviceManagementConstants.EmailAttributes.ENROLLMENT_GUIDE_TEMPLATE, metaInfo); + } catch (ConfigurationManagementException e) { + String msg = "Error occurred while sending the mail."; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + } + @Override public void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException, ConfigurationManagementException { @@ -4874,4 +4900,34 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv paginationResult.setData(populateAllDeviceInfo(subscribedDeviceDetails)); return paginationResult; } + + @Override + public Boolean sendDeviceNameChangedNotification(Device device) throws DeviceManagementException { + + try { + ProfileOperation operation = new ProfileOperation(); + operation.setCode(Constants.SEND_USERNAME); + operation.setType(Operation.Type.PROFILE); + operation.setPayLoad(device.getName()); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(device.getDeviceIdentifier()); + deviceIdentifier.setType(device.getType()); + + List deviceIdentifiers = new ArrayList<>(); + deviceIdentifiers.add(deviceIdentifier); + Activity activity; + activity = addOperation(device.getType(), operation, deviceIdentifiers); + + return activity != null; + } catch (OperationManagementException e) { + String msg = "Error occurred while sending operation"; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } catch (InvalidDeviceException e) { + String msg = "Invalid Device exception occurred"; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java index 5028f2560b..8f12f8a1df 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java @@ -41,6 +41,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceTypesOfGroups; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException; @@ -335,4 +336,11 @@ public interface GroupManagementProviderService { */ boolean isDeviceMappedToGroup(int groupId, DeviceIdentifier deviceIdentifier) throws GroupManagementException; + /** + * + * @param identifiers identifiers of groups + * @return whether the groups has android, iOS, Windows device types + * @throws GroupManagementException + */ + DeviceTypesOfGroups getDeviceTypesOfGroups(List identifiers) throws GroupManagementException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index aed9bc8782..9981333428 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -43,6 +43,7 @@ import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; @@ -51,6 +52,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.TrackerAlreadyExistException import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceTypesOfGroups; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException; @@ -79,6 +81,7 @@ import java.util.stream.Collectors; public class GroupManagementProviderServiceImpl implements GroupManagementProviderService { private static final Log log = LogFactory.getLog(GroupManagementProviderServiceImpl.class); + private static final String DEVICE_STATUS_REMOVED = "REMOVED"; private final GroupDAO groupDAO; private final DeviceDAO deviceDAO; @@ -1379,4 +1382,60 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid createGroupWithChildren(nextParentGroup, childrenGroups, requireGroupProps, tenantId, depth, counter); } } + @Override + public DeviceTypesOfGroups getDeviceTypesOfGroups(List identifiers) throws GroupManagementException { + DeviceTypesOfGroups deviceTypesOfGroups = new DeviceTypesOfGroups(); + List groupsIDs = new ArrayList<>(); + try { + for (String id : identifiers) { + groupsIDs.add(Integer.parseInt(id)); + } + + List deviceIDs = new ArrayList<>(); + List allDevices = new ArrayList<>(); + for (Integer groupID : groupsIDs) { + DeviceGroup deviceGroup = getGroup(groupID, false); + if (deviceGroup == null) { + String errorMessage = "Invalid Group ID provided."; + log.error(errorMessage); + throw new GroupManagementException(errorMessage); + } + List devices = getAllDevicesOfGroup(deviceGroup.getName(), false); + for (Device device : devices) { + if (!DEVICE_STATUS_REMOVED.equals(device.getEnrolmentInfo().getStatus().toString()) + && !deviceIDs.contains(device.getDeviceIdentifier())) { + deviceIDs.add(device.getDeviceIdentifier()); + allDevices.add(device); + } + } + } + + for (Device device : allDevices) { + if (DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID.equals(device.getType())) { + deviceTypesOfGroups.setHasAndroid(true); + break; + } + } + for (Device device : allDevices) { + if (DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS.equals(device.getType())) { + deviceTypesOfGroups.setHasIos(true); + break; + } + } + for (Device device : allDevices) { + if (DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS.equals(device.getType())) { + deviceTypesOfGroups.setHasWindows(true); + break; + } + } + + } catch (NumberFormatException e) { + String errorMessage = "Only numbers can exists in a group ID"; + log.error(errorMessage); + throw new GroupManagementException(errorMessage, e); + + } + + return deviceTypesOfGroups; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java index 5182fc3651..9d2e1ee7ce 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java @@ -37,7 +37,6 @@ import org.wso2.carbon.device.mgt.core.task.impl.DynamicPartitionedScheduleTask; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import java.util.Map; /** * This implements the Task service which monitors the device activity periodically & update the device-status if @@ -47,19 +46,8 @@ public class DeviceStatusMonitoringTask extends DynamicPartitionedScheduleTask { private static final Log log = LogFactory.getLog(DeviceStatusMonitoringTask.class); private String deviceType; - private DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig; private int deviceTypeId = -1; - @Override - public void setProperties(Map properties) { - super.setProperties(properties); - deviceType = properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE); - deviceTypeId = Integer.parseInt(properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE_ID)); - String deviceStatusTaskConfigStr = properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_STATUS_TASK_CONFIG); - Gson gson = new Gson(); - deviceStatusTaskPluginConfig = gson.fromJson(deviceStatusTaskConfigStr, DeviceStatusTaskPluginConfig.class); - } - @Override protected void setup() { } @@ -92,6 +80,11 @@ public class DeviceStatusMonitoringTask extends DynamicPartitionedScheduleTask { @Override public void executeDynamicTask() { + deviceType = getProperty(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE); + deviceTypeId = Integer.parseInt(getProperty(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE_ID)); + String deviceStatusTaskConfigStr = getProperty(DeviceStatusTaskManagerServiceImpl.DEVICE_STATUS_TASK_CONFIG); + Gson gson = new Gson(); + DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig = gson.fromJson(deviceStatusTaskConfigStr, DeviceStatusTaskPluginConfig.class); try { List enrolmentInfoTobeUpdated = new ArrayList<>(); List allDevicesForMonitoring = getAllDevicesForMonitoring(); @@ -102,10 +95,10 @@ public class DeviceStatusMonitoringTask extends DynamicPartitionedScheduleTask { EnrolmentInfo enrolmentInfo = monitoringData.getDevice().getEnrolmentInfo(); EnrolmentInfo.Status status = null; - if (lastUpdatedTime >= this.deviceStatusTaskPluginConfig + if (lastUpdatedTime >= deviceStatusTaskPluginConfig .getIdleTimeToMarkInactive()) { status = EnrolmentInfo.Status.INACTIVE; - } else if (lastUpdatedTime >= this.deviceStatusTaskPluginConfig + } else if (lastUpdatedTime >= deviceStatusTaskPluginConfig .getIdleTimeToMarkUnreachable()) { status = EnrolmentInfo.Status.UNREACHABLE; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java index 0c6f77c15d..a13031eabb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java @@ -48,7 +48,6 @@ import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManager; import java.util.List; -import java.util.Map; public class DeviceDetailsRetrieverTask extends DynamicPartitionedScheduleTask { @@ -56,14 +55,9 @@ public class DeviceDetailsRetrieverTask extends DynamicPartitionedScheduleTask { private String deviceType; private DeviceManagementProviderService deviceManagementProviderService; - @Override - public void setProperties(Map map) { - super.setProperties(map); - deviceType = map.get("DEVICE_TYPE"); - } - @Override public void executeDynamicTask() { + deviceType = getProperty("DEVICE_TYPE"); deviceManagementProviderService = DeviceManagementDataHolder.getInstance() .getDeviceManagementProvider(); OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementProviderService diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java index 0bbb59d2bd..ad3269be00 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java @@ -19,10 +19,11 @@ package org.wso2.carbon.device.mgt.core.task.impl; import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import io.entgra.task.mgt.common.constant.TaskMgtConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.ServerCtxInfo; import org.wso2.carbon.device.mgt.common.DynamicTaskContext; +import org.wso2.carbon.device.mgt.common.ServerCtxInfo; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.ntask.core.Task; @@ -37,11 +38,11 @@ public abstract class DynamicPartitionedScheduleTask implements Task { private Map properties; @Override - public void setProperties(Map properties) { + public final void setProperties(Map properties) { this.properties = properties; } - public String getProperty(String name) { + public final String getProperty(String name) { if (properties == null) { return null; } @@ -62,7 +63,7 @@ public abstract class DynamicPartitionedScheduleTask implements Task { } } } catch (HeartBeatManagementException e) { - log.error("Error Instantiating Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function." , e); + log.error("Error Instantiating Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function.", e); } setup(); } @@ -70,11 +71,41 @@ public abstract class DynamicPartitionedScheduleTask implements Task { @Override public final void execute() { refreshContext(); - executeDynamicTask(); + if (taskContext != null && taskContext.isPartitioningEnabled()) { + String localHashIndex = getProperty(TaskMgtConstants.Task.LOCAL_HASH_INDEX); + // These tasks are not dynamically scheduled. They are added via a config so scheduled in each node + // during the server startup + if (localHashIndex == null ) { + if (log.isDebugEnabled()) { + log.debug("Executing startup scheduled task (" + getTaskName() + ") with class: " + + this.getClass().getName()); + } + executeDynamicTask(); + return; + } + if (localHashIndex.equals(String.valueOf(taskContext.getServerHashIndex()))) { + if (log.isDebugEnabled()) { + log.debug("Executing dynamically scheduled task (" + getTaskName() + + ") for current server hash index: " + localHashIndex); + } + executeDynamicTask(); + } else { + if (log.isDebugEnabled()) { + log.debug("Ignoring execution of task (" + getTaskName() + + ") not belonging to current serer hash index: " + localHashIndex); + } + } + } else { + executeDynamicTask(); + } + } + + public String getTaskName() { + return getProperty(TaskMgtConstants.Task.LOCAL_TASK_NAME); } - public void refreshContext(){ - if(taskContext != null && taskContext.isPartitioningEnabled()) { + public void refreshContext() { + if (taskContext != null && taskContext.isPartitioningEnabled()) { try { updateContext(); } catch (HeartBeatManagementException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml index 5f934cdba4..8ecdd1dea7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml index 78d65441e7..dec22c688c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml @@ -23,7 +23,7 @@ device-mgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/pom.xml b/components/device-mgt/pom.xml index 01a2b61415..480b375d31 100644 --- a/components/device-mgt/pom.xml +++ b/components/device-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml index 62f34fec47..2b3cd78219 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt heartbeat-management - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ElectedCandidate.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ElectedCandidate.java index a3920d362b..99bfa8eba9 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ElectedCandidate.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ElectedCandidate.java @@ -19,13 +19,14 @@ package io.entgra.server.bootup.heartbeat.beacon.dto; import java.sql.Timestamp; +import java.util.ArrayList; import java.util.List; public class ElectedCandidate { private String serverUUID; private Timestamp timeOfElection; - private List acknowledgedTaskList = null; + private List acknowledgedTaskList = new ArrayList<>(); public List getAcknowledgedTaskList() { return acknowledgedTaskList; diff --git a/components/heartbeat-management/pom.xml b/components/heartbeat-management/pom.xml index 12b187f60b..272466b326 100644 --- a/components/heartbeat-management/pom.xml +++ b/components/heartbeat-management/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml index 2f143b316a..37b1f466a7 100644 --- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml +++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt identity-extensions - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml index 4ca291c299..e98ae105c3 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt identity-extensions - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/identity-extensions/pom.xml b/components/identity-extensions/pom.xml index 12f156ebe6..454b046f52 100644 --- a/components/identity-extensions/pom.xml +++ b/components/identity-extensions/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/components/logger/io.entgra.notification.logger/pom.xml b/components/logger/io.entgra.notification.logger/pom.xml new file mode 100644 index 0000000000..6044056d1d --- /dev/null +++ b/components/logger/io.entgra.notification.logger/pom.xml @@ -0,0 +1,88 @@ + + + + + 4.0.0 + + + org.wso2.carbon.devicemgt + logger + 5.0.21-SNAPSHOT + + + io.entgra.notification.logger + Entgra - Notification Logger + bundle + http://entgra.io + + + + org.wso2.carbon + org.wso2.carbon.logging + + + org.testng + testng + + + org.wso2.carbon.devicemgt + io.entgra.device.mgt.extensions.logger + + + + + 8 + 8 + UTF-8 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.device.mgt.version} + Device Notification Logger Bundle + + io.entgra.device.mgt.extensions.logger.*, + org.apache.commons.logging;version="[1.2,2)", + org.apache.log4j;version="[1.2,2)", + org.wso2.carbon.context;version="[4.4,5) + + + io.entgra.notification.logger.* + + + + + + + + \ No newline at end of file diff --git a/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/DeviceLogContext.java b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/DeviceLogContext.java new file mode 100644 index 0000000000..3becd28b9c --- /dev/null +++ b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/DeviceLogContext.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.notification.logger; + +import io.entgra.device.mgt.extensions.logger.LogContext; + +public class DeviceLogContext extends LogContext { + private final String deviceName; + private final String operationCode; + private final String deviceType; + private final String tenantID; + + private DeviceLogContext(Builder builder) { + this.operationCode = builder.operationCode; + this.deviceName = builder.deviceName; + this.deviceType = builder.deviceType; + this.tenantID = builder.tenantID; + } + + public String getTenantID() { + return tenantID; + } + + public String getDeviceName() { + return deviceName; + } + + public String getOperationCode() { + return operationCode; + } + + public String getDeviceType() { + return deviceType; + } + + + public static class Builder { + private String deviceName; + private String operationCode; + private String deviceType; + private String tenantID; + + public Builder() { + } + + public String getDeviceType() { + return deviceType; + } + + public Builder setDeviceType(String deviceType) { + this.deviceType = deviceType; + return this; + } + + public String getTenantID() { + return tenantID; + } + + public Builder setTenantID(String tenantID) { + this.tenantID = tenantID; + return this; + } + + public String getDeviceName() { + return deviceName; + } + + public Builder setDeviceName(String deviceName) { + this.deviceName = deviceName; + return this; + } + + public String getOperationCode() { + return operationCode; + } + + public Builder setOperationCode(String operationCode) { + this.operationCode = operationCode; + return this; + } + + public DeviceLogContext build() { + return new DeviceLogContext(this); + } + + } +} diff --git a/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/UserLogContext.java b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/UserLogContext.java new file mode 100644 index 0000000000..13702d570b --- /dev/null +++ b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/UserLogContext.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.notification.logger; + +import io.entgra.device.mgt.extensions.logger.LogContext; + +public class UserLogContext extends LogContext { + private final String userName; + private final String userEmail; + private final String metaInfo; + private final String tenantID; + + private UserLogContext(Builder builder) { + this.userEmail = builder.userEmail; + this.userName = builder.userName; + this.metaInfo = builder.metaInfo; + this.tenantID = builder.tenantID; + } + + public String getTenantID() { + return tenantID; + } + + public String getUserName() { + return userName; + } + + public String getUserEmail() { + return userEmail; + } + + public String getMetaInfo() { + return metaInfo; + } + + + public static class Builder { + private String userName; + private String userEmail; + private String metaInfo; + private String tenantID; + + public Builder() { + } + + public String getMetaInfo() { + return metaInfo; + } + + public Builder setMetaInfo(String metaInfo) { + this.metaInfo = metaInfo; + return this; + } + + public String getTenantID() { + return tenantID; + } + + public Builder setTenantID(String tenantID) { + this.tenantID = tenantID; + return this; + } + + public String getUserName() { + return userName; + } + + public Builder setUserName(String userName) { + this.userName = userName; + return this; + } + + public String getUserEmail() { + return userEmail; + } + + public Builder setUserEmail(String userEmail) { + this.userEmail = userEmail; + return this; + } + + public UserLogContext build() { + return new UserLogContext(this); + } + + } +} diff --git a/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/impl/EntgraDeviceLoggerImpl.java b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/impl/EntgraDeviceLoggerImpl.java new file mode 100644 index 0000000000..f1360ae6c3 --- /dev/null +++ b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/impl/EntgraDeviceLoggerImpl.java @@ -0,0 +1,294 @@ +/* + * Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.notification.logger.impl; + + +import io.entgra.device.mgt.extensions.logger.LogContext; +import io.entgra.device.mgt.extensions.logger.spi.EntgraLogger; +import io.entgra.notification.logger.DeviceLogContext; +import io.entgra.notification.logger.util.MDCContextUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.log4j.MDC; + + +public class EntgraDeviceLoggerImpl implements EntgraLogger { + + private static Log log = null; + + public EntgraDeviceLoggerImpl(Class clazz) { + log = LogFactory.getLog(clazz); + } + + @Override + public void info(Object object, LogContext logContext) { + } + + @Override + public void info(Object object, Throwable t, LogContext logContext) { + } + + @Override + public void debug(Object object, LogContext logContext) { + } + + @Override + public void debug(Object object, Throwable t, LogContext logContext) { + } + + @Override + public void error(Object object, LogContext logContext) { + } + + @Override + public void error(Object object, Throwable t, LogContext logContext) { + } + + @Override + public void fatal(Object object, LogContext logContext) { + } + + @Override + public void fatal(Object object, Throwable t, LogContext logContext) { + } + + @Override + public void trace(Object object, LogContext logContext) { + + } + + @Override + public void trace(Object object, Throwable t, LogContext logContext) { + + } + + @Override + public void warn(Object object, LogContext logContext) { + } + + @Override + public void warn(Object object, Throwable t, LogContext logContext) { + } + + public void info(String message) { + } + + public void info(String message, Throwable t) { + log.info(message, t); + } + + @Override + public void info(String message, LogContext logContext) { + DeviceLogContext deviceLogContext = (DeviceLogContext) logContext; + MDCContextUtil.populateDeviceMDCContext(deviceLogContext); + log.info(message); + } + + + public void debug(String message) { + log.debug(message); + } + + + public void debug(String message, Throwable t) { + log.debug(message, t); + } + + @Override + public void debug(String message, LogContext logContext) { + DeviceLogContext deviceLogContext = (DeviceLogContext) logContext; + MDCContextUtil.populateDeviceMDCContext(deviceLogContext); + log.debug(message); + } + + public void error(String message) { + log.error(message); + } + + + public void error(String message, Throwable t) { + log.error(message, t); + } + + @Override + public void error(String message, LogContext logContext) { + DeviceLogContext deviceLogContext = (DeviceLogContext) logContext; + MDCContextUtil.populateDeviceMDCContext(deviceLogContext); + log.error(message); + } + + @Override + public void error(String message, Throwable t, LogContext logContext) { + DeviceLogContext deviceLogContext = (DeviceLogContext) logContext; + MDCContextUtil.populateDeviceMDCContext(deviceLogContext); + log.error(message, t); + } + + + public void warn(String message) { + log.warn(message); + } + + + public void warn(String message, Throwable t) { + log.warn(message, t); + } + + @Override + public void warn(String message, LogContext logContext) { + DeviceLogContext deviceLogContext = (DeviceLogContext) logContext; + MDCContextUtil.populateDeviceMDCContext(deviceLogContext); + log.warn(message); + } + + @Override + public void warn(String message, Throwable t, LogContext logContext) { + DeviceLogContext deviceLogContext = (DeviceLogContext) logContext; + MDCContextUtil.populateDeviceMDCContext(deviceLogContext); + log.warn(message, t); + } + + + public void trace(String message) { + log.trace(message); + } + + + public void trace(String message, Throwable t) { + log.trace(message, t); + } + + @Override + public void trace(String message, LogContext logContext) { + DeviceLogContext deviceLogContext = (DeviceLogContext) logContext; + MDCContextUtil.populateDeviceMDCContext(deviceLogContext); + log.trace(message); + } + + + public void fatal(String message) { + log.fatal(message); + } + + + public void fatal(String message, Throwable t) { + log.fatal(message, t); + } + + @Override + public void fatal(String message, LogContext logContext) { + DeviceLogContext deviceLogContext = (DeviceLogContext) logContext; + MDCContextUtil.populateDeviceMDCContext(deviceLogContext); + log.fatal(message); + } + + @Override + public void debug(Object o) { + log.debug(o); + } + + @Override + public void debug(Object o, Throwable throwable) { + log.debug(o, throwable); + } + + @Override + public void error(Object o) { + log.error(o); + } + + @Override + public void error(Object o, Throwable throwable) { + log.error(o, throwable); + } + + @Override + public void fatal(Object o) { + log.fatal(0); + } + + @Override + public void fatal(Object o, Throwable throwable) { + log.fatal(0, throwable); + } + + @Override + public void info(Object o) { + log.info(o); + } + + @Override + public void info(Object o, Throwable throwable) { + log.info(o, throwable); + } + + @Override + public boolean isDebugEnabled() { + return log.isDebugEnabled(); + } + + @Override + public boolean isErrorEnabled() { + return log.isErrorEnabled(); + } + + @Override + public boolean isFatalEnabled() { + return log.isFatalEnabled(); + } + + @Override + public boolean isInfoEnabled() { + return log.isInfoEnabled(); + } + + @Override + public boolean isTraceEnabled() { + return log.isTraceEnabled(); + } + + @Override + public boolean isWarnEnabled() { + return log.isWarnEnabled(); + } + + @Override + public void trace(Object o) { + log.trace(o); + } + + @Override + public void trace(Object o, Throwable throwable) { + log.trace(o, throwable); + } + + @Override + public void warn(Object o) { + log.warn(o); + } + + @Override + public void warn(Object o, Throwable throwable) { + log.warn(o, throwable); + } + + @Override + public void clearLogContext() { + MDC.clear(); + } +} diff --git a/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/impl/EntgraUserLoggerImpl.java b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/impl/EntgraUserLoggerImpl.java new file mode 100644 index 0000000000..92beeabb2f --- /dev/null +++ b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/impl/EntgraUserLoggerImpl.java @@ -0,0 +1,294 @@ +/* + * Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.notification.logger.impl; + + +import io.entgra.device.mgt.extensions.logger.LogContext; +import io.entgra.device.mgt.extensions.logger.spi.EntgraLogger; +import io.entgra.notification.logger.UserLogContext; +import io.entgra.notification.logger.util.MDCContextUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.log4j.MDC; + + +public class EntgraUserLoggerImpl implements EntgraLogger { + + private static Log log = null; + + public EntgraUserLoggerImpl(Class clazz) { + log = LogFactory.getLog(clazz); + } + + @Override + public void info(Object object, LogContext logContext) { + } + + @Override + public void info(Object object, Throwable t, LogContext logContext) { + } + + @Override + public void debug(Object object, LogContext logContext) { + } + + @Override + public void debug(Object object, Throwable t, LogContext logContext) { + } + + @Override + public void error(Object object, LogContext logContext) { + } + + @Override + public void error(Object object, Throwable t, LogContext logContext) { + } + + @Override + public void fatal(Object object, LogContext logContext) { + } + + @Override + public void fatal(Object object, Throwable t, LogContext logContext) { + } + + @Override + public void trace(Object object, LogContext logContext) { + + } + + @Override + public void trace(Object object, Throwable t, LogContext logContext) { + + } + + @Override + public void warn(Object object, LogContext logContext) { + } + + @Override + public void warn(Object object, Throwable t, LogContext logContext) { + } + + public void info(String message) { + } + + public void info(String message, Throwable t) { + log.info(message, t); + } + + @Override + public void info(String message, LogContext logContext) { + UserLogContext userLogContext = (UserLogContext) logContext; + MDCContextUtil.populateUserMDCContext(userLogContext); + log.info(message); + } + + + public void debug(String message) { + log.debug(message); + } + + + public void debug(String message, Throwable t) { + log.debug(message, t); + } + + @Override + public void debug(String message, LogContext logContext) { + UserLogContext userLogContext = (UserLogContext) logContext; + MDCContextUtil.populateUserMDCContext(userLogContext); + log.debug(message); + } + + public void error(String message) { + log.error(message); + } + + + public void error(String message, Throwable t) { + log.error(message, t); + } + + @Override + public void error(String message, LogContext logContext) { + UserLogContext userLogContext = (UserLogContext) logContext; + MDCContextUtil.populateUserMDCContext(userLogContext); + log.error(message); + } + + @Override + public void error(String message, Throwable t, LogContext logContext) { + UserLogContext userLogContext = (UserLogContext) logContext; + MDCContextUtil.populateUserMDCContext(userLogContext); + log.error(message, t); + } + + + public void warn(String message) { + log.warn(message); + } + + + public void warn(String message, Throwable t) { + log.warn(message, t); + } + + @Override + public void warn(String message, LogContext logContext) { + UserLogContext userLogContext = (UserLogContext) logContext; + MDCContextUtil.populateUserMDCContext(userLogContext); + log.warn(message); + } + + @Override + public void warn(String message, Throwable t, LogContext logContext) { + UserLogContext userLogContext = (UserLogContext) logContext; + MDCContextUtil.populateUserMDCContext(userLogContext); + log.warn(message, t); + } + + + public void trace(String message) { + log.trace(message); + } + + + public void trace(String message, Throwable t) { + log.trace(message, t); + } + + @Override + public void trace(String message, LogContext logContext) { + UserLogContext userLogContext = (UserLogContext) logContext; + MDCContextUtil.populateUserMDCContext(userLogContext); + log.trace(message); + } + + + public void fatal(String message) { + log.fatal(message); + } + + + public void fatal(String message, Throwable t) { + log.fatal(message, t); + } + + @Override + public void fatal(String message, LogContext logContext) { + UserLogContext userLogContext = (UserLogContext) logContext; + MDCContextUtil.populateUserMDCContext(userLogContext); + log.fatal(message); + } + + @Override + public void debug(Object o) { + log.debug(o); + } + + @Override + public void debug(Object o, Throwable throwable) { + log.debug(o, throwable); + } + + @Override + public void error(Object o) { + log.error(o); + } + + @Override + public void error(Object o, Throwable throwable) { + log.error(o, throwable); + } + + @Override + public void fatal(Object o) { + log.fatal(0); + } + + @Override + public void fatal(Object o, Throwable throwable) { + log.fatal(0, throwable); + } + + @Override + public void info(Object o) { + log.info(o); + } + + @Override + public void info(Object o, Throwable throwable) { + log.info(o, throwable); + } + + @Override + public boolean isDebugEnabled() { + return log.isDebugEnabled(); + } + + @Override + public boolean isErrorEnabled() { + return log.isErrorEnabled(); + } + + @Override + public boolean isFatalEnabled() { + return log.isFatalEnabled(); + } + + @Override + public boolean isInfoEnabled() { + return log.isInfoEnabled(); + } + + @Override + public boolean isTraceEnabled() { + return log.isTraceEnabled(); + } + + @Override + public boolean isWarnEnabled() { + return log.isWarnEnabled(); + } + + @Override + public void trace(Object o) { + log.trace(o); + } + + @Override + public void trace(Object o, Throwable throwable) { + log.trace(o, throwable); + } + + @Override + public void warn(Object o) { + log.warn(o); + } + + @Override + public void warn(Object o, Throwable throwable) { + log.warn(o, throwable); + } + + @Override + public void clearLogContext() { + MDC.clear(); + } +} diff --git a/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/util/MDCContextUtil.java b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/util/MDCContextUtil.java new file mode 100644 index 0000000000..fd78c26dba --- /dev/null +++ b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/util/MDCContextUtil.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.notification.logger.util; + +import io.entgra.notification.logger.DeviceLogContext; +import io.entgra.notification.logger.UserLogContext; +import org.apache.log4j.MDC; + +public final class MDCContextUtil { + + public static void populateDeviceMDCContext(final DeviceLogContext mdcContext) { + if (mdcContext.getDeviceName() != null) { + MDC.put("DeviceName", mdcContext.getDeviceName()); + } + if (mdcContext.getDeviceType() != null) { + MDC.put("DeviceType", mdcContext.getDeviceType()); + } + if (mdcContext.getOperationCode() != null) { + MDC.put("OperationCode", mdcContext.getOperationCode()); + } + if (mdcContext.getTenantID() != null) { + MDC.put("TenantId", mdcContext.getTenantID()); + } + } + + public static void populateUserMDCContext(final UserLogContext mdcContext) { + if (mdcContext.getUserName() != null) { + MDC.put("UserName", mdcContext.getUserName()); + } + if (mdcContext.getUserEmail() != null) { + MDC.put("UserEmail", mdcContext.getUserEmail()); + } + if (mdcContext.getMetaInfo() != null) { + MDC.put("MetaInfo", mdcContext.getMetaInfo()); + } + if (mdcContext.getTenantID() != null) { + MDC.put("TenantId", mdcContext.getTenantID()); + } + } +} + + diff --git a/components/logger/io.entgra.notification.logger/src/test/resources/log4j.properties b/components/logger/io.entgra.notification.logger/src/test/resources/log4j.properties new file mode 100644 index 0000000000..b174b35e36 --- /dev/null +++ b/components/logger/io.entgra.notification.logger/src/test/resources/log4j.properties @@ -0,0 +1,32 @@ +# +# Copyright 2023 Entgra Pvt. Ltd.. (http://entgra.io) +# +# Licensed 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. +# + +# +# This is the log4j configuration file used by Entgra Pvt. Ltd. +# +# IMPORTANT : Please do not remove or change the names of any +# of the Appenders defined here. The layout pattern & log file +# can be changed using the WSO2 Carbon Management Console, and those +# settings will override the settings in this file. +# + +log4j.rootLogger=DEBUG, STD_OUT + +# Redirect log messages to console +log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender +log4j.appender.STD_OUT.Target=System.out +log4j.appender.STD_OUT.layout=org.apache.log4j.PatternLayout +log4j.appender.STD_OUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n diff --git a/components/logger/pom.xml b/components/logger/pom.xml new file mode 100644 index 0000000000..f0884c2238 --- /dev/null +++ b/components/logger/pom.xml @@ -0,0 +1,46 @@ + + + + 4.0.0 + + + carbon-devicemgt + org.wso2.carbon.devicemgt + 5.0.21-SNAPSHOT + ../../pom.xml + + + logger + pom + Entgra - Notification Logger Component + http://entgra.io + + + io.entgra.notification.logger + + + + 8 + 8 + UTF-8 + + + \ No newline at end of file diff --git a/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml index adbad363b8..d20a058c01 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml @@ -3,7 +3,7 @@ org.wso2.carbon.devicemgt policy-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml index 5ea8b324a7..ae24f2c103 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml @@ -3,7 +3,7 @@ org.wso2.carbon.devicemgt policy-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml index e37d88532b..065e6db69c 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt policy-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml index be0b657d10..2d4cb3f782 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt policy-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index 66a71a8426..13e8665102 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -1038,7 +1038,7 @@ public class PolicyManagerImpl implements PolicyManager { .getInstance().getDeviceManagementService(); List allDevices; try { - allDevices = deviceManagementService.getAllDevices(); + allDevices = deviceManagementService.getAllDevices(false); } catch (DeviceManagementException e) { throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" + policyId + ")", e); diff --git a/components/policy-mgt/pom.xml b/components/policy-mgt/pom.xml index c7893323ec..8c0bc9058e 100644 --- a/components/policy-mgt/pom.xml +++ b/components/policy-mgt/pom.xml @@ -23,7 +23,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/components/task-mgt/pom.xml b/components/task-mgt/pom.xml new file mode 100755 index 0000000000..f46835f8be --- /dev/null +++ b/components/task-mgt/pom.xml @@ -0,0 +1,39 @@ + + + + + + org.wso2.carbon.devicemgt + carbon-devicemgt + 5.0.21-SNAPSHOT + ../../pom.xml + + + 4.0.0 + task-mgt + pom + Entgra IoT - Task Management Component + http://entgra.io + + + task-manager + task-watcher + + + \ No newline at end of file diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/pom.xml b/components/task-mgt/task-manager/io.entgra.task.mgt.common/pom.xml new file mode 100755 index 0000000000..39551beebb --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/pom.xml @@ -0,0 +1,54 @@ + + + + + task-manager + org.wso2.carbon.devicemgt + 5.0.21-SNAPSHOT + ../pom.xml + + + 4.0.0 + io.entgra.task.mgt.common + bundle + Entgra IoT - Task Management Common + Entgra IoT - Task Management Common + https://entgra.io + + + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.device.mgt.version} + Task Management Common Bundle + + io.entgra.task.mgt.common.* + + + + + + + \ No newline at end of file diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/bean/DynamicTask.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/bean/DynamicTask.java new file mode 100755 index 0000000000..ece8d4dc26 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/bean/DynamicTask.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.common.bean; + +import java.util.Map; + +public class DynamicTask { + + private int dynamicTaskId; + private String name; + private String cronExpression; + private boolean isEnabled; + private int tenantId; + private String taskClassName; + private Map properties; + + public int getDynamicTaskId() { + return dynamicTaskId; + } + + public void setDynamicTaskId(int dynamicTaskId) { + this.dynamicTaskId = dynamicTaskId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCronExpression() { + return cronExpression; + } + + public void setCronExpression(String cronExpression) { + this.cronExpression = cronExpression; + } + + public boolean isEnabled() { + return isEnabled; + } + + public void setEnabled(boolean enable) { + isEnabled = enable; + } + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public String getTaskClassName() { + return taskClassName; + } + + public void setTaskClassName(String taskClassName) { + this.taskClassName = taskClassName; + } + + public Map getProperties() { + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } + +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/constant/TaskMgtConstants.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/constant/TaskMgtConstants.java new file mode 100755 index 0000000000..2ffe960964 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/constant/TaskMgtConstants.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.common.constant; + +public class TaskMgtConstants { + public static final class DataSourceProperties { + private DataSourceProperties() { + throw new AssertionError(); + } + + public static final String DB_CHECK_QUERY = "SELECT * FROM DM_DEVICE"; + public static final String TASK_CONFIG_XML_NAME = "task-mgt-config.xml"; + } + + public static final class DataBaseTypes { + private DataBaseTypes() { + throw new AssertionError(); + } + + public static final String DB_TYPE_MYSQL = "MySQL"; + public static final String DB_TYPE_ORACLE = "Oracle"; + public static final String DB_TYPE_MSSQL = "Microsoft SQL Server"; + public static final String DB_TYPE_DB2 = "DB2"; + public static final String DB_TYPE_H2 = "H2"; + public static final String DB_TYPE_POSTGRESQL = "PostgreSQL"; + } + + public static final class Task { + + public static final String DYNAMIC_TASK_TYPE = "DYNAMIC_TASK"; + public static final String NAME_SEPARATOR = "_"; + public static final String PROPERTY_KEY_COLUMN_NAME = "PROPERTY_NAME"; + public static final String PROPERTY_VALUE_COLUMN_NAME = "PROPERTY_VALUE"; + public static final String TENANT_ID_PROP = "__TENANT_ID_PROP__"; + public static final String LOCAL_HASH_INDEX = "__LOCAL_HASH_INDEX__"; + public static final String LOCAL_TASK_NAME = "__LOCAL_TASK_NAME__"; + } +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/IllegalTransactionStateException.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/IllegalTransactionStateException.java new file mode 100755 index 0000000000..4c4c996c59 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/IllegalTransactionStateException.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.common.exception; + +public class IllegalTransactionStateException extends RuntimeException { + + private static final long serialVersionUID = -3151279331929070297L; + + public IllegalTransactionStateException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public IllegalTransactionStateException(String message, Throwable cause) { + super(message, cause); + } + + public IllegalTransactionStateException(String msg) { + super(msg); + } + + public IllegalTransactionStateException() { + super(); + } + + public IllegalTransactionStateException(Throwable cause) { + super(cause); + } + +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskManagementDAOException.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskManagementDAOException.java new file mode 100755 index 0000000000..9b683dba20 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskManagementDAOException.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.common.exception; + +public class TaskManagementDAOException extends Exception { + + public TaskManagementDAOException(String msg) { + super(msg); + } + + public TaskManagementDAOException(String msg, Exception e) { + super(msg, e); + } + + +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskManagementException.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskManagementException.java new file mode 100755 index 0000000000..d9705e6438 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskManagementException.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.common.exception; + +public class TaskManagementException extends Exception { + + public TaskManagementException(String msg) { + super(msg); + } + + public TaskManagementException(String msg, Exception e) { + super(msg, e); + } +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskNotFoundException.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskNotFoundException.java new file mode 100755 index 0000000000..2d2f568fe2 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskNotFoundException.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.common.exception; + +/** + * Represents the exception thrown during validating the request. + */ +public class TaskNotFoundException extends Exception { + + public TaskNotFoundException(String message) { + super(message); + } + + public TaskNotFoundException(String message, Exception ex) { + super(message, ex); + } + +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TransactionManagementException.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TransactionManagementException.java new file mode 100755 index 0000000000..5e43237e43 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TransactionManagementException.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.common.exception; + +public class TransactionManagementException extends Exception { + + private static final long serialVersionUID = -3151279321929070297L; + + public TransactionManagementException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public TransactionManagementException(String message, Throwable cause) { + super(message, cause); + } + + public TransactionManagementException(String msg) { + super(msg); + } + + public TransactionManagementException() { + super(); + } + + public TransactionManagementException(Throwable cause) { + super(cause); + } + +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/UnsupportedDatabaseEngineException.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/UnsupportedDatabaseEngineException.java new file mode 100755 index 0000000000..a29f954e12 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/UnsupportedDatabaseEngineException.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.common.exception; + +/** + * This runtime exception will be thrown if the server has configured with unsupported DB engine. + */ +public class UnsupportedDatabaseEngineException extends RuntimeException { + + private static final long serialVersionUID = -3151279311929070297L; + + public UnsupportedDatabaseEngineException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public UnsupportedDatabaseEngineException(String message, Throwable cause) { + super(message, cause); + } + + public UnsupportedDatabaseEngineException(String msg) { + super(msg); + } + + public UnsupportedDatabaseEngineException() { + super(); + } + + public UnsupportedDatabaseEngineException(Throwable cause) { + super(cause); + } + +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/spi/TaskManagementService.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/spi/TaskManagementService.java new file mode 100755 index 0000000000..fac557e0bd --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/spi/TaskManagementService.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.common.spi; + +import io.entgra.task.mgt.common.exception.TaskNotFoundException; +import io.entgra.task.mgt.common.exception.TaskManagementException; +import io.entgra.task.mgt.common.bean.DynamicTask; + +import java.util.List; + +public interface TaskManagementService { + + void init() throws TaskManagementException; + + void createTask(DynamicTask dynamicTask) throws TaskManagementException; + + void updateTask(int dynamicTaskId, DynamicTask dynamicTask) throws TaskManagementException, TaskNotFoundException; + + void toggleTask(int dynamicTaskId, boolean isEnabled) throws TaskManagementException, TaskNotFoundException; + + void deleteTask(int dynamicTaskId) throws TaskManagementException, TaskNotFoundException; + + List getAllDynamicTasks() throws TaskManagementException; + + DynamicTask getDynamicTaskById(int dynamicTaskId) throws TaskManagementException; + + List getActiveDynamicTasks() throws TaskManagementException; +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/pom.xml b/components/task-mgt/task-manager/io.entgra.task.mgt.core/pom.xml new file mode 100755 index 0000000000..6eeba4c8bc --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/pom.xml @@ -0,0 +1,139 @@ + + + + + + org.wso2.carbon.devicemgt + task-manager + 5.0.21-SNAPSHOT + ../pom.xml + + + 4.0.0 + io.entgra.task.mgt.core + bundle + Entgra IoT - Task manager Core + Entgra IoT - Task manager Core + http://entgra.io + + + + + org.apache.felix + maven-scr-plugin + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.device.mgt.version} + Task Management Core Bundle + io.entgra.task.mgt.core.internal + + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.apache.commons.logging, + org.wso2.carbon.ndatasource.core, + org.w3c.dom, + javax.xml.bind.annotation, + javax.xml.bind, + javax.sql, + javax.naming, + io.entgra.task.mgt.common.*, + org.wso2.carbon.utils.*, + org.wso2.carbon.ntask.core.*, + org.wso2.carbon.ntask.common, + org.wso2.carbon.device.mgt.common.*, + org.wso2.carbon.context, + org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", + org.apache.commons.codec.digest;version="${commons-codec.wso2.osgi.version.range}", + io.entgra.server.bootup.heartbeat.beacon.dto, + io.entgra.server.bootup.heartbeat.beacon.exception, + io.entgra.server.bootup.heartbeat.beacon.service, + + + !io.entgra.task.mgt.core.internal, + io.entgra.task.mgt.core.* + + + + + + + + + + org.eclipse.osgi + org.eclipse.osgi + provided + + + org.eclipse.osgi + org.eclipse.osgi.services + provided + + + org.wso2.carbon + org.wso2.carbon.ndatasource.core + provided + + + org.wso2.carbon.devicemgt + io.entgra.task.mgt.common + provided + + + org.wso2.carbon + org.wso2.carbon.logging + provided + + + org.wso2.carbon + org.wso2.carbon.utils + provided + + + commons-codec.wso2 + commons-codec + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + org.wso2.carbon.devicemgt + io.entgra.server.bootup.heartbeat.beacon + provided + + + + + org.wso2.carbon.commons + org.wso2.carbon.ntask.core + provided + + + + \ No newline at end of file diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskConfigurationManager.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskConfigurationManager.java new file mode 100755 index 0000000000..2779a07ff9 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskConfigurationManager.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.config; + +import io.entgra.task.mgt.common.constant.TaskMgtConstants; +import io.entgra.task.mgt.common.exception.TaskManagementException; +import io.entgra.task.mgt.core.util.TaskManagementUtil; +import org.w3c.dom.Document; +import org.wso2.carbon.utils.CarbonUtils; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import java.io.File; + +/** + * Class responsible for the task mgt configuration initialization. + */ +public class TaskConfigurationManager { + + private TaskManagementConfig taskManagementConfig; + private static volatile TaskConfigurationManager taskConfigurationManager; + + private static final String TASK_MGT_CONFIG_PATH = + CarbonUtils.getCarbonConfigDirPath() + File.separator + + TaskMgtConstants.DataSourceProperties.TASK_CONFIG_XML_NAME; + + public static TaskConfigurationManager getInstance() { + if (taskConfigurationManager == null) { + synchronized (TaskConfigurationManager.class) { + if (taskConfigurationManager == null) { + taskConfigurationManager = new TaskConfigurationManager(); + } + } + } + return taskConfigurationManager; + } + + public synchronized void initConfig() throws TaskManagementException { + try { + File taskMgtConfig = new File(TASK_MGT_CONFIG_PATH); + Document doc = TaskManagementUtil.convertToDocument(taskMgtConfig); + + /* Un-marshaling Device Management configuration */ + JAXBContext cdmContext = JAXBContext.newInstance(TaskManagementConfig.class); + Unmarshaller unmarshaller = cdmContext.createUnmarshaller(); + //unmarshaller.setSchema(getSchema()); + this.taskManagementConfig = (TaskManagementConfig) unmarshaller.unmarshal(doc); + } catch (JAXBException e) { + throw new TaskManagementException("Error occurred while initializing Data Source config", e); + } + } + + public TaskManagementConfig getTaskManagementConfig() throws TaskManagementException { + if (taskManagementConfig == null) { + initConfig(); + } + return taskManagementConfig; + } + + public void setTaskManagementConfig(TaskManagementConfig taskManagementConfig) { + this.taskManagementConfig = taskManagementConfig; + } +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskManagementConfig.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskManagementConfig.java new file mode 100755 index 0000000000..2b3ae468ac --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskManagementConfig.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.config; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Represents Task Mgt configuration. + */ +@XmlRootElement(name = "TaskMgtConfiguration") +@SuppressWarnings("unused") +public final class TaskManagementConfig { + + private TaskManagementConfigRepository taskMgtConfigRepository; + private boolean isTaskWatcherEnabled; + + @XmlElement(name = "ManagementRepository", required = true) + public TaskManagementConfigRepository getTaskMgtConfigRepository() { + return taskMgtConfigRepository; + } + + public void setTaskMgtConfigRepository(TaskManagementConfigRepository taskMgtConfigRepository) { + this.taskMgtConfigRepository = taskMgtConfigRepository; + } + + @XmlElement(name = "TaskWatcherEnable", required = true) + public boolean isTaskWatcherEnabled() { + return isTaskWatcherEnabled; + } + + public void setTaskWatcherEnabled(boolean enabled) { + this.isTaskWatcherEnabled = enabled; + } +} + diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskManagementConfigRepository.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskManagementConfigRepository.java new file mode 100755 index 0000000000..a81617f738 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskManagementConfigRepository.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.config; + +import io.entgra.task.mgt.core.config.datasource.DataSourceConfig; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Class for holding management repository data. + */ +@XmlRootElement(name = "ManagementRepository") +public class TaskManagementConfigRepository { + + private DataSourceConfig dataSourceConfig; + + @XmlElement(name = "DataSourceConfiguration", required = true) + public DataSourceConfig getDataSourceConfig() { + return dataSourceConfig; + } + + public void setDataSourceConfig(DataSourceConfig dataSourceConfig) { + this.dataSourceConfig = dataSourceConfig; + } + +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/datasource/DataSourceConfig.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/datasource/DataSourceConfig.java new file mode 100755 index 0000000000..b4c4d9fc2d --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/datasource/DataSourceConfig.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.config.datasource; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Class for holding data source configuration in task-mgt-config.xml at parsing with JAXB. + */ +@XmlRootElement(name = "DataSourceConfiguration") +public class DataSourceConfig { + + private JNDILookupDefinition jndiLookupDefinition; + + @XmlElement(name = "JndiLookupDefinition", required = true) + public JNDILookupDefinition getJndiLookupDefinition() { + return jndiLookupDefinition; + } + + public void setJndiLookupDefinition(JNDILookupDefinition jndiLookupDefinition) { + this.jndiLookupDefinition = jndiLookupDefinition; + } + +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/datasource/JNDILookupDefinition.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/datasource/JNDILookupDefinition.java new file mode 100755 index 0000000000..5101af8d49 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/datasource/JNDILookupDefinition.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.config.datasource; + +import javax.xml.bind.annotation.*; +import java.util.List; + +/** + * Class for hold JndiLookupDefinition of task-mgt-config.xml at parsing with JAXB. + */ +@XmlRootElement(name = "JndiLookupDefinition") +public class JNDILookupDefinition { + + private String jndiName; + private List jndiProperties; + + @XmlElement(name = "Name", required = false) + public String getJndiName() { + return jndiName; + } + + public void setJndiName(String jndiName) { + this.jndiName = jndiName; + } + + @XmlElementWrapper(name = "Environment", required = false) + @XmlElement(name = "Property", nillable = false) + public List getJndiProperties() { + return jndiProperties; + } + + public void setJndiProperties(List jndiProperties) { + this.jndiProperties = jndiProperties; + } + + @XmlRootElement(name = "Property") + public static class JNDIProperty { + + private String name; + + private String value; + + @XmlAttribute(name = "Name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } + +} + diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/DynamicTaskDAO.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/DynamicTaskDAO.java new file mode 100755 index 0000000000..317870dba1 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/DynamicTaskDAO.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.dao; + +import io.entgra.task.mgt.common.bean.DynamicTask; +import io.entgra.task.mgt.common.exception.TaskManagementDAOException; + +import java.util.List; + +/** + * This class represents the key operations associated with dynamic tasks. + */ +public interface DynamicTaskDAO { + + int addTask(DynamicTask dynamicTask) throws TaskManagementDAOException; + + boolean updateDynamicTask(DynamicTask dynamicTask) throws TaskManagementDAOException; + + void deleteDynamicTask(int dynamicTaskId) throws TaskManagementDAOException; + + DynamicTask getDynamicTaskById(int dynamicTaskId) throws TaskManagementDAOException; + + List getAllDynamicTasks() throws TaskManagementDAOException; + + List getActiveDynamicTasks() throws TaskManagementDAOException; + +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/DynamicTaskPropDAO.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/DynamicTaskPropDAO.java new file mode 100755 index 0000000000..b458417298 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/DynamicTaskPropDAO.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.dao; + +import io.entgra.task.mgt.common.exception.TaskManagementDAOException; + +import java.util.Map; + +/** + * This class represents the key operations associated with dynamic task properties. + */ +public interface DynamicTaskPropDAO { + + void addTaskProperties(int dynamicTaskId, Map properties) throws TaskManagementDAOException; + + Map getDynamicTaskProps(int dynamicTaskId) throws TaskManagementDAOException; + + void updateDynamicTaskProps(int dynamicTaskId, Map properties) + throws TaskManagementDAOException; +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/common/TaskManagementDAOFactory.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/common/TaskManagementDAOFactory.java new file mode 100755 index 0000000000..c8f8623777 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/common/TaskManagementDAOFactory.java @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.dao.common; + +import io.entgra.task.mgt.common.constant.TaskMgtConstants; +import io.entgra.task.mgt.common.exception.IllegalTransactionStateException; +import io.entgra.task.mgt.common.exception.TransactionManagementException; +import io.entgra.task.mgt.common.exception.UnsupportedDatabaseEngineException; +import io.entgra.task.mgt.core.config.datasource.DataSourceConfig; +import io.entgra.task.mgt.core.config.datasource.JNDILookupDefinition; +import io.entgra.task.mgt.core.dao.DynamicTaskDAO; +import io.entgra.task.mgt.core.dao.DynamicTaskPropDAO; +import io.entgra.task.mgt.core.dao.impl.DynamicTaskDAOImpl; +import io.entgra.task.mgt.core.dao.impl.DynamicTaskPropDAOImpl; +import io.entgra.task.mgt.core.dao.util.TaskManagementDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Hashtable; +import java.util.List; + +public class TaskManagementDAOFactory { + + private static DataSource dataSource; + private static String databaseEngine; + private static final Log log = LogFactory.getLog(TaskManagementDAOFactory.class); + private static ThreadLocal currentConnection = new ThreadLocal<>(); + + + public static DynamicTaskDAO getDynamicTaskDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case TaskMgtConstants.DataBaseTypes.DB_TYPE_H2: + case TaskMgtConstants.DataBaseTypes.DB_TYPE_MYSQL: + return new DynamicTaskDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + + public static DynamicTaskPropDAO getDynamicTaskPropDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case TaskMgtConstants.DataBaseTypes.DB_TYPE_H2: + case TaskMgtConstants.DataBaseTypes.DB_TYPE_MYSQL: + return new DynamicTaskPropDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + + public static void init(DataSourceConfig config) { + dataSource = resolveDataSource(config); + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + log.error("Error occurred while retrieving config.datasource connection", e); + } + } + + public static void init(DataSource dtSource) { + dataSource = dtSource; + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + log.error("Error occurred while retrieving config.datasource connection", e); + } + } + + public static void beginTransaction() throws TransactionManagementException { + Connection conn = currentConnection.get(); + if (conn != null) { + throw new IllegalTransactionStateException("A transaction is already active within the context of " + + "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + + "transaction is already active is a sign of improper transaction handling"); + } + try { + conn = dataSource.getConnection(); + conn.setAutoCommit(false); + currentConnection.set(conn); + } catch (SQLException e) { + throw new TransactionManagementException("Error occurred while retrieving config.datasource connection", e); + } + } + + public static void openConnection() throws SQLException { + Connection conn = currentConnection.get(); + if (conn != null) { + throw new IllegalTransactionStateException("A transaction is already active within the context of " + + "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + + "transaction is already active is a sign of improper transaction handling"); + } + conn = dataSource.getConnection(); + currentConnection.set(conn); + } + + public static Connection getConnection() throws SQLException { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + return conn; + } + + public static void commitTransaction() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + try { + conn.commit(); + } catch (SQLException e) { + log.error("Error occurred while committing the transaction", e); + } + } + + public static void rollbackTransaction() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + try { + conn.rollback(); + } catch (SQLException e) { + log.warn("Error occurred while roll-backing the transaction", e); + } + } + + public static void closeConnection() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + try { + conn.close(); + } catch (SQLException e) { + log.warn("Error occurred while close the connection"); + } + currentConnection.remove(); + } + + + /** + * Resolve data source from the data source definition + * + * @param config data source configuration + * @return data source resolved from the data source definition + */ + private static DataSource resolveDataSource(DataSourceConfig config) { + DataSource dataSource = null; + if (config == null) { + throw new RuntimeException( + "Device Management Repository data source configuration " + "is null and " + + "thus, is not initialized"); + } + io.entgra.task.mgt.core.config.datasource.JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition(); + if (jndiConfig != null) { + if (log.isDebugEnabled()) { + log.debug("Initializing Device Management Repository data source using the JNDI " + + "Lookup Definition"); + } + List jndiPropertyList = + jndiConfig.getJndiProperties(); + if (jndiPropertyList != null) { + Hashtable jndiProperties = new Hashtable(); + for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) { + jndiProperties.put(prop.getName(), prop.getValue()); + } + dataSource = TaskManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), jndiProperties); + } else { + dataSource = TaskManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), null); + } + } + return dataSource; + } +} \ No newline at end of file diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/impl/DynamicTaskDAOImpl.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/impl/DynamicTaskDAOImpl.java new file mode 100755 index 0000000000..80fcb98e15 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/impl/DynamicTaskDAOImpl.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.dao.impl; + +import io.entgra.task.mgt.common.bean.DynamicTask; +import io.entgra.task.mgt.common.exception.TaskManagementDAOException; +import io.entgra.task.mgt.core.dao.DynamicTaskDAO; +import io.entgra.task.mgt.core.dao.common.TaskManagementDAOFactory; +import io.entgra.task.mgt.core.dao.util.TaskManagementDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.sql.*; +import java.util.List; + + +public class DynamicTaskDAOImpl implements DynamicTaskDAO { + private static final Log log = LogFactory.getLog(DynamicTaskDAOImpl.class); + + @Override + public int addTask(DynamicTask dynamicTask) throws TaskManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + int taskId = -1; + try { + Connection conn = TaskManagementDAOFactory.getConnection(); + String sql = "INSERT INTO DYNAMIC_TASK(CRON, NAME, IS_ENABLED, TASK_CLASS_NAME, TENANT_ID) " + + "VALUES (?, ?, ?, ?, ?)"; + + stmt = conn.prepareStatement(sql, new String[]{"DYNAMIC_TASK_ID"}); + stmt.setString(1, dynamicTask.getCronExpression()); + stmt.setString(2, dynamicTask.getName()); + stmt.setBoolean(3, dynamicTask.isEnabled()); + stmt.setString(4, dynamicTask.getTaskClassName()); + stmt.setInt(5, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + stmt.executeUpdate(); + + rs = stmt.getGeneratedKeys(); + if (rs.next()) { + taskId = rs.getInt(1); + } + return taskId; + } catch (SQLException e) { + String msg = "Error occurred while inserting task '" + dynamicTask.getName() + "'"; + log.error(msg, e); + throw new TaskManagementDAOException(msg, e); + } finally { + TaskManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public boolean updateDynamicTask(DynamicTask dynamicTask) throws TaskManagementDAOException { + PreparedStatement stmt = null; + int rows; + try { + Connection conn = TaskManagementDAOFactory.getConnection(); + String sql = "UPDATE DYNAMIC_TASK SET CRON = ?,IS_ENABLED = ? WHERE DYNAMIC_TASK_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, dynamicTask.getCronExpression()); + stmt.setBoolean(2, dynamicTask.isEnabled()); + stmt.setInt(3, dynamicTask.getDynamicTaskId()); + rows = stmt.executeUpdate(); + return (rows > 0); + } catch (SQLException e) { + String msg = "Error occurred while updating dynamic task '" + dynamicTask.getDynamicTaskId() + "'"; + log.error(msg, e); + throw new TaskManagementDAOException(msg, e); + } finally { + TaskManagementDAOUtil.cleanupResources(stmt, null); + } + } + + + @Override + public void deleteDynamicTask(int dynamicTaskId) throws TaskManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete dynamic task with the id: " + dynamicTaskId); + } + String sql = "DELETE FROM DYNAMIC_TASK WHERE DYNAMIC_TASK_ID = ? AND TENANT_ID = ?"; + try { + Connection conn = TaskManagementDAOFactory.getConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setInt(1, dynamicTaskId); + stmt.setInt(2, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete a dynamic task which has the id " + + dynamicTaskId; + log.error(msg, e); + throw new TaskManagementDAOException(msg, e); + } + } + + @Override + public DynamicTask getDynamicTaskById(int dynamicTaskId) throws TaskManagementDAOException { + DynamicTask dynamicTask = null; + try { + Connection conn = TaskManagementDAOFactory.getConnection(); + String sql = "SELECT * FROM DYNAMIC_TASK WHERE DYNAMIC_TASK_ID= ? AND TENANT_ID = ?"; + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, dynamicTaskId); + stmt.setInt(2, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + dynamicTask = TaskManagementDAOUtil.loadDynamicTask(rs); + } + } + } + } catch (SQLException e) { + String msg = "Error occurred while getting dynamic task data for task identifier '" + + dynamicTask + "'"; + log.error(msg, e); + throw new TaskManagementDAOException(msg, e); + } + return dynamicTask; + } + + @Override + public List getAllDynamicTasks() throws TaskManagementDAOException { + List dynamicTasks = null; + try { + Connection conn = TaskManagementDAOFactory.getConnection(); + String sql = "SELECT * FROM DYNAMIC_TASK"; + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + try (ResultSet rs = stmt.executeQuery()) { + dynamicTasks = TaskManagementDAOUtil.loadDynamicTasks(rs); + } + } + } catch (SQLException e) { + String msg = "Error occurred while getting all dynamic task data "; + log.error(msg, e); + throw new TaskManagementDAOException(msg, e); + } + return dynamicTasks; + } + + @Override + public List getActiveDynamicTasks() throws TaskManagementDAOException { + List dynamicTasks = null; + try { + Connection conn = TaskManagementDAOFactory.getConnection(); + String sql = "SELECT * FROM DYNAMIC_TASK WHERE IS_ENABLED = 'true' "; + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + try (ResultSet rs = stmt.executeQuery()) { + dynamicTasks = TaskManagementDAOUtil.loadDynamicTasks(rs); + } + } + } catch (SQLException e) { + String msg = "Error occurred while getting all dynamic task data "; + log.error(msg, e); + throw new TaskManagementDAOException(msg, e); + } + return dynamicTasks; + } +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/impl/DynamicTaskPropDAOImpl.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/impl/DynamicTaskPropDAOImpl.java new file mode 100755 index 0000000000..66d6920feb --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/impl/DynamicTaskPropDAOImpl.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.dao.impl; + +import io.entgra.task.mgt.common.constant.TaskMgtConstants; +import io.entgra.task.mgt.common.exception.TaskManagementDAOException; +import io.entgra.task.mgt.core.dao.DynamicTaskPropDAO; +import io.entgra.task.mgt.core.dao.common.TaskManagementDAOFactory; +import io.entgra.task.mgt.core.dao.util.TaskManagementDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +public class DynamicTaskPropDAOImpl implements DynamicTaskPropDAO { + + private static final Log log = LogFactory.getLog(DynamicTaskPropDAOImpl.class); + + @Override + public void addTaskProperties(int taskId, Map properties) + throws TaskManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = TaskManagementDAOFactory.getConnection(); + stmt = conn.prepareStatement( + "INSERT INTO DYNAMIC_TASK_PROPERTIES(DYNAMIC_TASK_ID, PROPERTY_NAME, " + + "PROPERTY_VALUE, TENANT_ID) VALUES (?, ?, ?, ?)"); + for (String propertyKey : properties.keySet()) { + stmt.setInt(1, taskId); + stmt.setString(2, propertyKey); + stmt.setString(3, properties.get(propertyKey)); + stmt.setInt(4, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + stmt.addBatch(); + } + stmt.executeBatch(); + } catch (SQLException e) { + String msg = "Error occurred while adding task properties of task '" + taskId + "' to the db."; + log.error(msg, e); + throw new TaskManagementDAOException(msg, e); + } finally { + TaskManagementDAOUtil.cleanupResources(stmt, null); + } + } + + + public Map getDynamicTaskProps(int dynamicTaskId) throws TaskManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + ResultSet resultSet = null; + Map properties; + try { + conn = TaskManagementDAOFactory.getConnection(); + stmt = conn.prepareStatement( + "SELECT * FROM DYNAMIC_TASK_PROPERTIES WHERE DYNAMIC_TASK_ID = ?"); + stmt.setInt(1, dynamicTaskId); + resultSet = stmt.executeQuery(); + properties = new HashMap<>(); + while (resultSet.next()) { + properties.put(resultSet.getString(TaskMgtConstants.Task.PROPERTY_KEY_COLUMN_NAME) + , resultSet.getString(TaskMgtConstants.Task.PROPERTY_VALUE_COLUMN_NAME)); + } + } catch (SQLException e) { + String msg = "Error occurred while fetching task properties of : '" + dynamicTaskId + "'"; + log.error(msg, e); + throw new TaskManagementDAOException(msg, e); + } finally { + TaskManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return properties; + } + + @Override + public void updateDynamicTaskProps(int dynamicTaskId, Map properties) + throws TaskManagementDAOException { + if (properties.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("Property map of task id :" + dynamicTaskId + " is empty."); + } + return; + } + Connection conn; + PreparedStatement stmt = null; + try { + conn = TaskManagementDAOFactory.getConnection(); + stmt = conn.prepareStatement("UPDATE DYNAMIC_TASK_PROPERTIES SET PROPERTY_VALUE = ? " + + "WHERE DYNAMIC_TASK_ID = ? AND PROPERTY_NAME = ?"); + + for (Map.Entry entry : properties.entrySet()) { + stmt.setString(1, entry.getValue()); + stmt.setInt(2, dynamicTaskId); + stmt.setString(3, entry.getKey()); + stmt.addBatch(); + } + stmt.executeBatch(); + } catch (SQLException e) { + throw new TaskManagementDAOException + ("Error occurred while updating device properties to database.", e); + } finally { + TaskManagementDAOUtil.cleanupResources(stmt, null); + } + } +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/util/TaskManagementDAOUtil.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/util/TaskManagementDAOUtil.java new file mode 100755 index 0000000000..c9ba9ea07a --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/util/TaskManagementDAOUtil.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.dao.util; + +import io.entgra.task.mgt.common.bean.DynamicTask; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.naming.InitialContext; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; + +public class TaskManagementDAOUtil { + private static final Log log = LogFactory.getLog(TaskManagementDAOUtil.class); + + public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing result set", e); + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing prepared statement", e); + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing database connection", e); + } + } + } + + public static void cleanupResources(PreparedStatement stmt, ResultSet rs) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing result set", e); + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing prepared statement", e); + } + } + } + + public static DataSource lookupDataSource(String dataSourceName, + final Hashtable jndiProperties) { + try { + if (jndiProperties == null || jndiProperties.isEmpty()) { + return (DataSource) InitialContext.doLookup(dataSourceName); + } + final InitialContext context = new InitialContext(jndiProperties); + return (DataSource) context.lookup(dataSourceName); + } catch (Exception e) { + throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); + } + } + + public static DynamicTask loadDynamicTask(ResultSet rs) throws SQLException { + DynamicTask dynamicTask = new DynamicTask(); + dynamicTask.setDynamicTaskId(rs.getInt("DYNAMIC_TASK_ID")); + dynamicTask.setName(rs.getString("NAME")); + dynamicTask.setCronExpression(rs.getString("CRON")); + dynamicTask.setTaskClassName(rs.getString("TASK_CLASS_NAME")); + dynamicTask.setEnabled(rs.getBoolean("IS_ENABLED")); + dynamicTask.setTenantId(rs.getInt("TENANT_ID")); + return dynamicTask; + } + + public static List loadDynamicTasks(ResultSet rs) throws SQLException { + List dynamicTasks = new ArrayList<>(); + while (rs.next()) { + dynamicTasks.add(loadDynamicTask(rs)); + } + return dynamicTasks; + } + +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/internal/TaskManagerDataHolder.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/internal/TaskManagerDataHolder.java new file mode 100755 index 0000000000..8de0cbb40f --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/internal/TaskManagerDataHolder.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.internal; + +import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; +import io.entgra.task.mgt.common.spi.TaskManagementService; +import org.wso2.carbon.ntask.core.service.TaskService; + +public class TaskManagerDataHolder { + private TaskManagementService taskManagerService; + private TaskService nTaskService; + + private HeartBeatManagementService heartBeatService; + + private static final TaskManagerDataHolder thisInstance = new TaskManagerDataHolder(); + + private TaskManagerDataHolder() { + } + + public static TaskManagerDataHolder getInstance() { + return thisInstance; + } + + public TaskManagementService getTaskManagementService() { + return taskManagerService; + } + + public void setTaskManagementService(TaskManagementService taskManagerService) { + this.taskManagerService = taskManagerService; + } + + public TaskService getnTaskService() { + return nTaskService; + } + + public void setnTaskService(TaskService nTaskService) { + this.nTaskService = nTaskService; + } + + public HeartBeatManagementService getHeartBeatService() { + return heartBeatService; + } + + public void setHeartBeatService(HeartBeatManagementService heartBeatService) { + this.heartBeatService = heartBeatService; + } +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/internal/TaskManagerServiceComponent.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/internal/TaskManagerServiceComponent.java new file mode 100755 index 0000000000..9021b070ec --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/internal/TaskManagerServiceComponent.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.internal; + +import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; +import io.entgra.task.mgt.core.config.TaskManagementConfig; +import io.entgra.task.mgt.core.config.datasource.DataSourceConfig; +import io.entgra.task.mgt.common.spi.TaskManagementService; +import io.entgra.task.mgt.core.config.TaskConfigurationManager; +import io.entgra.task.mgt.core.dao.common.TaskManagementDAOFactory; +import io.entgra.task.mgt.core.service.TaskManagementServiceImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.ndatasource.core.DataSourceService; +import org.wso2.carbon.ntask.core.service.TaskService; + +/** + * @scr.component name="io.entgra.task.mgt.service" immediate="true" + * @scr.reference name="datasource.service" + * interface="org.wso2.carbon.ndatasource.core.DataSourceService" + * cardinality="1..1" + * policy="dynamic" + * bind="setDataSourceService" + * unbind="unsetDataSourceService" + * @scr.reference name="app.mgt.ntask.component" + * interface="org.wso2.carbon.ntask.core.service.TaskService" + * cardinality="1..1" + * policy="dynamic" + * bind="setTaskService" + * unbind="unsetTaskService" + * @scr.reference name="entgra.heart.beat.service" + * interface="io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService" + * cardinality="0..1" + * policy="dynamic" + * bind="setHeartBeatService" + * unbind="unsetHeartBeatService" + */ +public class TaskManagerServiceComponent { + + private static final Log log = LogFactory.getLog(TaskManagerServiceComponent.class); + + protected void activate(ComponentContext ctx) { + + if (log.isDebugEnabled()) { + log.debug("Activating Task Manager Service Component"); + } + try { + TaskManagementConfig taskManagementConfig = TaskConfigurationManager.getInstance() + .getTaskManagementConfig(); + DataSourceConfig dataSourceConfig = taskManagementConfig.getTaskMgtConfigRepository() + .getDataSourceConfig(); + TaskManagementDAOFactory.init(dataSourceConfig); + BundleContext bundleContext = ctx.getBundleContext(); + TaskManagementService taskManagementService = new TaskManagementServiceImpl(); + taskManagementService.init(); + TaskManagerDataHolder.getInstance().setTaskManagementService(taskManagementService); + bundleContext.registerService(TaskManagementService.class.getName() + , taskManagementService, null); + if (log.isDebugEnabled()) { + log.debug("Task Manager Service Component has been successfully activated"); + } + } catch (Throwable e) { + log.error("Error occurred while activating Task Manager Service Component", e); + } + } + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating Task Manager Service Component"); + } + } + + protected void setDataSourceService(DataSourceService dataSourceService) { + /* This is to avoid Task Manager Service Component getting initialized before the underlying datasources + are registered */ + if (log.isDebugEnabled()) { + log.debug("Data source service set to Task Manager Service Component "); + } + } + + protected void unsetDataSourceService(DataSourceService dataSourceService) { + //do nothing + } + + @SuppressWarnings("unused") + public void setTaskService(TaskService taskService) { + if (log.isDebugEnabled()) { + log.debug("Setting the task service to Task Manager Service Component"); + } + TaskManagerDataHolder.getInstance().setnTaskService(taskService); + } + + @SuppressWarnings("unused") + protected void unsetTaskService(TaskService taskService) { + if (log.isDebugEnabled()) { + log.debug("Removing the task service from Task Manager Service Component"); + } + TaskManagerDataHolder.getInstance().setnTaskService(null); + } + + @SuppressWarnings("unused") + protected void setHeartBeatService(HeartBeatManagementService heartBeatService) { + if (log.isDebugEnabled()) { + log.debug("Setting heart beat service to Task Manager Service Component"); + } + TaskManagerDataHolder.getInstance().setHeartBeatService(heartBeatService); + } + + @SuppressWarnings("unused") + protected void unsetHeartBeatService(HeartBeatManagementService heartBeatManagementService) { + if (log.isDebugEnabled()) { + log.debug("Removing heart beat service from Task Manager Service Component"); + } + TaskManagerDataHolder.getInstance().setHeartBeatService(null); + } + +} \ No newline at end of file diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/service/TaskManagementServiceImpl.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/service/TaskManagementServiceImpl.java new file mode 100755 index 0000000000..fe3a7cb97e --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/service/TaskManagementServiceImpl.java @@ -0,0 +1,397 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (https://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.task.mgt.core.service; + +import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import io.entgra.task.mgt.common.bean.DynamicTask; +import io.entgra.task.mgt.common.constant.TaskMgtConstants; +import io.entgra.task.mgt.common.exception.TaskManagementDAOException; +import io.entgra.task.mgt.common.exception.TaskManagementException; +import io.entgra.task.mgt.common.exception.TaskNotFoundException; +import io.entgra.task.mgt.common.exception.TransactionManagementException; +import io.entgra.task.mgt.common.spi.TaskManagementService; +import io.entgra.task.mgt.core.dao.DynamicTaskDAO; +import io.entgra.task.mgt.core.dao.DynamicTaskPropDAO; +import io.entgra.task.mgt.core.dao.common.TaskManagementDAOFactory; +import io.entgra.task.mgt.core.internal.TaskManagerDataHolder; +import io.entgra.task.mgt.core.util.TaskManagementUtil; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.ntask.common.TaskException; +import org.wso2.carbon.ntask.core.TaskInfo; +import org.wso2.carbon.ntask.core.TaskManager; +import org.wso2.carbon.ntask.core.service.TaskService; + +import java.util.List; +import java.util.Map; + +public class TaskManagementServiceImpl implements TaskManagementService { + private static final Log log = LogFactory.getLog(TaskManagementServiceImpl.class); + + private final DynamicTaskDAO dynamicTaskDAO; + + private final DynamicTaskPropDAO dynamicTaskPropDAO; + private TaskManager taskManager; + + public TaskManagementServiceImpl() { + this.dynamicTaskDAO = TaskManagementDAOFactory.getDynamicTaskDAO(); + this.dynamicTaskPropDAO = TaskManagementDAOFactory.getDynamicTaskPropDAO(); + } + + @Override + public void init() throws TaskManagementException { + TaskService nTaskService = TaskManagerDataHolder.getInstance().getnTaskService(); + if (nTaskService == null) { + String msg = "Unable to load TaskService, hence unable to schedule the task."; + log.error(msg); + throw new TaskManagementException(msg); + } + if (!nTaskService.getRegisteredTaskTypes().contains(TaskMgtConstants.Task.DYNAMIC_TASK_TYPE)) { + try { + nTaskService.registerTaskType(TaskMgtConstants.Task.DYNAMIC_TASK_TYPE); + this.taskManager = nTaskService.getTaskManager(TaskMgtConstants.Task.DYNAMIC_TASK_TYPE); + } catch (TaskException e) { + String msg = "Error occurred while registering task type [" + + TaskMgtConstants.Task.DYNAMIC_TASK_TYPE + + "], hence unable to schedule the task."; + log.error(msg); + throw new TaskManagementException(msg, e); + } + } + } + + @Override + public void createTask(DynamicTask dynamicTask) throws TaskManagementException { + String taskId; + try { + // add into the dynamic task tables + TaskManagementDAOFactory.beginTransaction(); + int dynamicTaskId = dynamicTaskDAO.addTask(dynamicTask); + + Map taskProperties = dynamicTask.getProperties(); + dynamicTaskPropDAO.addTaskProperties(dynamicTaskId, taskProperties); + + // add into the ntask core + taskId = TaskManagementUtil.generateTaskId(dynamicTaskId); + + try { + int serverHashIdx = TaskManagerDataHolder.getInstance().getHeartBeatService() + .getServerCtxInfo().getLocalServerHashIdx(); + taskProperties.put(TaskMgtConstants.Task.LOCAL_HASH_INDEX, String.valueOf(serverHashIdx)); + taskProperties.put(TaskMgtConstants.Task.LOCAL_TASK_NAME, taskId); + } catch (HeartBeatManagementException e) { + String msg = "Unexpected exception when getting server hash index."; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } + + if (!isTaskExists(taskId)) { + TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); + triggerInfo.setCronExpression(dynamicTask.getCronExpression()); + TaskInfo taskInfo = new TaskInfo(taskId, dynamicTask.getTaskClassName(), taskProperties, triggerInfo); + taskManager.registerTask(taskInfo); + taskManager.scheduleTask(taskId); + if (!dynamicTask.isEnabled()) { + taskManager.pauseTask(taskId); + } + } else { + String msg = "Task '" + taskId + "' is already exists in the ntask core " + + "Hence not creating another task for the same name."; + log.error(msg); + } + + TaskManagementDAOFactory.commitTransaction(); + } catch (TaskManagementDAOException e) { + TaskManagementDAOFactory.rollbackTransaction(); + String msg = "Failed to add dynamic task " + dynamicTask.getName(); + log.error(msg, e); + throw new TaskManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Failed to start/open transaction to add dynamic task"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } catch (TaskException e) { + TaskManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while scheduling task '" + dynamicTask.getName() + "'"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } finally { + TaskManagementDAOFactory.closeConnection(); + } + } + + @Override + public void updateTask(int dynamicTaskId, DynamicTask dynamicTask) throws TaskManagementException + , TaskNotFoundException { + try { + //Update dynamic task table + TaskManagementDAOFactory.beginTransaction(); + DynamicTask existingTask = dynamicTaskDAO.getDynamicTaskById(dynamicTaskId); + + if (existingTask != null) { + existingTask.setEnabled(dynamicTask.isEnabled()); + existingTask.setCronExpression(dynamicTask.getCronExpression()); + dynamicTaskDAO.updateDynamicTask(existingTask); + if (!dynamicTask.getProperties().isEmpty()) { + dynamicTaskPropDAO.updateDynamicTaskProps(dynamicTaskId, dynamicTask.getProperties()); + } + } else { + String msg = "Task '" + dynamicTaskId + "' is not exists in the dynamic task table."; + log.error(msg); + throw new TaskNotFoundException(msg); + } + + // Update task in the ntask core + String taskId = TaskManagementUtil.generateTaskId(existingTask.getDynamicTaskId()); + if (isTaskExists(taskId)) { + TaskInfo taskInfo = taskManager.getTask(taskId); + if (!dynamicTask.getProperties().isEmpty()) { + taskInfo.setProperties(dynamicTask.getProperties()); + } + TaskInfo.TriggerInfo triggerInfo; + if (taskInfo.getTriggerInfo() == null) { + triggerInfo = new TaskInfo.TriggerInfo(); + } else { + triggerInfo = taskInfo.getTriggerInfo(); + } + triggerInfo.setCronExpression(dynamicTask.getCronExpression()); + taskInfo.setTriggerInfo(triggerInfo); + taskManager.registerTask(taskInfo); + taskManager.rescheduleTask(taskId); + } else { + String msg = "Task '" + taskId + "' is not exists in the n task core " + + "Hence cannot update the task."; + log.error(msg); + } + TaskManagementDAOFactory.commitTransaction(); + } catch (TaskManagementDAOException e) { + TaskManagementDAOFactory.rollbackTransaction(); + String msg = "Failed to update dynamic task " + dynamicTask.getDynamicTaskId(); + log.error(msg, e); + throw new TaskManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Failed to start/open transaction to update dynamic task"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } catch (TaskException e) { + TaskManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while updating task '" + dynamicTask.getDynamicTaskId() + "'"; + log.error(msg); + throw new TaskManagementException(msg, e); + } finally { + TaskManagementDAOFactory.closeConnection(); + } + } + + @Override + public void toggleTask(int dynamicTaskId, boolean isEnabled) throws TaskManagementException + , TaskNotFoundException { + + try { + //update dynamic task table + TaskManagementDAOFactory.beginTransaction(); + DynamicTask existingTask = dynamicTaskDAO.getDynamicTaskById(dynamicTaskId); + if (existingTask != null) { + existingTask.setEnabled(isEnabled); + dynamicTaskDAO.updateDynamicTask(existingTask); + } else { + String msg = "Task '" + dynamicTaskId + "' is not exists."; + log.error(msg); + throw new TaskNotFoundException(msg); + } + + // Update task in the ntask core + String taskId = TaskManagementUtil.generateTaskId(existingTask.getDynamicTaskId()); + if (isTaskExists(taskId)) { + if (isEnabled) { + taskManager.resumeTask(taskId); + } else { + taskManager.pauseTask(taskId); + } + } else { + String msg = "Task '" + taskId + "' is not exists in the ntask core " + + "Hence cannot toggle the task in the ntask."; + log.error(msg); + } + TaskManagementDAOFactory.commitTransaction(); + } catch (TaskManagementDAOException e) { + TaskManagementDAOFactory.rollbackTransaction(); + String msg = "Failed to toggle dynamic task " + dynamicTaskId; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Failed to start/open transaction to toggle dynamic task"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } catch (TaskException e) { + String msg = "Error occurred while toggling task '" + dynamicTaskId + "' to '" + isEnabled + "'"; + log.error(msg); + throw new TaskManagementException(msg, e); + } finally { + TaskManagementDAOFactory.closeConnection(); + } + } + + @Override + public void deleteTask(int dynamicTaskId) throws TaskManagementException, TaskNotFoundException { + // delete task from dynamic task table + try { + TaskManagementDAOFactory.beginTransaction(); + DynamicTask existingTask = dynamicTaskDAO.getDynamicTaskById(dynamicTaskId); + if (existingTask != null) { + dynamicTaskDAO.deleteDynamicTask(dynamicTaskId); + } else { + String msg = "Task '" + dynamicTaskId + "' is not exists."; + log.error(msg); + throw new TaskNotFoundException(msg); + } + + String taskId = TaskManagementUtil.generateTaskId(existingTask.getDynamicTaskId()); + if (isTaskExists(taskId)) { + taskManager.deleteTask(taskId); + } else { + String msg = "Task '" + taskId + "' is not exists in the ntask core " + + "Hence cannot delete from the ntask core."; + log.error(msg); + } + TaskManagementDAOFactory.commitTransaction(); + } catch (TaskManagementDAOException e) { + TaskManagementDAOFactory.rollbackTransaction(); + String msg = "Failed to update dynamic task " + dynamicTaskId; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Failed to start/open transaction to delete dynamic task"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } catch (TaskException e) { + TaskManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while retrieving task manager to delete task '" + dynamicTaskId + "'"; + log.error(msg); + throw new TaskManagementException(msg, e); + } finally { + TaskManagementDAOFactory.closeConnection(); + } + } + + @Override + public List getAllDynamicTasks() throws TaskManagementException { + List dynamicTasks; + try { + if (log.isDebugEnabled()) { + log.debug("Fetching the details of all dynamic tasks"); + } + TaskManagementDAOFactory.beginTransaction(); + dynamicTasks = dynamicTaskDAO.getAllDynamicTasks(); + if (dynamicTasks != null) { + for (DynamicTask dynamicTask : dynamicTasks) { + dynamicTask.setProperties(dynamicTaskPropDAO + .getDynamicTaskProps(dynamicTask.getDynamicTaskId())); + } + } + TaskManagementDAOFactory.commitTransaction(); + } catch (TaskManagementDAOException e) { + TaskManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while fetching all dynamic tasks"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Failed to start/open transaction to get all dynamic tasks"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } finally { + TaskManagementDAOFactory.closeConnection(); + } + return dynamicTasks; + } + + @Override + public DynamicTask getDynamicTaskById(int dynamicTaskId) throws TaskManagementException { + DynamicTask dynamicTask; + try { + if (log.isDebugEnabled()) { + log.debug("Fetching the details of dynamic task '" + dynamicTaskId + "'"); + } + TaskManagementDAOFactory.beginTransaction(); + dynamicTask = dynamicTaskDAO.getDynamicTaskById(dynamicTaskId); + if (dynamicTask != null) { + dynamicTask.setProperties(dynamicTaskPropDAO.getDynamicTaskProps(dynamicTask.getDynamicTaskId())); + } + TaskManagementDAOFactory.commitTransaction(); + } catch (TaskManagementDAOException e) { + TaskManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while fetching dynamic task '" + dynamicTaskId + "'"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Failed to start/open transaction to get dynamic task '" + dynamicTaskId + "'"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } finally { + TaskManagementDAOFactory.closeConnection(); + } + return dynamicTask; + } + + @Override + public List getActiveDynamicTasks() throws TaskManagementException { + List dynamicTasks; + try { + if (log.isDebugEnabled()) { + log.debug("Fetching the details of all active dynamic tasks"); + } + TaskManagementDAOFactory.beginTransaction(); + dynamicTasks = dynamicTaskDAO.getActiveDynamicTasks(); + if (dynamicTasks != null) { + for (DynamicTask dynamicTask : dynamicTasks) { + dynamicTask.setProperties(dynamicTaskPropDAO.getDynamicTaskProps(dynamicTask.getDynamicTaskId())); + } + } + TaskManagementDAOFactory.commitTransaction(); + } catch (TaskManagementDAOException e) { + TaskManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while fetching all active dynamic tasks"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Failed to start/open transaction to get all active dynamic tasks"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } finally { + TaskManagementDAOFactory.closeConnection(); + } + return dynamicTasks; + } + + // check whether task exist in the ntask core + private boolean isTaskExists(String taskId) throws TaskManagementException, TaskException { + if (StringUtils.isEmpty(taskId)) { + String msg = "Task ID must not be null or empty."; + log.error(msg); + throw new TaskManagementException(msg); + } + List tasks = taskManager.getAllTasks(); + for (TaskInfo t : tasks) { + if (taskId.equals(t.getName())) { + return true; + } + } + return false; + } +} diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/util/TaskManagementUtil.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/util/TaskManagementUtil.java new file mode 100755 index 0000000000..5308fc29c9 --- /dev/null +++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/util/TaskManagementUtil.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.core.util; + +import com.google.gson.Gson; +import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import io.entgra.task.mgt.common.constant.TaskMgtConstants; +import io.entgra.task.mgt.common.exception.TaskManagementException; +import io.entgra.task.mgt.core.internal.TaskManagerDataHolder; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.File; +import java.util.Map; + +/** + * Provides utility methods required by the task management bundle. + */ +public class TaskManagementUtil { + + private static final Log log = LogFactory.getLog(TaskManagementUtil.class); + + public static Document convertToDocument(File file) throws TaskManagementException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + try { + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + return docBuilder.parse(file); + } catch (Exception e) { + throw new TaskManagementException( + "Error occurred while parsing file, while converting " + + "to a org.w3c.dom.Document : " + e.getMessage(), e); + } + } + + public static String generateTaskId(int dynamicTaskId) throws TaskManagementException { + try { + int serverHashIdx = TaskManagerDataHolder.getInstance().getHeartBeatService() + .getServerCtxInfo().getLocalServerHashIdx(); + return generateTaskId(dynamicTaskId, serverHashIdx); + } catch (HeartBeatManagementException e) { + String msg = "Failed to generate task id for a dynamic task " + dynamicTaskId; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } + } + + public static String generateTaskId(int dynamicTaskId, int serverHashIdx) { + return TaskMgtConstants.Task.DYNAMIC_TASK_TYPE + TaskMgtConstants.Task.NAME_SEPARATOR + dynamicTaskId + + TaskMgtConstants.Task.NAME_SEPARATOR + serverHashIdx; + } + + public static String generateTaskPropsMD5(Map taskProperties) { + taskProperties.remove(TaskMgtConstants.Task.TENANT_ID_PROP); + taskProperties.remove(TaskMgtConstants.Task.LOCAL_HASH_INDEX); + taskProperties.remove(TaskMgtConstants.Task.LOCAL_TASK_NAME); + Gson gson = new Gson(); + String json = gson.toJson(taskProperties); + return DigestUtils.md5Hex(json); + } + +} diff --git a/components/task-mgt/task-manager/pom.xml b/components/task-mgt/task-manager/pom.xml new file mode 100755 index 0000000000..344ee82cfc --- /dev/null +++ b/components/task-mgt/task-manager/pom.xml @@ -0,0 +1,39 @@ + + + + + + org.wso2.carbon.devicemgt + task-mgt + 5.0.21-SNAPSHOT + ../pom.xml + + + 4.0.0 + task-manager + Entgra IoT - Task Manager Component + pom + http://entgra.io + + + io.entgra.task.mgt.core + io.entgra.task.mgt.common + + + \ No newline at end of file diff --git a/components/task-mgt/task-watcher/io.entgra.task.mgt.watcher/pom.xml b/components/task-mgt/task-watcher/io.entgra.task.mgt.watcher/pom.xml new file mode 100755 index 0000000000..34eaf2c430 --- /dev/null +++ b/components/task-mgt/task-watcher/io.entgra.task.mgt.watcher/pom.xml @@ -0,0 +1,138 @@ + + + + + + org.wso2.carbon.devicemgt + task-watcher + 5.0.21-SNAPSHOT + ../pom.xml + + + 4.0.0 + io.entgra.task.mgt.watcher + bundle + Entgra IoT - Task Watcher + Entgra IoT - Task Watcher + http://entgra.io + + + + + org.apache.felix + maven-scr-plugin + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.device.mgt.version} + Task Watcher Bundle + io.entgra.task.mgt.watcher.internal + + io.entgra.server.bootup.heartbeat.beacon.*, + io.entgra.task.mgt.common.*, + io.entgra.task.mgt.core.*, + org.apache.commons.logging, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.wso2.carbon.context, + org.wso2.carbon.core, + org.wso2.carbon.device.mgt.common.*, + org.wso2.carbon.ntask.*, + org.wso2.carbon.user.api, + org.wso2.carbon.user.core.*, + + + io.entgra.task.mgt.watcher.* + + + + + + + + + + org.eclipse.osgi + org.eclipse.osgi + provided + + + org.eclipse.osgi + org.eclipse.osgi.services + provided + + + org.wso2.carbon + org.wso2.carbon.logging + provided + + + org.wso2.carbon.devicemgt + io.entgra.task.mgt.core + provided + + + org.wso2.carbon.devicemgt + io.entgra.task.mgt.common + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + provided + + + org.wso2.carbon.devicemgt + io.entgra.server.bootup.heartbeat.beacon + provided + + + org.wso2.carbon + org.wso2.carbon.core + provided + + + org.wso2.carbon + org.wso2.carbon.user.core + provided + + + org.wso2.carbon + org.wso2.carbon.user.api + provided + + + org.wso2.carbon + org.wso2.carbon.utils + provided + + + + \ No newline at end of file diff --git a/components/task-mgt/task-watcher/io.entgra.task.mgt.watcher/src/main/java/io/entgra/task/mgt/watcher/IoTSStartupHandler.java b/components/task-mgt/task-watcher/io.entgra.task.mgt.watcher/src/main/java/io/entgra/task/mgt/watcher/IoTSStartupHandler.java new file mode 100755 index 0000000000..355fba3825 --- /dev/null +++ b/components/task-mgt/task-watcher/io.entgra.task.mgt.watcher/src/main/java/io/entgra/task/mgt/watcher/IoTSStartupHandler.java @@ -0,0 +1,260 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.watcher; + +import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import io.entgra.task.mgt.common.bean.DynamicTask; +import io.entgra.task.mgt.common.constant.TaskMgtConstants; +import io.entgra.task.mgt.common.exception.TaskManagementException; +import io.entgra.task.mgt.core.util.TaskManagementUtil; +import io.entgra.task.mgt.watcher.internal.TaskWatcherDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.core.ServerStartupObserver; +import org.wso2.carbon.ntask.common.TaskException; +import org.wso2.carbon.ntask.core.TaskInfo; +import org.wso2.carbon.ntask.core.TaskManager; +import org.wso2.carbon.ntask.core.service.TaskService; +import org.wso2.carbon.user.api.Tenant; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.core.service.RealmService; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; + +public class IoTSStartupHandler implements ServerStartupObserver { + private static final Log log = LogFactory.getLog(IoTSStartupHandler.class); + + @Override + public void completingServerStartup() { + } + + @Override + public void completedServerStartup() { + Timer timer = new Timer(); + timer.schedule(new TimerTask() { + @Override + public void run() { + try { + compareTasks(); + } catch (Exception e) { + log.error("Error occurred when comparing tasks.", e); + } + } + }, 200000, 300000); + } + + private void compareTasks() { + if (log.isDebugEnabled()) { + log.debug("Comparing Tasks from carbon nTask manager and entgra task manager"); + } + TaskService nTaskService = TaskWatcherDataHolder.getInstance().getnTaskService(); + if (nTaskService == null) { + String msg = "Unable to load TaskService from the carbon nTask core"; + log.error(msg); + return; + } + try { + List dynamicTasks = TaskWatcherDataHolder.getInstance().getTaskManagementService() + .getAllDynamicTasks(); + + scheduleMissingTasks(nTaskService, dynamicTasks); + deleteObsoleteTasks(nTaskService, dynamicTasks); + + if (log.isDebugEnabled()) { + log.debug("Task Comparison Completed and all tasks in current node are updated"); + } + } catch (TaskException e) { + String msg = "Error occurred while accessing carbon nTask manager."; + log.error(msg, e); + } catch (TaskManagementException e) { + String msg = "Error occurred while retrieving all active tasks from entgra task manager"; + log.error(msg, e); + } + + } + + private static void scheduleMissingTasks(TaskService nTaskService, List dynamicTasks) + throws TaskException, TaskManagementException { + Map> tenantedDynamicTasks = new HashMap<>(); + List dts; + for (DynamicTask dt : dynamicTasks) { + if (tenantedDynamicTasks.containsKey(dt.getTenantId())) { + dts = tenantedDynamicTasks.get(dt.getTenantId()); + } else { + dts = new ArrayList<>(); + } + dts.add(dt); + tenantedDynamicTasks.put(dt.getTenantId(), dts); + } + TaskManager taskManager; + for (Integer tenantId : tenantedDynamicTasks.keySet()) { + if (tenantId == -1) { + log.warn("Found " + tenantedDynamicTasks.get(tenantId).size() + + " invalid tasks without a valid tenant id."); + continue; + } + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); + if (!nTaskService.getRegisteredTaskTypes().contains(TaskMgtConstants.Task.DYNAMIC_TASK_TYPE)) { + nTaskService.registerTaskType(TaskMgtConstants.Task.DYNAMIC_TASK_TYPE); + } + taskManager = nTaskService.getTaskManager(TaskMgtConstants.Task.DYNAMIC_TASK_TYPE); + List tasks = taskManager.getAllTasks(); + // add or update task into nTask core + for (DynamicTask dt : tenantedDynamicTasks.get(tenantId)) { + String generatedTaskId = TaskManagementUtil.generateTaskId(dt.getDynamicTaskId()); + boolean isExist = false; + for (TaskInfo taskInfo : tasks) { + if (taskInfo.getName().equals(generatedTaskId)) { + isExist = true; + TaskInfo.TriggerInfo triggerInfo = taskInfo.getTriggerInfo(); + String dynamicTaskPropMD5 = TaskManagementUtil.generateTaskPropsMD5(dt.getProperties()); + String existingTaskPropMD5 = TaskManagementUtil.generateTaskPropsMD5(taskInfo.getProperties()); + if (!triggerInfo.getCronExpression().equals(dt.getCronExpression()) + || !dynamicTaskPropMD5.equals(existingTaskPropMD5)) { + triggerInfo.setCronExpression(dt.getCronExpression()); + taskInfo.setTriggerInfo(triggerInfo); + taskInfo.setProperties(populateTaskProperties(tenantId, generatedTaskId, dt.getProperties())); + taskManager.registerTask(taskInfo); + taskManager.rescheduleTask(generatedTaskId); + if (log.isDebugEnabled()) { + log.debug("Task - '" + generatedTaskId + "' updated according to the dynamic task table"); + } + } + if (dt.isEnabled() + && taskManager.getTaskState(generatedTaskId) == TaskManager.TaskState.PAUSED) { + taskManager.resumeTask(generatedTaskId); + if (log.isDebugEnabled()) { + log.debug("Task - '" + generatedTaskId + "' enabled according to the dynamic task table"); + } + } else if (!dt.isEnabled() + && taskManager.getTaskState(generatedTaskId) != TaskManager.TaskState.PAUSED) { + taskManager.pauseTask(generatedTaskId); + if (log.isDebugEnabled()) { + log.debug("Task - '" + generatedTaskId + "' disabled according to the dynamic task table"); + } + } + break; + } + } + if (!isExist) { + TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); + triggerInfo.setCronExpression(dt.getCronExpression()); + TaskInfo taskInfo = new TaskInfo(generatedTaskId, dt.getTaskClassName(), + populateTaskProperties(tenantId, generatedTaskId, dt.getProperties()), triggerInfo); + taskManager.registerTask(taskInfo); + taskManager.scheduleTask(generatedTaskId); + if (log.isDebugEnabled()) { + log.debug("New task -'" + generatedTaskId + "' created according to the dynamic task table"); + } + } + } + PrivilegedCarbonContext.endTenantFlow(); + } + } + + private static Map populateTaskProperties(int tenantId, String generatedTaskId, + Map taskProperties) + throws TaskManagementException { + try { + int serverHashIdx = TaskWatcherDataHolder.getInstance().getHeartBeatService() + .getServerCtxInfo().getLocalServerHashIdx(); + taskProperties.put(TaskMgtConstants.Task.LOCAL_HASH_INDEX, String.valueOf(serverHashIdx)); + taskProperties.put(TaskMgtConstants.Task.LOCAL_TASK_NAME, generatedTaskId); + taskProperties.put(TaskMgtConstants.Task.TENANT_ID_PROP, String.valueOf(tenantId)); + return taskProperties; + } catch (HeartBeatManagementException e) { + String msg = "Unexpected exception when getting server hash index."; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } + } + + private static void deleteObsoleteTasks(TaskService nTaskService, List dynamicTasks) + throws TaskManagementException, TaskException { + + List tenants = new ArrayList<>(); + try { + RealmService realmService = TaskWatcherDataHolder.getInstance().getRealmService(); + Tenant[] tenantArray = realmService.getTenantManager().getAllTenants(); + if (tenantArray != null && tenantArray.length != 0) { + tenants.addAll(Arrays.asList(tenantArray)); + } + Tenant superTenant = new Tenant(); + superTenant.setId(-1234); + tenants.add(superTenant); + } catch (UserStoreException e) { + String msg = "Unable to load tenants"; + log.error(msg, e); + return; + } + + TaskManager taskManager; + Set hashIds; + try { + hashIds = TaskWatcherDataHolder.getInstance().getHeartBeatService().getActiveServers().keySet(); + } catch (HeartBeatManagementException e) { + String msg = "Unexpected exception when getting hash indexes of active servers"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } + + for (Tenant tenant : tenants) { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenant.getId(), true); + if (!nTaskService.getRegisteredTaskTypes().contains(TaskMgtConstants.Task.DYNAMIC_TASK_TYPE)) { + nTaskService.registerTaskType(TaskMgtConstants.Task.DYNAMIC_TASK_TYPE); + } + taskManager = nTaskService.getTaskManager(TaskMgtConstants.Task.DYNAMIC_TASK_TYPE); + List tasks = taskManager.getAllTasks(); + // Remove deleted items from the nTask core + for (TaskInfo taskInfo : tasks) { + boolean isExist = false; + for (DynamicTask dt : dynamicTasks) { + for (int hid : hashIds) { + if (tenant.getId() == dt.getTenantId() && + taskInfo.getName().equals(TaskManagementUtil.generateTaskId(dt.getDynamicTaskId(), hid))) { + isExist = true; + break; + } + } + if (isExist) { + break; + } + } + if (!isExist) { + taskManager.deleteTask(taskInfo.getName()); + if (log.isDebugEnabled()) { + log.debug("Task '" + taskInfo.getName() + "' deleted according to the dynamic task table"); + } + } + } + PrivilegedCarbonContext.endTenantFlow(); + } + } + +} diff --git a/components/task-mgt/task-watcher/io.entgra.task.mgt.watcher/src/main/java/io/entgra/task/mgt/watcher/internal/TaskWatcherDataHolder.java b/components/task-mgt/task-watcher/io.entgra.task.mgt.watcher/src/main/java/io/entgra/task/mgt/watcher/internal/TaskWatcherDataHolder.java new file mode 100755 index 0000000000..9e2953ae25 --- /dev/null +++ b/components/task-mgt/task-watcher/io.entgra.task.mgt.watcher/src/main/java/io/entgra/task/mgt/watcher/internal/TaskWatcherDataHolder.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.watcher.internal; + +import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; +import io.entgra.task.mgt.common.spi.TaskManagementService; +import org.wso2.carbon.ntask.core.service.TaskService; +import org.wso2.carbon.user.core.service.RealmService; + +public class TaskWatcherDataHolder { + private TaskManagementService taskManagerService; + + private TaskService nTaskService; + + private HeartBeatManagementService heartBeatService; + private RealmService realmService; + + private static final TaskWatcherDataHolder thisInstance = new TaskWatcherDataHolder(); + + private TaskWatcherDataHolder() {} + + public static TaskWatcherDataHolder getInstance() { + return thisInstance; + } + + public TaskManagementService getTaskManagementService() { + return taskManagerService; + } + + public void setTaskManagementService(TaskManagementService taskManagerService) { + this.taskManagerService = taskManagerService; + } + + public TaskService getnTaskService() { + return nTaskService; + } + + public void setnTaskService(TaskService nTaskService) { + this.nTaskService = nTaskService; + } + + public HeartBeatManagementService getHeartBeatService() { + return heartBeatService; + } + + public void setHeartBeatService(HeartBeatManagementService heartBeatService) { + this.heartBeatService = heartBeatService; + } + + public RealmService getRealmService() { + return this.realmService; + } + + public void setRealmService(RealmService realmService) { + this.realmService = realmService; + } + +} diff --git a/components/task-mgt/task-watcher/io.entgra.task.mgt.watcher/src/main/java/io/entgra/task/mgt/watcher/internal/TaskWatcherServiceComponent.java b/components/task-mgt/task-watcher/io.entgra.task.mgt.watcher/src/main/java/io/entgra/task/mgt/watcher/internal/TaskWatcherServiceComponent.java new file mode 100755 index 0000000000..209113df84 --- /dev/null +++ b/components/task-mgt/task-watcher/io.entgra.task.mgt.watcher/src/main/java/io/entgra/task/mgt/watcher/internal/TaskWatcherServiceComponent.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) 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.task.mgt.watcher.internal; + +import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; +import io.entgra.task.mgt.common.spi.TaskManagementService; +import io.entgra.task.mgt.core.config.TaskConfigurationManager; +import io.entgra.task.mgt.core.config.TaskManagementConfig; +import io.entgra.task.mgt.watcher.IoTSStartupHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.core.ServerStartupObserver; +import org.wso2.carbon.ntask.core.service.TaskService; +import org.wso2.carbon.user.core.service.RealmService; + +/** + * @scr.component + * name="io.entgra.task.mgt.watcher" immediate="true" + * @scr.reference name="app.mgt.ntask.component" + * interface="org.wso2.carbon.ntask.core.service.TaskService" + * cardinality="1..1" + * policy="dynamic" + * bind="setTaskService" + * unbind="unsetTaskService" + * @scr.reference name="io.entgra.task.mgt.service" + * interface="io.entgra.task.mgt.common.spi.TaskManagementService" + * cardinality="1..1" + * policy="dynamic" + * bind="setTaskMgtService" + * unbind="unsetTaskMgtService" + * @scr.reference name="entgra.heart.beat.service" + * interface="io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService" + * cardinality="0..1" + * policy="dynamic" + * bind="setHeartBeatService" + * unbind="unsetHeartBeatService" + * @scr.reference name="user.realmservice.default" + * interface="org.wso2.carbon.user.core.service.RealmService" + * cardinality="1..1" + * policy="dynamic" + * bind="setRealmService" + * unbind="unsetRealmService" + */ +public class TaskWatcherServiceComponent { + + private static final Log log = LogFactory.getLog(TaskWatcherServiceComponent.class); + + protected void activate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("Activating Task Watcher Service Component"); + } + try { + TaskManagementConfig taskManagementConfig = TaskConfigurationManager.getInstance().getTaskManagementConfig(); + if (taskManagementConfig.isTaskWatcherEnabled()) { + BundleContext bundleContext = ctx.getBundleContext(); + bundleContext.registerService(ServerStartupObserver.class.getName(), new IoTSStartupHandler(), null); + } else { + String msg = "Task watcher is not enabled in this environment hence wso2 carbon ntask will not " + + "update according to the task manager "; + log.debug(msg); + } + if (log.isDebugEnabled()) { + log.debug("Task Watcher Service Component has been successfully activated"); + } + } catch (Throwable e) { + log.error("Error occurred while activating Task Watcher Service Component", e); + } + } + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating Task Watcher Service Component"); + } + } + + @SuppressWarnings("unused") + public void setTaskService(TaskService taskService) { + if (log.isDebugEnabled()) { + log.debug("Setting the task service to Task Watcher Service Component "); + } + TaskWatcherDataHolder.getInstance().setnTaskService(taskService); + } + + @SuppressWarnings("unused") + protected void unsetTaskService(TaskService taskService) { + if (log.isDebugEnabled()) { + log.debug("Removing the task service from Task Watcher Service Component "); + } + TaskWatcherDataHolder.getInstance().setnTaskService(null); + } + + @SuppressWarnings("unused") + protected void setTaskMgtService(TaskManagementService taskManagementService) { + if (log.isDebugEnabled()) { + log.debug("Setting the task service to Task Watcher Service Component "); + } + TaskWatcherDataHolder.getInstance().setTaskManagementService(taskManagementService); + } + + @SuppressWarnings("unused") + protected void unsetTaskMgtService(TaskManagementService taskManagementService) { + if (log.isDebugEnabled()) { + log.debug("Removing the task service from Task Watcher Service Component "); + } + TaskWatcherDataHolder.getInstance().setTaskManagementService(null); + } + + @SuppressWarnings("unused") + protected void setHeartBeatService(HeartBeatManagementService heartBeatService) { + if (log.isDebugEnabled()) { + log.debug("Setting heart beat service to Task Manager Service Component"); + } + TaskWatcherDataHolder.getInstance().setHeartBeatService(heartBeatService); + } + + @SuppressWarnings("unused") + protected void unsetHeartBeatService(HeartBeatManagementService heartBeatManagementService) { + if (log.isDebugEnabled()) { + log.debug("Removing heart beat service from Task Manager Service Component"); + } + TaskWatcherDataHolder.getInstance().setHeartBeatService(null); + } + + /** + * Sets Realm Service. + * + * @param realmService An instance of RealmService + */ + @SuppressWarnings("unused") + protected void setRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Setting Realm Service"); + } + TaskWatcherDataHolder.getInstance().setRealmService(realmService); + } + + /** + * Unsets Realm Service. + * + * @param realmService An instance of RealmService + */ + @SuppressWarnings("unused") + protected void unsetRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Unsetting Realm Service"); + } + TaskWatcherDataHolder.getInstance().setRealmService(null); + } + +} diff --git a/components/task-mgt/task-watcher/pom.xml b/components/task-mgt/task-watcher/pom.xml new file mode 100755 index 0000000000..23d376c072 --- /dev/null +++ b/components/task-mgt/task-watcher/pom.xml @@ -0,0 +1,38 @@ + + + + + + org.wso2.carbon.devicemgt + task-mgt + 5.0.21-SNAPSHOT + ../pom.xml + + + 4.0.0 + task-watcher + Entgra IoT - Task Watcher Component + pom + http://entgra.io + + + io.entgra.task.mgt.watcher + + + \ No newline at end of file diff --git a/components/transport-mgt/email-sender/org.wso2.carbon.email.sender.core/pom.xml b/components/transport-mgt/email-sender/org.wso2.carbon.email.sender.core/pom.xml index 40b9eca423..e36ee469ff 100644 --- a/components/transport-mgt/email-sender/org.wso2.carbon.email.sender.core/pom.xml +++ b/components/transport-mgt/email-sender/org.wso2.carbon.email.sender.core/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt email-sender - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/email-sender/pom.xml b/components/transport-mgt/email-sender/pom.xml index fb2fb75815..e5d79a0c6c 100644 --- a/components/transport-mgt/email-sender/pom.xml +++ b/components/transport-mgt/email-sender/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt transport-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/pom.xml b/components/transport-mgt/pom.xml index 7d745fe489..fb8cf3777c 100644 --- a/components/transport-mgt/pom.xml +++ b/components/transport-mgt/pom.xml @@ -3,7 +3,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api/pom.xml b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api/pom.xml index 949fd17fb8..c2f4f05076 100644 --- a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt sms-handler - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.common/pom.xml b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.common/pom.xml index 157cd9b525..6fcf7686ac 100644 --- a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.common/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.common/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt sms-handler - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.core/pom.xml b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.core/pom.xml index 4b595c6713..6088ee0053 100644 --- a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.core/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.core/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt sms-handler - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/pom.xml b/components/transport-mgt/sms-handler/pom.xml index 26692cbe03..63039c781f 100644 --- a/components/transport-mgt/sms-handler/pom.xml +++ b/components/transport-mgt/sms-handler/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt transport-mgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/pom.xml b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/pom.xml index e6a9a9be20..1c585b5b74 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/pom.xml +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/pom.xml @@ -21,7 +21,7 @@ ui-request-interceptor io.entgra.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT 4.0.0 diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/HubspotHandler.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/HubspotHandler.java new file mode 100644 index 0000000000..b649d341fe --- /dev/null +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/HubspotHandler.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 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.ui.request.interceptor; + +import com.google.gson.JsonObject; +import io.entgra.ui.request.interceptor.beans.ProxyResponse; +import io.entgra.ui.request.interceptor.util.HandlerConstants; +import io.entgra.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.HttpGet; +import org.apache.http.client.methods.HttpPost; + +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( + name = "HubspotRequestHandlerServlet", + description = "", + urlPatterns = { + "/hubspot/*" + } +) +public class HubspotHandler extends HttpServlet { + + private static final Log log = LogFactory.getLog(HubspotHandler.class); + private HttpSession httpSession; + private static String hubspotEndpoint; + private static String chatConfig; + private JsonObject uiConfigJsonObject; + private static String gatewayUrl; + private static String iotsCoreUrl; + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) { + try { + if (validateRequest(req, resp)) { + HttpPost postRequest = new HttpPost(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint)); + HandlerUtil.generateChatRequestEntity(req, postRequest); + postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); + postRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig); + ProxyResponse proxyResponse = HandlerUtil.execute(postRequest); + HandlerUtil.handleSuccess(resp, proxyResponse); + } + } catch (IOException e) { + log.error("Error occurred when processing POST request.", e); + } + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) { + try { + if (validateRequest(req, resp)) { + HttpGet getRequest = new HttpGet(HandlerUtil.generateBackendRequestURL(req,hubspotEndpoint)); + getRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); + getRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig); + ProxyResponse proxyResponse = HandlerUtil.execute(getRequest); + HandlerUtil.handleSuccess(resp, proxyResponse); + } + } catch (IOException e) { + log.error("Error occurred when processing GET request.", e); + } + } + + /*** + * Validates the hubspot's incoming request. + * + * @param req {@link HttpServletRequest} + * @param resp {@link HttpServletResponse} + * @return If request is a valid one, returns TRUE, otherwise return FALSE + * @throws IOException If and error occurs while witting error response to client side + */ + private boolean validateRequest(HttpServletRequest req, HttpServletResponse resp) + throws IOException { + httpSession = req.getSession(false); + if (httpSession == null) { + log.error("Unauthorized, You are not logged in. Please log in to the portal"); + HandlerUtil.handleError(resp, HttpStatus.SC_UNAUTHORIZED); + return false; + } + if (req.getMethod() == null) { + log.error("Bad Request, Request method is empty"); + HandlerUtil.handleError(resp, HttpStatus.SC_BAD_REQUEST); + return false; + } + gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); + iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme()); + String uiConfigUrl = iotsCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT; + uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); + chatConfig = uiConfigJsonObject.get("hubspotChat").getAsJsonObject().get("accessToken").getAsString(); + hubspotEndpoint = HandlerConstants.HTTPS_PROTOCOL + HandlerConstants.SCHEME_SEPARATOR + HandlerConstants.HUBSPOT_CHAT_URL; + return true; + } +} diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerConstants.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerConstants.java index bf9947a9af..27d6afaadc 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerConstants.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerConstants.java @@ -105,4 +105,5 @@ public class HandlerConstants { public static final String IOT_GW_HTTPS_PORT_ENV_VAR = "iot.gateway.https.port"; public static final String IOT_REPORTING_WEBAPP_HOST_ENV_VAR = "iot.reporting.webapp.host"; public static final String USER_SCOPES = "userScopes"; + public static final String HUBSPOT_CHAT_URL = "api.hubapi.com"; } diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java index fb565bf59b..b7376abddc 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java @@ -435,6 +435,23 @@ public class HandlerUtil { } } + /** + * Generate te request entity for POST requests from the hubspot's incoming request. + * + * @param req incoming {@link HttpServletRequest}. + * @param proxyRequest proxy request instance. + * @throws IOException If error occurred while generating the request body. + */ + public static void generateChatRequestEntity(HttpServletRequest req, HttpEntityEnclosingRequestBase proxyRequest) + throws IOException { + if (StringUtils.isNotEmpty(req.getHeader(HttpHeaders.CONTENT_LENGTH)) || + StringUtils.isNotEmpty(req.getHeader(HttpHeaders.TRANSFER_ENCODING))) { + InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), + Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH))); + proxyRequest.setEntity(new BufferedHttpEntity(entity)); + } + } + /*** * Constructs the application registration payload for DCR. * diff --git a/components/ui-request-interceptor/pom.xml b/components/ui-request-interceptor/pom.xml index 8477f97879..d849368d9b 100644 --- a/components/ui-request-interceptor/pom.xml +++ b/components/ui-request-interceptor/pom.xml @@ -21,7 +21,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml index 9dc0e25218..f11df1e3a4 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.devicemgt webapp-authenticator-framework - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/components/webapp-authenticator-framework/pom.xml b/components/webapp-authenticator-framework/pom.xml index 3ffd5ca338..b1a10ee9f5 100644 --- a/components/webapp-authenticator-framework/pom.xml +++ b/components/webapp-authenticator-framework/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/features/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.api.feature/pom.xml b/features/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.api.feature/pom.xml index 32f3e183cd..0c7462faaf 100644 --- a/features/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.api.feature/pom.xml +++ b/features/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.api.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt grafana-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.server.feature/pom.xml b/features/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.server.feature/pom.xml index 30a1342c73..6d3e16a063 100644 --- a/features/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.server.feature/pom.xml +++ b/features/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.server.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt grafana-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/analytics-mgt/grafana-mgt/pom.xml b/features/analytics-mgt/grafana-mgt/pom.xml index 1526f52946..787ea0747f 100644 --- a/features/analytics-mgt/grafana-mgt/pom.xml +++ b/features/analytics-mgt/grafana-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt analytics-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/analytics-mgt/pom.xml b/features/analytics-mgt/pom.xml index 3e0c361e02..ccb9f84d26 100644 --- a/features/analytics-mgt/pom.xml +++ b/features/analytics-mgt/pom.xml @@ -3,7 +3,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml index ba1696ca43..0d9d2b9d6a 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.devicemgt apimgt-extensions-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.feature/pom.xml index 8a676873d8..b6a28994d8 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.feature/pom.xml +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.feature/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.devicemgt apimgt-extensions-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml index 6c9e2929ae..c1b4c92172 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.devicemgt apimgt-extensions-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/pom.xml b/features/apimgt-extensions/pom.xml index ef802e791f..45a706e7a9 100644 --- a/features/apimgt-extensions/pom.xml +++ b/features/apimgt-extensions/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/features/application-mgt/io.entgra.application.mgt.api.feature/pom.xml b/features/application-mgt/io.entgra.application.mgt.api.feature/pom.xml index 9beeb2a45f..d215fd6e29 100644 --- a/features/application-mgt/io.entgra.application.mgt.api.feature/pom.xml +++ b/features/application-mgt/io.entgra.application.mgt.api.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt application-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/application-mgt/io.entgra.application.mgt.server.feature/pom.xml b/features/application-mgt/io.entgra.application.mgt.server.feature/pom.xml index a29aef3b8b..e1447edb86 100644 --- a/features/application-mgt/io.entgra.application.mgt.server.feature/pom.xml +++ b/features/application-mgt/io.entgra.application.mgt.server.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt application-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql index bb85e18ffa..f9c5861831 100644 --- a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql +++ b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql @@ -117,7 +117,8 @@ CREATE TABLE IF NOT EXISTS AP_DEVICE_SUBSCRIPTION( PRIMARY KEY (ID), CONSTRAINT fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1 FOREIGN KEY (AP_APP_RELEASE_ID) - REFERENCES AP_APP_RELEASE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + REFERENCES AP_APP_RELEASE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT uq_AP_DEVICE_SUBSCRIPTION UNIQUE (DM_DEVICE_ID, AP_APP_RELEASE_ID) ); CREATE INDEX fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_DEVICE_SUBSCRIPTION (AP_APP_RELEASE_ID ASC); diff --git a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql index 754eaca191..9b2e89b3f7 100644 --- a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql +++ b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql @@ -1,6 +1,7 @@ -- ----------------------------------------------------- -- Table AP_APP -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_APP]') AND TYPE IN (N'U')) CREATE TABLE AP_APP( ID INTEGER NOT NULL IDENTITY, NAME VARCHAR(350) NOT NULL, @@ -18,6 +19,7 @@ CREATE TABLE AP_APP( -- ----------------------------------------------------- -- Table AP_APP_RELEASE -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_APP_RELEASE]') AND TYPE IN (N'U')) CREATE TABLE AP_APP_RELEASE( ID INTEGER NOT NULL IDENTITY, DESCRIPTION VARCHAR(max) NOT NULL, @@ -52,6 +54,7 @@ CREATE INDEX fk_AP_APP_RELEASE_AP_APP1_idx ON AP_APP_RELEASE (AP_APP_ID ASC); -- ----------------------------------------------------- -- Table AP_APP_REVIEW -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_APP_REVIEW]') AND TYPE IN (N'U')) CREATE TABLE AP_APP_REVIEW( ID INTEGER NOT NULL IDENTITY, TENANT_ID INTEGER NOT NULL, @@ -74,6 +77,7 @@ CREATE INDEX fk_AP_APP_COMMENT_AP_APP_RELEASE1_idx ON AP_APP_REVIEW (AP_APP_RELE -- ----------------------------------------------------- -- Table AP_APP_LIFECYCLE_STATE -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_APP_LIFECYCLE_STATE]') AND TYPE IN (N'U')) CREATE TABLE AP_APP_LIFECYCLE_STATE( ID INTEGER NOT NULL IDENTITY, CURRENT_STATE VARCHAR(45) NOT NULL, @@ -93,6 +97,7 @@ CREATE INDEX fk_AP_APP_LIFECYCLE_STATE_AP_APP_RELEASE1_idx ON AP_APP_LIFECYCLE_S -- ----------------------------------------------------- -- Table AP_APP_TAG -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_APP_TAG]') AND TYPE IN (N'U')) CREATE TABLE AP_APP_TAG( ID INTEGER NOT NULL IDENTITY, TENANT_ID INTEGER NOT NULL, @@ -103,6 +108,7 @@ CREATE TABLE AP_APP_TAG( -- ----------------------------------------------------- -- Table AP_DEVICE_SUBSCRIPTION -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_DEVICE_SUBSCRIPTION]') AND TYPE IN (N'U')) CREATE TABLE AP_DEVICE_SUBSCRIPTION( ID INTEGER NOT NULL IDENTITY, TENANT_ID INTEGER NOT NULL, @@ -118,13 +124,15 @@ CREATE TABLE AP_DEVICE_SUBSCRIPTION( PRIMARY KEY (ID), CONSTRAINT fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1 FOREIGN KEY (AP_APP_RELEASE_ID) - REFERENCES AP_APP_RELEASE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + REFERENCES AP_APP_RELEASE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT uq_AP_DEVICE_SUBSCRIPTION UNIQUE (DM_DEVICE_ID, AP_APP_RELEASE_ID) ); CREATE INDEX fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_DEVICE_SUBSCRIPTION (AP_APP_RELEASE_ID ASC); -- ----------------------------------------------------- -- Table AP_GROUP_SUBSCRIPTION -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_GROUP_SUBSCRIPTION]') AND TYPE IN (N'U')) CREATE TABLE AP_GROUP_SUBSCRIPTION( ID INTEGER NOT NULL IDENTITY, TENANT_ID INTEGER NOT NULL, @@ -145,6 +153,7 @@ CREATE INDEX fk_AP_GROUP_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_GROUP_SUBSCRIPTI -- ----------------------------------------------------- -- Table AP_ROLE_SUBSCRIPTION -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_ROLE_SUBSCRIPTION]') AND TYPE IN (N'U')) CREATE TABLE AP_ROLE_SUBSCRIPTION( ID INTEGER NOT NULL IDENTITY, TENANT_ID INTEGER NOT NULL, @@ -165,6 +174,7 @@ CREATE INDEX fk_AP_ROLE_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_ROLE_SUBSCRIPTION -- ----------------------------------------------------- -- Table AP_UNRESTRICTED_ROLE -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_UNRESTRICTED_ROLE]') AND TYPE IN (N'U')) CREATE TABLE AP_UNRESTRICTED_ROLE( ID INTEGER NOT NULL IDENTITY, TENANT_ID INTEGER NOT NULL, @@ -180,6 +190,7 @@ CREATE INDEX fk_AP_APP_VISIBILITY_AP_APP1_idx ON AP_UNRESTRICTED_ROLE (AP_APP_ID -- ----------------------------------------------------- -- Table AP_USER_SUBSCRIPTION -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_USER_SUBSCRIPTION]') AND TYPE IN (N'U')) CREATE TABLE AP_USER_SUBSCRIPTION( ID INTEGER NOT NULL IDENTITY, TENANT_ID INTEGER NOT NULL, @@ -200,6 +211,7 @@ CREATE INDEX fk_AP_USER_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_USER_SUBSCRIPTION -- ----------------------------------------------------- -- Table AP_APP_CATEGORY -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_APP_CATEGORY]') AND TYPE IN (N'U')) CREATE TABLE AP_APP_CATEGORY( ID INTEGER NOT NULL IDENTITY, TENANT_ID INTEGER NOT NULL, @@ -211,6 +223,7 @@ CREATE TABLE AP_APP_CATEGORY( -- ----------------------------------------------------- -- Table AP_APP_TAG_MAPPING -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_APP_TAG_MAPPING]') AND TYPE IN (N'U')) CREATE TABLE AP_APP_TAG_MAPPING( ID INTEGER NOT NULL IDENTITY, TENANT_ID INTEGER NOT NULL, @@ -230,6 +243,7 @@ CREATE INDEX fk_AP_APP_TAG_copy1_AP_APP1_idx ON AP_APP_TAG_MAPPING (AP_APP_ID AS -- ----------------------------------------------------- -- Table AP_APP_CATEGORY_MAPPING -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_APP_CATEGORY_MAPPING]') AND TYPE IN (N'U')) CREATE TABLE AP_APP_CATEGORY_MAPPING( ID INTEGER NOT NULL IDENTITY, TENANT_ID INTEGER NOT NULL, @@ -249,6 +263,7 @@ CREATE INDEX fk_AP_APP_CATEGORY_copy1_AP_APP1_idx ON AP_APP_CATEGORY_MAPPING (AP -- ----------------------------------------------------- -- Table AP_APP_SUB_OP_MAPPING -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_APP_SUB_OP_MAPPING]') AND TYPE IN (N'U')) CREATE TABLE AP_APP_SUB_OP_MAPPING ( ID INTEGER NOT NULL IDENTITY, TENANT_ID INTEGER NOT NULL, @@ -264,6 +279,7 @@ CREATE INDEX fk_AP_APP_SUB_OP_MAPPING_AP_DEVICE_SUBSCRIPTION1_idx ON AP_APP_SUB_ -- ----------------------------------------------------- -- Table AP_SCHEDULED_SUBSCRIPTION -- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_SCHEDULED_SUBSCRIPTION]') AND TYPE IN (N'U')) CREATE TABLE AP_SCHEDULED_SUBSCRIPTION( ID INTEGER NOT NULL IDENTITY, TASK_NAME VARCHAR(100) NOT NULL, @@ -283,7 +299,8 @@ CREATE TABLE AP_SCHEDULED_SUBSCRIPTION( -- ----------------------------------------------------- -- Table AP_IDENTITY_SERVER -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS AP_IDENTITY_SERVER ( +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_IDENTITY_SERVER]') AND TYPE IN (N'U')) +CREATE TABLE AP_IDENTITY_SERVER ( ID INTEGER NOT NULL IDENTITY, NAME VARCHAR(255) NOT NULL, PROVIDER_NAME VARCHAR(255) NOT NULL, @@ -298,8 +315,9 @@ CREATE TABLE IF NOT EXISTS AP_IDENTITY_SERVER ( -- ----------------------------------------------------- -- Table AP_IS_SP_APP_MAPPING --- -----------------------------------------------------; -CREATE TABLE IF NOT EXISTS AP_IS_SP_APP_MAPPING ( +-- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_IS_SP_APP_MAPPING]') AND TYPE IN (N'U')) +CREATE TABLE AP_IS_SP_APP_MAPPING ( ID INTEGER NOT NULL IDENTITY, SP_UID VARCHAR(255) NOT NULL, AP_APP_ID INT NOT NULL, @@ -313,7 +331,8 @@ CREATE TABLE IF NOT EXISTS AP_IS_SP_APP_MAPPING ( -- ----------------------------------------------------- -- Table AP_APP_FAVOURITES -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS AP_APP_FAVOURITES( +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AP_APP_FAVOURITES]') AND TYPE IN (N'U')) +CREATE TABLE AP_APP_FAVOURITES( ID INTEGER NOT NULL IDENTITY, AP_APP_ID INTEGER NOT NULL, USER_NAME VARCHAR(100) NOT NULL, diff --git a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql index 6070139961..54ba58a9fe 100644 --- a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql +++ b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql @@ -104,7 +104,8 @@ CREATE TABLE IF NOT EXISTS AP_DEVICE_SUBSCRIPTION( DM_DEVICE_ID INTEGER NOT NULL, AP_APP_RELEASE_ID INTEGER NOT NULL, PRIMARY KEY (ID), - CONSTRAINT fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1 FOREIGN KEY (AP_APP_RELEASE_ID) REFERENCES AP_APP_RELEASE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + CONSTRAINT fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1 FOREIGN KEY (AP_APP_RELEASE_ID) REFERENCES AP_APP_RELEASE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT uq_AP_DEVICE_SUBSCRIPTION UNIQUE (DM_DEVICE_ID, AP_APP_RELEASE_ID) ); CREATE INDEX fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_DEVICE_SUBSCRIPTION (AP_APP_RELEASE_ID ASC); -- ----------------------------------------------------- diff --git a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql index 946d720dfd..e8e1dbb225 100644 --- a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql +++ b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql @@ -129,7 +129,8 @@ CREATE TABLE IF NOT EXISTS AP_DEVICE_SUBSCRIPTION( PRIMARY KEY (ID), CONSTRAINT fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1 FOREIGN KEY (AP_APP_RELEASE_ID) - REFERENCES AP_APP_RELEASE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + REFERENCES AP_APP_RELEASE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT uq_AP_DEVICE_SUBSCRIPTION UNIQUE (DM_DEVICE_ID, AP_APP_RELEASE_ID) ); CREATE INDEX fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_DEVICE_SUBSCRIPTION (AP_APP_RELEASE_ID ASC); diff --git a/features/application-mgt/pom.xml b/features/application-mgt/pom.xml index 66b040bcdd..527c8a633d 100644 --- a/features/application-mgt/pom.xml +++ b/features/application-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.api.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.api.feature/pom.xml index 0653561d5e..2bd79de79e 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.api.feature/pom.xml +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.api.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt certificate-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml index 30215f2ee2..7c9fb7153e 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt certificate-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml index 0d39f02701..b730341140 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt certificate-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/pom.xml b/features/certificate-mgt/pom.xml index cc903aa17e..05fdb44cc1 100644 --- a/features/certificate-mgt/pom.xml +++ b/features/certificate-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.extensions.defaultrole.manager.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.extensions.defaultrole.manager.feature/pom.xml index 29aacad17b..54e8544e67 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.extensions.defaultrole.manager.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.extensions.defaultrole.manager.feature/pom.xml @@ -23,7 +23,7 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.extensions.logger.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.extensions.logger.feature/pom.xml index a4b1e41bbc..b9eaed372f 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.extensions.logger.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.extensions.logger.feature/pom.xml @@ -23,7 +23,7 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.extensions.stateengine.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.extensions.stateengine.feature/pom.xml index b1bb7519b3..1046d773c9 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.extensions.stateengine.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.extensions.stateengine.feature/pom.xml @@ -23,7 +23,7 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature/pom.xml index c4aa1edfee..0678d1bbe6 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml index 23097f159c..4d38c3719b 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature/pom.xml index 56eeb0bfcc..5ee749568c 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml index a930e180c0..ae887ab14c 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml index 86c64be043..314b1a82b3 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/pom.xml b/features/device-mgt-extensions/pom.xml index fcb0afbb85..1c98737cfa 100644 --- a/features/device-mgt-extensions/pom.xml +++ b/features/device-mgt-extensions/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml index cf1749359d..0bb36492df 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/pom.xml index e33829a360..ba9e88437c 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml index 989e6209a7..fafc2dce73 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml @@ -207,5 +207,9 @@ + + false + Replace with mail + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/datasources/cdm-datasources.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/datasources/cdm-datasources.xml index 78db49688e..4494b4fcd6 100755 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/datasources/cdm-datasources.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/datasources/cdm-datasources.xml @@ -61,5 +61,25 @@ + + EVENT_DB + The datasource used for event storing + + jdbc/EVENT_DB + + + + jdbc:h2:./repository/database/EVENT_DB;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE;LOCK_TIMEOUT=60000 + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml index 4bae2c2e64..8012642fe5 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml @@ -24,6 +24,15 @@ 3600 10000 + + + false + tracking_url + + access_token + sender_actorId + channel_AccountId + false true @@ -100,6 +109,7 @@ perm:devices:details perm:devices:update perm:devices:view + perm:devices:enrollment-guide:view perm:view-configuration perm:manage-configuration perm:policies:remove @@ -129,6 +139,7 @@ perm:groups:add perm:groups:device perm:groups:devices-count + perm:groups:devices-types perm:groups:remove perm:groups:groups perm:groups:groups-view @@ -214,6 +225,7 @@ perm:admin:tenant:view perm:admin:metadata:view perm:admin:usage:view + perm:android:alternate-install device-mgt diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 index c985f6d068..5c6162f385 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 @@ -322,8 +322,8 @@ - - + + <a href='https://entgra.io' target='_blank'> Entgra @@ -332,16 +332,16 @@ , All Rights Reserved. Entgra - - repository/resources/whitelabel - favicon.png - logo.png - icon.png - default - - + + repository/resources/whitelabel + favicon.png + logo.png + icon.png + default + + - + @@ -369,6 +369,15 @@ {% endfor %} {% endif%} - + + + {% if device_mgt_conf.enrollment_guide_conf is defined %} + {{device_mgt_conf.enrollment_guide_conf.enable}} + {{device_mgt_conf.enrollment_guide_conf.mail}} + {% else %} + false + Replace with mail + {% endif %} + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/cdm-datasources.xml.j2 b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/cdm-datasources.xml.j2 index e9105a8d3e..81e6ed9714 100755 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/cdm-datasources.xml.j2 +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/cdm-datasources.xml.j2 @@ -83,5 +83,36 @@ + + EVENT_DB + The datasource used for event storing + + jdbc/EVENT_DB + + + + {% if database.device_mgt_event_db is defined %} + {{database.device_mgt_event_db.url}} + {{database.device_mgt_event_db.username}} + {{database.device_mgt_event_db.password}} + {{database.device_mgt_event_db.driver}} + {{database.device_mgt_event_db.validationQuery}} + {% for property_name,property_value in database.device_mgt_event_db.pool_options.items() %} + <{{property_name}}>{{property_value}} + {% endfor %} + {% else %} + jdbc:h2:./repository/database/EVENT_DB;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE;LOCK_TIMEOUT=60000 + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + {% endif %} + + + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql index 0e8d1b8466..f383c5d5b9 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -765,3 +765,25 @@ CREATE TABLE IF NOT EXISTS DM_EXT_PERMISSION_MAPPING ( TRACCAR_USER_ID INT DEFAULT 0 ); -- END OF DM_EXT_PERMISSION_MAPPING TABLE-- + +-- DYNAMIC TASK TABLES-- +CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( + DYNAMIC_TASK_ID INTEGER AUTO_INCREMENT NOT NULL, + NAME VARCHAR(300) DEFAULT NULL , + CRON VARCHAR(8000) DEFAULT NULL, + IS_ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TASK_CLASS_NAME VARCHAR(8000) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (DYNAMIC_TASK_ID) +); + +CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( + DYNAMIC_TASK_ID INTEGER NOT NULL, + PROPERTY_NAME VARCHAR(100) DEFAULT 0, + PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, + TENANT_ID VARCHAR(100), + PRIMARY KEY (DYNAMIC_TASK_ID, PROPERTY_NAME, TENANT_ID), + CONSTRAINT FK_DYNAMIC_TASK_TASK_PROPERTIES FOREIGN KEY (DYNAMIC_TASK_ID) REFERENCES + DYNAMIC_TASK (DYNAMIC_TASK_ID) ON DELETE CASCADE ON UPDATE CASCADE +); +-- END OF DYNAMIC TASK TABLE-- \ No newline at end of file diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql index a682f457be..1c22ba25fc 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -120,21 +120,6 @@ CREATE TABLE DM_OPERATION ( PRIMARY KEY (ID) ); -IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_DEVICE_STATUS]') AND TYPE IN (N'U')) -CREATE TABLE DM_DEVICE_STATUS ( - ID INTEGER IDENTITY(1,1) NOT NULL, - ENROLMENT_ID INTEGER NOT NULL, - DEVICE_ID INTEGER NOT NULL, - STATUS VARCHAR(50) DEFAULT NULL, - UPDATE_TIME DATETIME2 DEFAULT NULL, - CHANGED_BY VARCHAR(255) NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT FK_DM_DEVICE_STATUS_DEVICE FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT FK_DM_DEVICE_STATUS_ENROLMENT FOREIGN KEY (ENROLMENT_ID) REFERENCES - DM_ENROLMENT (ID) ON DELETE CASCADE ON UPDATE CASCADE -); - 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, @@ -151,6 +136,21 @@ CREATE TABLE DM_ENROLMENT ( DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_DEVICE_STATUS]') AND TYPE IN (N'U')) +CREATE TABLE DM_DEVICE_STATUS ( + ID INTEGER IDENTITY(1,1) NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + DEVICE_ID INTEGER NOT NULL, + STATUS VARCHAR(50) DEFAULT NULL, + UPDATE_TIME DATETIME2 DEFAULT NULL, + CHANGED_BY VARCHAR(255) NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_DEVICE_STATUS_DEVICE FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT FK_DM_DEVICE_STATUS_ENROLMENT FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID) ON DELETE CASCADE ON UPDATE CASCADE +); + IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_ENROLMENT_FK_DEVICE_ID' AND OBJECT_ID = OBJECT_ID('DM_ENROLMENT')) CREATE INDEX IDX_ENROLMENT_FK_DEVICE_ID ON DM_ENROLMENT(DEVICE_ID); IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_ENROLMENT_DEVICE_ID_TENANT_ID' AND OBJECT_ID = OBJECT_ID('DM_ENROLMENT')) @@ -639,10 +639,10 @@ CREATE TABLE 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(8000) NOT NULL, CREATED_AT DATETIME2(0) NOT NULL, EXPIRY_TIME INT NOT NULL DEFAULT 3600, - IS_EXPIRED BIT DEFAULT false, + IS_EXPIRED BIT DEFAULT 0, PRIMARY KEY (ID), CONSTRAINT email_type_uk UNIQUE (EMAIL, EMAIL_TYPE) ); @@ -718,8 +718,8 @@ CREATE TABLE DM_GEOFENCE ( ID INT IDENTITY NOT NULL, FENCE_NAME VARCHAR(255) NOT NULL, DESCRIPTION VARCHAR(MAX) DEFAULT NULL, - LATITUDE DECIMAL(3,5) DEFAULT NULL, - LONGITUDE DECIMAL(3,5) DEFAULT NULL, + LATITUDE FLOAT DEFAULT NULL, + LONGITUDE FLOAT DEFAULT NULL, RADIUS DECIMAL(30,4) DEFAULT NULL, GEO_JSON VARCHAR(MAX) DEFAULT NULL, FENCE_SHAPE VARCHAR(100) DEFAULT NULL, @@ -730,3 +730,27 @@ CREATE TABLE DM_GEOFENCE ( ); -- END OF DM_GEOFENCE TABLE-- + +-- DYNAMIC TASK TABLES-- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DYNAMIC_TASK]') AND TYPE IN (N'U')) +CREATE TABLE DYNAMIC_TASK ( + DYNAMIC_TASK_ID INTEGER IDENTITY(1,1) NOT NULL, + NAME VARCHAR(255) DEFAULT NULL , + CRON VARCHAR(8000) DEFAULT NULL, + IS_ENABLED BIT NOT NULL DEFAULT 0, + TASK_CLASS_NAME VARCHAR(8000) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (DYNAMIC_TASK_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DYNAMIC_TASK_PROPERTIES]') AND TYPE IN (N'U')) +CREATE TABLE DYNAMIC_TASK_PROPERTIES ( + DYNAMIC_TASK_ID INTEGER NOT NULL, + PROPERTY_NAME VARCHAR(100) DEFAULT 0, + PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, + TENANT_ID VARCHAR(100), + PRIMARY KEY (DYNAMIC_TASK_ID, PROPERTY_NAME, TENANT_ID), + CONSTRAINT FK_DYNAMIC_TASK_TASK_PROPERTIES FOREIGN KEY (DYNAMIC_TASK_ID) REFERENCES + DYNAMIC_TASK (DYNAMIC_TASK_ID) ON DELETE CASCADE ON UPDATE CASCADE +); +-- END OF DYNAMIC TASK TABLE-- \ No newline at end of file diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql index 33ac7964dd..17c7460c97 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -829,3 +829,25 @@ CREATE TABLE IF NOT EXISTS DM_EXT_PERMISSION_MAPPING ( TRACCAR_USER_ID INT DEFAULT 0 ); -- END OF DM_EXT_PERMISSION_MAPPING TABLE-- + +-- DYNAMIC TASK TABLES-- +CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( + DYNAMIC_TASK_ID INTEGER AUTO_INCREMENT NOT NULL, + NAME VARCHAR(300) DEFAULT NULL , + CRON VARCHAR(8000) DEFAULT NULL, + IS_ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TASK_CLASS_NAME VARCHAR(8000) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (DYNAMIC_TASK_ID) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( + DYNAMIC_TASK_ID INTEGER NOT NULL, + PROPERTY_NAME VARCHAR(100) DEFAULT 0, + PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, + TENANT_ID VARCHAR(100), + PRIMARY KEY (DYNAMIC_TASK_ID, PROPERTY_NAME, TENANT_ID), + CONSTRAINT FK_DYNAMIC_TASK_TASK_PROPERTIES FOREIGN KEY (DYNAMIC_TASK_ID) REFERENCES + DYNAMIC_TASK (DYNAMIC_TASK_ID) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB; +-- END OF DYNAMIC TASK TABLE-- diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql index bbfe9bbcfb..a5d3725548 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -1096,5 +1096,26 @@ CREATE TABLE DM_GEOFENCE ( TENANT_ID NUMBER(10) DEFAULT 0, CONSTRAINT PK_DM_GEOFENCE PRIMARY KEY (ID) ); - -- END OF DM_GEOFENCE TABLE-- + +-- DYNAMIC TASK TABLES-- +CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( + DYNAMIC_TASK_ID NUMBER(10) NOT NULL, + NAME VARCHAR2(300) DEFAULT NULL , + CRON VARCHAR2(8000) DEFAULT NULL, + IS_ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TASK_CLASS_NAME VARCHAR2(8000) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + CONSTRAINT PK_DYNAMIC_TASK PRIMARY KEY (DYNAMIC_TASK_ID) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( + DYNAMIC_TASK_ID INTEGER NOT NULL, + PROPERTY_NAME VARCHAR2(100) DEFAULT 0, + PROPERTY_VALUE VARCHAR2(100) DEFAULT NULL, + TENANT_ID VARCHAR2(100), + CONSTRAINT PK_DYNAMIC_TASK_PROPERTIES PRIMARY KEY (DYNAMIC_TASK_ID, PROPERTY_NAME, TENANT_ID), + CONSTRAINT FK_DYNAMIC_TASK_TASK_PROPERTIES FOREIGN KEY (DYNAMIC_TASK_ID) REFERENCES + DYNAMIC_TASK (DYNAMIC_TASK_ID) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB; +-- END OF DYNAMIC TASK TABLE-- diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql index 67ba8f1b6a..731f086c61 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -750,3 +750,25 @@ CREATE TABLE IF NOT EXISTS DM_GEOFENCE ( ); -- END OF DM_GEOFENCE TABLE-- + +-- DYNAMIC TASK TABLES-- +CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( + DYNAMIC_TASK_ID INTEGER DEFAULT NEXTVAL ('DYNAMIC_TASK_seq') NOT NULL, + NAME VARCHAR(300) DEFAULT NULL , + CRON VARCHAR(8000) DEFAULT NULL, + IS_ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TASK_CLASS_NAME VARCHAR(8000) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (DYNAMIC_TASK_ID) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( + DYNAMIC_TASK_ID INTEGER NOT NULL, + PROPERTY_NAME VARCHAR(100) DEFAULT 0, + PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, + TENANT_ID VARCHAR(100), + PRIMARY KEY (DYNAMIC_TASK_ID, PROPERTY_NAME, TENANT_ID), + CONSTRAINT FK_DYNAMIC_TASK_TASK_PROPERTIES FOREIGN KEY (DYNAMIC_TASK_ID) REFERENCES + DYNAMIC_TASK (DYNAMIC_TASK_ID) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB; +-- END OF DYNAMIC TASK TABLE-- diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.extensions.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.extensions.feature/pom.xml index f0e0bd1b1a..31ff541dfc 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.extensions.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.extensions.feature/pom.xml @@ -4,7 +4,7 @@ org.wso2.carbon.devicemgt device-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.feature/pom.xml index 900ec36b6a..ae68720cf9 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml index e72a0e0e0c..59113b6e91 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/pom.xml b/features/device-mgt/pom.xml index 6aa8b07dbe..e606feaa46 100644 --- a/features/device-mgt/pom.xml +++ b/features/device-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml b/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml index 7892b1fd48..6c21432c0b 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt heart-beat-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/heart-beat-datasources.xml.j2 b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/heart-beat-datasources.xml.j2 index 524f28c42a..2360744fe6 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/heart-beat-datasources.xml.j2 +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/heart-beat-datasources.xml.j2 @@ -39,10 +39,10 @@ <{{property_name}}>{{property_value}} {% endfor %} {% else %} - jdbc:mysql://localhost:3306/heart_beat - root - root - com.mysql.jdbc.Driver + jdbc:h2:./repository/database/HEART_BEAT_DB;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE + wso2carbon + wso2carbon + org.h2.Driver 50 60000 true diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml index a3c656b757..ebbe5087f2 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml @@ -29,10 +29,10 @@ - jdbc:mysql://localhost:3306/heart_beat - root - root - com.mysql.jdbc.Driver + jdbc:h2:./repository/database/HEART_BEAT_DB;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE + wso2carbon + wso2carbon + org.h2.Driver 50 60000 true diff --git a/features/heartbeat-management/pom.xml b/features/heartbeat-management/pom.xml index 39703223a5..42febcc76b 100644 --- a/features/heartbeat-management/pom.xml +++ b/features/heartbeat-management/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml index cfb3303f01..31f48b995e 100644 --- a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml +++ b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml @@ -23,7 +23,7 @@ org.wso2.carbon.devicemgt jwt-client-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/jwt-client/pom.xml b/features/jwt-client/pom.xml index 36fae9c794..50925e545a 100644 --- a/features/jwt-client/pom.xml +++ b/features/jwt-client/pom.xml @@ -23,7 +23,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/features/logger/io.entgra.notification.logger.feature/pom.xml b/features/logger/io.entgra.notification.logger.feature/pom.xml new file mode 100644 index 0000000000..be7f7146f2 --- /dev/null +++ b/features/logger/io.entgra.notification.logger.feature/pom.xml @@ -0,0 +1,116 @@ + + + + + + + + org.wso2.carbon.devicemgt + logger-feature + 5.0.21-SNAPSHOT + ../pom.xml + + + 4.0.0 + io.entgra.notification.logger.feature + pom + Entgra - Notification logger + http://entgra.io + + This feature bundles for the Entgra Notification logger + + + + + org.wso2.carbon + org.wso2.carbon.logging + + + org.testng + testng + + + org.wso2.carbon.devicemgt + io.entgra.device.mgt.extensions.logger + + + org.wso2.carbon.devicemgt + io.entgra.notification.logger + + + + + + + maven-resources-plugin + 2.6 + + + copy-resources + generate-resources + + copy-resources + + + src/main/resources + + + resources + + build.properties + p2.inf + + + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + p2-feature-generation + package + + p2-feature-gen + + + io.entgra.notification.logger + ../../../features/etc/feature.properties + + + org.wso2.carbon.p2.category.type:server + org.eclipse.equinox.p2.type.group:true + + + + + org.wso2.carbon.devicemgt:io.entgra.notification.logger:${carbon.device.mgt.version} + + + + + + + + + diff --git a/features/logger/io.entgra.notification.logger.feature/src/main/resources/build.properties b/features/logger/io.entgra.notification.logger.feature/src/main/resources/build.properties new file mode 100644 index 0000000000..e98fb2729f --- /dev/null +++ b/features/logger/io.entgra.notification.logger.feature/src/main/resources/build.properties @@ -0,0 +1,20 @@ +# +# Copyright (C) 2018 - 2023 Entgra (Pvt) Ltd, Inc - All Rights Reserved. +# +# Unauthorised copying/redistribution of this file, via any medium is strictly prohibited. +# +# Licensed under the Entgra Commercial License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://entgra.io/licenses/entgra-commercial/1.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. +# + +custom = true diff --git a/features/logger/io.entgra.notification.logger.feature/src/main/resources/p2.inf b/features/logger/io.entgra.notification.logger.feature/src/main/resources/p2.inf new file mode 100644 index 0000000000..7ab37b9d7d --- /dev/null +++ b/features/logger/io.entgra.notification.logger.feature/src/main/resources/p2.inf @@ -0,0 +1 @@ +instructions.configure = \ \ No newline at end of file diff --git a/features/logger/pom.xml b/features/logger/pom.xml new file mode 100644 index 0000000000..10fc1b3f0b --- /dev/null +++ b/features/logger/pom.xml @@ -0,0 +1,40 @@ + + + + + + + + org.wso2.carbon.devicemgt + carbon-devicemgt + 5.0.21-SNAPSHOT + ../../pom.xml + + + 4.0.0 + logger-feature + pom + Entgra - Logger Feature + http://entgra.io + + + io.entgra.notification.logger.feature + + + diff --git a/features/policy-mgt/org.wso2.carbon.policy.mgt.server.feature/pom.xml b/features/policy-mgt/org.wso2.carbon.policy.mgt.server.feature/pom.xml index 0c6770578d..eb28b067bf 100644 --- a/features/policy-mgt/org.wso2.carbon.policy.mgt.server.feature/pom.xml +++ b/features/policy-mgt/org.wso2.carbon.policy.mgt.server.feature/pom.xml @@ -23,7 +23,7 @@ org.wso2.carbon.devicemgt policy-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/policy-mgt/pom.xml b/features/policy-mgt/pom.xml index 0478dbb17b..9a9f371f78 100644 --- a/features/policy-mgt/pom.xml +++ b/features/policy-mgt/pom.xml @@ -23,7 +23,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/features/task-mgt/io.entgra.task.mgt.feature/pom.xml b/features/task-mgt/io.entgra.task.mgt.feature/pom.xml new file mode 100755 index 0000000000..4094f312fb --- /dev/null +++ b/features/task-mgt/io.entgra.task.mgt.feature/pom.xml @@ -0,0 +1,110 @@ + + + + + + org.wso2.carbon.devicemgt + carbon-devicemgt + 5.0.21-SNAPSHOT + ../../../pom.xml + + + 4.0.0 + io.entgra.task.mgt.feature + pom + Entgra IoT - Task Manager Feature + http://wso2.org + + + + org.wso2.carbon.devicemgt + io.entgra.task.mgt.core + + + org.wso2.carbon.devicemgt + io.entgra.task.mgt.common + + + + + + + maven-resources-plugin + 2.6 + + + copy-resources + generate-resources + + copy-resources + + + src/main/resources + + + resources + + build.properties + p2.inf + + + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + p2-feature-generation + package + + p2-feature-gen + + + io.entgra.task.mgt + ../../../features/etc/feature.properties + + + org.wso2.carbon.p2.category.type:server + org.eclipse.equinox.p2.type.group:true + + + + + org.wso2.carbon.devicemgt:io.entgra.task.mgt.core:${carbon.device.mgt.version} + + + org.wso2.carbon.devicemgt:io.entgra.task.mgt.common:${carbon.device.mgt.version} + + + org.wso2.carbon.devicemgt:io.entgra.task.mgt.watcher:${carbon.device.mgt.version} + + + + + + + + + + \ No newline at end of file diff --git a/features/task-mgt/io.entgra.task.mgt.feature/src/main/resources/build.properties b/features/task-mgt/io.entgra.task.mgt.feature/src/main/resources/build.properties new file mode 100755 index 0000000000..9c86577d76 --- /dev/null +++ b/features/task-mgt/io.entgra.task.mgt.feature/src/main/resources/build.properties @@ -0,0 +1 @@ +custom = true diff --git a/features/task-mgt/io.entgra.task.mgt.feature/src/main/resources/conf/task-mgt-config.xml b/features/task-mgt/io.entgra.task.mgt.feature/src/main/resources/conf/task-mgt-config.xml new file mode 100755 index 0000000000..13fe285258 --- /dev/null +++ b/features/task-mgt/io.entgra.task.mgt.feature/src/main/resources/conf/task-mgt-config.xml @@ -0,0 +1,29 @@ + + + + + + + jdbc/DM_DS + + + + false + + diff --git a/features/task-mgt/io.entgra.task.mgt.feature/src/main/resources/conf_templates/templates/repository/conf/task-mgt-config.xml.j2 b/features/task-mgt/io.entgra.task.mgt.feature/src/main/resources/conf_templates/templates/repository/conf/task-mgt-config.xml.j2 new file mode 100755 index 0000000000..a6897adf2e --- /dev/null +++ b/features/task-mgt/io.entgra.task.mgt.feature/src/main/resources/conf_templates/templates/repository/conf/task-mgt-config.xml.j2 @@ -0,0 +1,37 @@ + + + + + + + {% if task_mgt.datasource.name is defined %} + {{task_mgt.datasource.name}} + {% else %} + jdbc/DM_DS + {% endif %} + + + + {% if task_watcher.conf is defined %} + {{task_watcher.conf.enable}} + {% else %} + false + {% endif %} + + diff --git a/features/task-mgt/io.entgra.task.mgt.feature/src/main/resources/p2.inf b/features/task-mgt/io.entgra.task.mgt.feature/src/main/resources/p2.inf new file mode 100755 index 0000000000..58012d9c01 --- /dev/null +++ b/features/task-mgt/io.entgra.task.mgt.feature/src/main/resources/p2.inf @@ -0,0 +1,3 @@ +instructions.configure = \ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.task.mgt_${feature.version}/conf/task-mgt-config.xml,target:${installFolder}/../../../repository/conf/task-mgt-config.xml,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.task.mgt_${feature.version}/conf_templates/,target:${installFolder}/../../resources/conf/,overwrite:true);\ \ No newline at end of file diff --git a/features/task-mgt/pom.xml b/features/task-mgt/pom.xml new file mode 100755 index 0000000000..189a163b78 --- /dev/null +++ b/features/task-mgt/pom.xml @@ -0,0 +1,40 @@ + + + + + + carbon-devicemgt + org.wso2.carbon.devicemgt + 5.0.21-SNAPSHOT + ../../pom.xml + + + 4.0.0 + task-mgt-feature + pom + Entgra IoT - Task Management Feature + http://entgra.io + + + io.entgra.task.mgt.feature + + + + + \ No newline at end of file diff --git a/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/pom.xml b/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/pom.xml index f6907c375e..dba94063ed 100644 --- a/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/pom.xml +++ b/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt email-sender-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/email/templates/enrollment-guide.vm b/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/email/templates/enrollment-guide.vm new file mode 100644 index 0000000000..f4f16cc8d7 --- /dev/null +++ b/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/email/templates/enrollment-guide.vm @@ -0,0 +1,34 @@ +#* + Copyright (c) 2023, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + + WSO2 Inc. 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. +*# + + $mail-subject + + + + Enrollment Questions and Answers + + +
+ $enrollment-guide +
+ + + ]]> + +
diff --git a/features/transport-mgt/email-sender/pom.xml b/features/transport-mgt/email-sender/pom.xml index 2f0bb51811..0e3241ad88 100644 --- a/features/transport-mgt/email-sender/pom.xml +++ b/features/transport-mgt/email-sender/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt transport-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/pom.xml b/features/transport-mgt/pom.xml index aa42bb243c..07ecebe2ff 100644 --- a/features/transport-mgt/pom.xml +++ b/features/transport-mgt/pom.xml @@ -3,7 +3,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api.feature/pom.xml b/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api.feature/pom.xml index 7942210a3f..47cb040d27 100644 --- a/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api.feature/pom.xml +++ b/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt sms-handler-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/pom.xml b/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/pom.xml index 9620d1cea1..41b8d3b338 100644 --- a/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/pom.xml +++ b/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt sms-handler-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/sms-handler/pom.xml b/features/transport-mgt/sms-handler/pom.xml index 1420821a23..d4bb6a06a6 100644 --- a/features/transport-mgt/sms-handler/pom.xml +++ b/features/transport-mgt/sms-handler/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt transport-mgt-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/pom.xml b/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/pom.xml index b8c1345513..d7fec7d0ca 100644 --- a/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/pom.xml +++ b/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/pom.xml @@ -21,7 +21,7 @@ ui-request-interceptor-feature io.entgra.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT 4.0.0 diff --git a/features/ui-request-interceptor/pom.xml b/features/ui-request-interceptor/pom.xml index 82269506f9..40c07d7c8d 100644 --- a/features/ui-request-interceptor/pom.xml +++ b/features/ui-request-interceptor/pom.xml @@ -21,7 +21,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/pom.xml b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/pom.xml index 322a15b651..15dbbd671f 100644 --- a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/pom.xml +++ b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt webapp-authenticator-framework-feature - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../pom.xml diff --git a/features/webapp-authenticator-framework/pom.xml b/features/webapp-authenticator-framework/pom.xml index 01f400a3da..80a6f00d3c 100644 --- a/features/webapp-authenticator-framework/pom.xml +++ b/features/webapp-authenticator-framework/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index aa41e4956d..09590375ba 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt pom - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT WSO2 Carbon - Device Management - Parent http://wso2.org WSO2 Connected Device Manager Components @@ -46,6 +46,8 @@ components/transport-mgt components/analytics-mgt components/webapp-authenticator-framework + components/logger + components/task-mgt features/device-mgt features/apimgt-extensions features/application-mgt @@ -58,6 +60,9 @@ features/transport-mgt features/analytics-mgt features/webapp-authenticator-framework + features/logger + features/task-mgt + @@ -348,8 +353,41 @@ org.wso2.carbon.apimgt.keymgt.extension.api ${carbon.device.mgt.version} + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.keymgt.extension + ${carbon.device.mgt.version} + + + org.wso2.carbon.devicemgt + io.entgra.notification.logger + ${carbon.device.mgt.version} + + + + org.wso2.carbon.devicemgt + io.entgra.task.mgt.common + ${carbon.device.mgt.version} + + + org.wso2.carbon.devicemgt + io.entgra.task.mgt.core + ${carbon.device.mgt.version} + + + org.wso2.carbon.devicemgt + io.entgra.task.mgt.watcher + ${carbon.device.mgt.version} + + + org.wso2.carbon.devicemgt + io.entgra.task.mgt.feature + zip + ${carbon.device.mgt.version} + + org.wso2.carbon @@ -1420,6 +1458,31 @@ org.wso2.carbon.databridge.core ${carbon.analytics.common.version} + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.stream.core + ${carbon.analytics.common.version} + + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.receiver.core + ${carbon.analytics.common.version} + + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.publisher.core + ${carbon.analytics.common.version} + + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.core + ${carbon.analytics.common.version} + + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.output.adapter.rdbms + ${carbon.analytics.common.version} + @@ -2033,7 +2096,7 @@ 1.2.11.wso2v10 - 5.0.16-SNAPSHOT + 5.0.21-SNAPSHOT 4.7.35 @@ -2048,8 +2111,8 @@ [9.0.0, 10.0.0) - 5.1.37 - [5.1.3,6.0.0) + 5.2.34 + [5.2.34,6.0.0) 1.3.25 [1.3.0,2.0.0) 2.1.23 @@ -2280,4 +2343,4 @@ - + \ No newline at end of file