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 495ffbee35..0f23492eda 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml @@ -22,13 +22,13 @@ apimgt-extensions org.wso2.carbon.devicemgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.annotations - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT bundle WSO2 Carbon - API Management Annotations WSO2 Carbon - API Management Custom Annotation Module 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 a84f27c301..220e24581a 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,12 +21,12 @@ apimgt-extensions org.wso2.carbon.devicemgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml 4.0.0 - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT org.wso2.carbon.apimgt.application.extension.api war WSO2 Carbon - API Application Management API diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java index 8b888a010d..54d68e7baa 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java @@ -42,6 +42,7 @@ public class APIUtil { private static Log log = LogFactory.getLog(APIUtil.class); private static final String DEFAULT_CDMF_API_TAG = "device_management"; + private static final String DEFAULT_AGENT_API_TAG = "device_agent"; private static final String DEFAULT_CERT_API_TAG = "scep_management"; public static final String PERMISSION_PROPERTY_NAME = "name"; @@ -106,6 +107,7 @@ public class APIUtil { List allowedApisTags = getDeviceManagementProviderService().getAvailableDeviceTypes(); allowedApisTags.add(DEFAULT_CDMF_API_TAG); allowedApisTags.add(DEFAULT_CERT_API_TAG); + allowedApisTags.add(DEFAULT_AGENT_API_TAG); return allowedApisTags; } 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 5f115d7a1d..8cd5a42506 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,12 +22,12 @@ apimgt-extensions org.wso2.carbon.devicemgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml 4.0.0 - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT org.wso2.carbon.apimgt.application.extension bundle WSO2 Carbon - API Application Management 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 bc92961f64..7f3def1ccd 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 @@ -84,109 +84,118 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe String keyType, String username, boolean isAllowedAllDomains, String validityTime) throws APIManagerException { - StoreClient storeClient = APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService() - .getStoreClient(); + StoreClient storeClient = + APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService() + .getStoreClient(); String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext() .getTenantDomain(); + try { + ApplicationList applicationList = storeClient.getApplications() + .applicationsGet("", applicationName, 1, 0, CONTENT_TYPE, null); + Application application; + if (applicationList == null || applicationList.getList() == null || applicationList.getList().size() == 0) { + //create application; + application = new Application(); + application.setName(applicationName); + application.setSubscriber(username); + application.setDescription(""); + application.setThrottlingTier(ApiApplicationConstants.DEFAULT_TIER); + application.setGroupId(""); + application = storeClient.getIndividualApplication().applicationsPost(application, CONTENT_TYPE); + } else { + ApplicationInfo applicationInfo = applicationList.getList().get(0); + application = storeClient.getIndividualApplication() + .applicationsApplicationIdGet(applicationInfo.getApplicationId(), CONTENT_TYPE, null, null); + } + if (application == null) { + throw new APIManagerException( + "Api application creation failed for " + applicationName + " to the user " + username); + } - ApplicationList applicationList = storeClient.getApplications() - .applicationsGet("", applicationName, 1, 0, CONTENT_TYPE, null); - Application application; - if (applicationList == null || applicationList.getList() == null || applicationList.getList().size() == 0) { - //create application; - application = new Application(); - application.setName(applicationName); - application.setSubscriber(username); - application.setDescription(""); - application.setThrottlingTier(ApiApplicationConstants.DEFAULT_TIER); - application.setGroupId(""); - application = storeClient.getIndividualApplication().applicationsPost(application, CONTENT_TYPE); - } else { - ApplicationInfo applicationInfo = applicationList.getList().get(0); - application = storeClient.getIndividualApplication() - .applicationsApplicationIdGet(applicationInfo.getApplicationId(), CONTENT_TYPE, null, null); - } - if (application == null) { - throw new APIManagerException ( - "Api application creation failed for " + applicationName + " to the user " + username); - } - - SubscriptionList subscriptionList = storeClient.getSubscriptions().subscriptionsGet - (null, application.getApplicationId(), "", 0, 100, CONTENT_TYPE, null); - List needToSubscribe = new ArrayList<>(); - // subscribe to apis. - if (tags != null && tags.length > 0) { - for (String tag: tags) { - APIList apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0, tenantDomain, "tag:" + tag - , CONTENT_TYPE, null); - if (apiList.getList() == null || apiList.getList().size() == 0) { - apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0 - , MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, "tag:" + tag, CONTENT_TYPE, null); - } + SubscriptionList subscriptionList = storeClient.getSubscriptions().subscriptionsGet + (null, application.getApplicationId(), "", 0, 100, CONTENT_TYPE, null); + List needToSubscribe = new ArrayList<>(); + // subscribe to apis. + if (tags != null && tags.length > 0) { + for (String tag : tags) { + APIList apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0, tenantDomain, "tag:" + tag + , CONTENT_TYPE, null); + if (apiList.getList() == null || apiList.getList().size() == 0) { + apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0 + , MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, "tag:" + tag, CONTENT_TYPE, null); + } - if (apiList.getList() != null && apiList.getList().size() > 0) { - for (APIInfo apiInfo : apiList.getList()) { - String id = apiInfo.getProvider().replace("@", "-AT-") - + "-" + apiInfo.getName()+ "-" + apiInfo.getVersion(); - boolean subscriptionExist = false; - if (subscriptionList.getList() != null && subscriptionList.getList().size() > 0) { - for (Subscription subs : subscriptionList.getList()) { - if (subs.getApiIdentifier().equals(id)) { - subscriptionExist = true; - break; + if (apiList.getList() != null && apiList.getList().size() > 0) { + for (APIInfo apiInfo : apiList.getList()) { + String id = apiInfo.getProvider().replace("@", "-AT-") + + "-" + apiInfo.getName() + "-" + apiInfo.getVersion(); + boolean subscriptionExist = false; + if (subscriptionList.getList() != null && subscriptionList.getList().size() > 0) { + for (Subscription subs : subscriptionList.getList()) { + if (subs.getApiIdentifier().equals(id)) { + subscriptionExist = true; + break; + } } } - } - if (!subscriptionExist) { - Subscription subscription = new Subscription(); - //fix for APIMANAGER-5566 admin-AT-tenant1.com-Tenant1API1-1.0.0 - - subscription.setApiIdentifier(id); - subscription.setApplicationId(application.getApplicationId()); - subscription.tier(ApiApplicationConstants.DEFAULT_TIER); - if (!needToSubscribe.contains(subscription)){ - needToSubscribe.add(subscription); + if (!subscriptionExist) { + Subscription subscription = new Subscription(); + //fix for APIMANAGER-5566 admin-AT-tenant1.com-Tenant1API1-1.0.0 + + subscription.setApiIdentifier(id); + subscription.setApplicationId(application.getApplicationId()); + subscription.tier(ApiApplicationConstants.DEFAULT_TIER); + if (!needToSubscribe.contains(subscription)) { + needToSubscribe.add(subscription); + } } } } } } - } - if (!needToSubscribe.isEmpty()) { - storeClient.getSubscriptionMultitpleApi().subscriptionsMultiplePost(needToSubscribe, CONTENT_TYPE); - } - //end of subscription - - List applicationKeys = application.getKeys(); - if (applicationKeys != null) { - for (ApplicationKey applicationKey : applicationKeys) { - if (keyType.equals(applicationKey.getKeyType().toString())) { - ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); - apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); - apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); - return apiApplicationKey; + if (!needToSubscribe.isEmpty()) { + storeClient.getSubscriptionMultitpleApi().subscriptionsMultiplePost(needToSubscribe, CONTENT_TYPE); + } + //end of subscription + + List applicationKeys = application.getKeys(); + if (applicationKeys != null) { + for (ApplicationKey applicationKey : applicationKeys) { + if (keyType.equals(applicationKey.getKeyType().toString())) { + if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) { + ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); + apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); + apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); + return apiApplicationKey; + } + } } } - } - ApplicationKeyGenerateRequest applicationKeyGenerateRequest = new ApplicationKeyGenerateRequest(); - List allowedDomains = new ArrayList<>(); - if (isAllowedAllDomains) { - allowedDomains.add(ApiApplicationConstants.ALLOWED_DOMAINS); - } else { - allowedDomains.add(APIManagerUtil.getTenantDomain()); + ApplicationKeyGenerateRequest applicationKeyGenerateRequest = new ApplicationKeyGenerateRequest(); + List allowedDomains = new ArrayList<>(); + if (isAllowedAllDomains) { + allowedDomains.add(ApiApplicationConstants.ALLOWED_DOMAINS); + } else { + allowedDomains.add(APIManagerUtil.getTenantDomain()); + } + applicationKeyGenerateRequest.setAccessAllowDomains(allowedDomains); + applicationKeyGenerateRequest.setCallbackUrl(""); + applicationKeyGenerateRequest.setKeyType(ApplicationKeyGenerateRequest.KeyTypeEnum.PRODUCTION); + applicationKeyGenerateRequest.setValidityTime(validityTime); + + ApplicationKey applicationKey = storeClient.getIndividualApplication().applicationsGenerateKeysPost( + application.getApplicationId(), applicationKeyGenerateRequest, CONTENT_TYPE, null, null); + if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) { + ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); + apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); + apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); + return apiApplicationKey; + } + throw new APIManagerException("Failed to generate keys for tenant: " + tenantDomain); + } catch (FeignException e) { + throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e); } - applicationKeyGenerateRequest.setAccessAllowDomains(allowedDomains); - applicationKeyGenerateRequest.setCallbackUrl(""); - applicationKeyGenerateRequest.setKeyType(ApplicationKeyGenerateRequest.KeyTypeEnum.PRODUCTION); - applicationKeyGenerateRequest.setValidityTime(validityTime); - - ApplicationKey applicationKey = storeClient.getIndividualApplication().applicationsGenerateKeysPost( - application.getApplicationId(), applicationKeyGenerateRequest, CONTENT_TYPE, null, null); - ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); - apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); - apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); - return apiApplicationKey; } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml index 969a408d19..fbf325db15 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml @@ -21,13 +21,13 @@ apimgt-extensions org.wso2.carbon.devicemgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.handlers - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT bundle WSO2 Carbon - API Security Handler Component WSO2 Carbon - API Management Security Handler Module diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java index d3c8ad3a9f..e7d239a1ee 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java @@ -44,6 +44,8 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Contains util methods for synapse gateway authentication handler @@ -62,21 +64,47 @@ public class Utils { public static IOTServerConfiguration initConfig() { try { - String IOTServerAPIConfigurationPath = - CarbonUtils.getCarbonConfigDirPath() + File.separator + IOT_APIS_CONFIG_FILE; + String IOTServerAPIConfigurationPath = CarbonUtils.getCarbonConfigDirPath() + File.separator + + IOT_APIS_CONFIG_FILE; File file = new File(IOTServerAPIConfigurationPath); Document doc = Utils.convertToDocument(file); JAXBContext fileContext = JAXBContext.newInstance(IOTServerConfiguration.class); Unmarshaller unmarshaller = fileContext.createUnmarshaller(); - return (IOTServerConfiguration) unmarshaller.unmarshal(doc); + IOTServerConfiguration iotServerConfiguration = (IOTServerConfiguration) unmarshaller.unmarshal( + doc); + iotServerConfiguration.setHostname(replaceProperties(iotServerConfiguration.getHostname())); + iotServerConfiguration.setVerificationEndpoint( + replaceProperties(iotServerConfiguration.getVerificationEndpoint())); + iotServerConfiguration.setDynamicClientRegistrationEndpoint( + replaceProperties(iotServerConfiguration.getDynamicClientRegistrationEndpoint())); + iotServerConfiguration.setOauthTokenEndpoint( + replaceProperties(iotServerConfiguration.getOauthTokenEndpoint())); + return iotServerConfiguration; } catch (JAXBException | APIMCertificateMGTException e) { log.error("Error occurred while initializing Data Source config", e); return null; } } + /** + * This method gets the values from system variables and sets to xml. + */ + public static String replaceProperties(String text) { + String regex = "\\$\\{(.*?)\\}"; + Pattern pattern = Pattern.compile(regex); + Matcher matchPattern = pattern.matcher(text); + while (matchPattern.find()) { + String sysPropertyName = matchPattern.group(1); + String sysPropertyValue = System.getProperty(sysPropertyName); + if (sysPropertyValue != null && !sysPropertyName.isEmpty()) { + text = text.replaceAll("\\$\\{(" + sysPropertyName + ")\\}", sysPropertyValue); + } + } + return text; + } + /** * This class build the iot-api-config.xml file. * @param file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/resources/iot-api-config.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/resources/iot-api-config.xml index fc65693d28..ed61a4a115 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/resources/iot-api-config.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/resources/iot-api-config.xml @@ -19,22 +19,22 @@ - https://localhost:9443/ + https://${iot.core.host}:${iot.core.https.port}/ - https://localhost:9443/api/certificate-mgt/v1.0/admin/certificates/verify/ + https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/ admin admin - https://localhost:9443/dynamic-client-web/register + https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.11/register - https://localhost:9443/oauth2/token + https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token - /services/echo + /services \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml index e90752fba8..842f0e6bfe 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml @@ -13,13 +13,13 @@ apimgt-extensions org.wso2.carbon.devicemgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.integration.client - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT bundle WSO2 Carbon - API Management Integration Client WSO2 Carbon - API Management Integration Client diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java index ed5a587986..3474d836bd 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java @@ -21,24 +21,43 @@ package org.wso2.carbon.apimgt.integration.client.util; import feign.Client; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; +import javax.net.ssl.*; +import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; +import java.io.InputStream; +import java.security.*; +import java.security.cert.CertificateException; import java.util.regex.Matcher; import java.util.regex.Pattern; import feign.Logger; import feign.Request; import feign.Response; import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.ServerConfiguration; public class Utils { + private static final Log log = LogFactory.getLog(Utils.class); + + private static final String KEY_STORE_TYPE = "JKS"; + /** + * Default truststore type of the client + */ + private static final String TRUST_STORE_TYPE = "JKS"; + /** + * Default keymanager type of the client + */ + private static final String KEY_MANAGER_TYPE = "SunX509"; //Default Key Manager Type + /** + * Default trustmanager type of the client + */ + private static final String TRUST_MANAGER_TYPE = "SunX509"; //Default Trust Manager Type + + private static final String SSLV3 = "SSLv3"; + + //This method is only used if the mb features are within DAS. public static String replaceProperties(String text) { String regex = "\\$\\{(.*?)\\}"; @@ -55,15 +74,20 @@ public class Utils { } public static Client getSSLClient() { - return new Client.Default(getTrustedSSLSocketFactory(), new HostnameVerifier() { - @Override - public boolean verify(String s, SSLSession sslSession) { - return true; - } - }); + boolean isIgnoreHostnameVerification = Boolean.parseBoolean(System.getProperty("org.wso2.ignoreHostnameVerification")); + if(isIgnoreHostnameVerification) { + return new Client.Default(getSimpleTrustedSSLSocketFactory(), new HostnameVerifier() { + @Override + public boolean verify(String s, SSLSession sslSession) { + return true; + } + }); + }else { + return new Client.Default(getTrustedSSLSocketFactory(), null); + } } - private static SSLSocketFactory getTrustedSSLSocketFactory() { + private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() { try { TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @@ -86,4 +110,60 @@ public class Utils { } } -} + + private static SSLSocketFactory getTrustedSSLSocketFactory() { + try { + String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password"); + String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location"); + String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty( + "Security.TrustStore.Password"); + String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty( + "Security.TrustStore.Location"); + KeyStore keyStore = loadKeyStore(keyStoreLocation,keyStorePassword,KEY_STORE_TYPE); + KeyStore trustStore = loadTrustStore(trustStoreLocation,trustStorePassword); + + return initSSLConnection(keyStore,keyStorePassword,trustStore); + } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException + |CertificateException | IOException | UnrecoverableKeyException e) { + log.error("Error while creating the SSL socket factory due to "+e.getMessage(),e); + return null; + } + + } + + private static SSLSocketFactory initSSLConnection(KeyStore keyStore,String keyStorePassword,KeyStore trustStore) throws NoSuchAlgorithmException, UnrecoverableKeyException, + KeyStoreException, KeyManagementException { + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE); + keyManagerFactory.init(keyStore, keyStorePassword.toCharArray()); + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE); + trustManagerFactory.init(trustStore); + + // Create and initialize SSLContext for HTTPS communication + SSLContext sslContext = SSLContext.getInstance(SSLV3); + sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); + SSLContext.setDefault(sslContext); + return sslContext.getSocketFactory(); + } + + + private static KeyStore loadKeyStore(String keyStorePath, String ksPassword,String type) + throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { + InputStream fileInputStream = null; + try { + char[] keypassChar = ksPassword.toCharArray(); + KeyStore keyStore = KeyStore.getInstance(type); + fileInputStream = new FileInputStream(keyStorePath); + keyStore.load(fileInputStream, keypassChar); + return keyStore; + } finally { + if (fileInputStream != null) { + fileInputStream.close(); + } + } + } + + private static KeyStore loadTrustStore(String trustStorePath, String tsPassword) + throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { + return loadKeyStore(trustStorePath,tsPassword,TRUST_STORE_TYPE); + } +} \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml index 6b85588bb4..31adc6fde5 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml @@ -13,13 +13,13 @@ apimgt-extensions org.wso2.carbon.devicemgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.integration.generated.client - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT bundle WSO2 Carbon - API Management Integration Generated Client WSO2 Carbon - API Management Integration Client 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 7b1f639ddc..cee4587b91 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,13 +22,13 @@ apimgt-extensions org.wso2.carbon.devicemgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.webapp.publisher - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT bundle WSO2 Carbon - API Management Webapp Publisher WSO2 Carbon - API Management Webapp Publisher diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index b57f64e0db..119693a8c8 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -22,13 +22,13 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../../pom.xml 4.0.0 apimgt-extensions - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT pom WSO2 Carbon - API Management Extensions Component http://wso2.org diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/pom.xml index dbf36b10b0..c9e28a7c47 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/pom.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/pom.xml @@ -22,13 +22,13 @@ application-mgt org.wso2.carbon.devicemgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.application.mgt.api - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT war WSO2 Carbon - Application Management API WSO2 Carbon - Application Management API diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/pom.xml index eae9703673..4493c59c69 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/pom.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/pom.xml @@ -21,13 +21,13 @@ org.wso2.carbon.devicemgt application-mgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.application.mgt.common - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT bundle WSO2 Carbon - Application Management Common WSO2 Carbon - Application Management Common diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml index 1d74027d97..a605c94d61 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml @@ -21,13 +21,13 @@ org.wso2.carbon.devicemgt application-mgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.application.mgt.core - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT bundle WSO2 Carbon - Application Management Core WSO2 Carbon - Application Management Core diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.ui/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.ui/pom.xml index f3401922bf..07b50760d8 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.ui/pom.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.ui/pom.xml @@ -22,14 +22,14 @@ application-mgt org.wso2.carbon.devicemgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.application.mgt.ui pom - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT WSO2 Carbon - Application Management Base UI WSO2 Carbon - Application Management Base UI http://wso2.org diff --git a/components/application-mgt/pom.xml b/components/application-mgt/pom.xml index 0feac88010..e8446736c5 100644 --- a/components/application-mgt/pom.xml +++ b/components/application-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 2.0.63-SNAPSHOT + 3.0.46-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 ab05087131..2bc513dbe8 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 - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml @@ -38,8 +38,8 @@ maven-compiler-plugin - 1.7 - 1.7 + 1.8 + 1.8 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 964411579c..70eead145a 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 - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml @@ -38,8 +38,8 @@ maven-compiler-plugin - 1.7 - 1.7 + 1.8 + 1.8 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 f2c509f9af..dec884436c 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 @@ -21,13 +21,13 @@ org.wso2.carbon.devicemgt certificate-mgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.certificate.mgt.core - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT bundle WSO2 Carbon - Certificate Management Core WSO2 Carbon - Certificate Management Core diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml index 0c93d81654..f360b55bbe 100644 --- a/components/certificate-mgt/pom.xml +++ b/components/certificate-mgt/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt certificate-mgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT pom WSO2 Carbon - Certificate Management Component http://wso2.org 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 ce7d13797c..f649963aa8 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 - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml @@ -112,7 +112,7 @@ org.w3c.dom, org.wso2.carbon.context, org.wso2.carbon.device.mgt.common.*, - org.wso2.carbon.device.mgt.extensions.*, + org.wso2.carbon.device.mgt.extensions.device.type.template.*, org.wso2.carbon.registry.api, org.wso2.carbon.registry.core, org.wso2.carbon.registry.core.*, diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployer.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployer.java index 5dfa895f39..eb02504d97 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployer.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployer.java @@ -29,12 +29,12 @@ import org.osgi.framework.ServiceRegistration; import org.w3c.dom.Document; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.DeviceTypeConfiguration; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.exception.DeviceTypeConfigurationException; import org.wso2.carbon.device.mgt.extensions.device.type.deployer.internal.DeviceTypeManagementDataHolder; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.DeviceTypeConfigIdentifier; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.DeviceTypeManagerService; import org.wso2.carbon.device.mgt.extensions.device.type.deployer.util.DeviceTypeConfigUtil; +import org.wso2.carbon.device.mgt.extensions.device.type.template.DeviceTypeConfigIdentifier; +import org.wso2.carbon.device.mgt.extensions.device.type.template.DeviceTypeManagerService; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypeUIDeployer.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypeUIDeployer.java deleted file mode 100644 index 5ee352751e..0000000000 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypeUIDeployer.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2016, 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. - * - */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer; - -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.deployment.AbstractDeployer; -import org.apache.axis2.deployment.DeploymentException; -import org.apache.axis2.deployment.repository.util.DeploymentFileData; -import org.apache.commons.io.FileUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.utils.CarbonUtils; - -import java.io.File; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * This is the device deployer that will read and deploy the device type ui files from - * "deployment/server/devicetypes-ui" - * directory. - */ -public class DeviceTypeUIDeployer extends AbstractDeployer { - - private static Log log = LogFactory.getLog(DeviceTypeUIDeployer.class); - protected Map deviceTypeDeployedUIMap = new ConcurrentHashMap(); - private static final String DEVICEMGT_JAGGERY_APP_PATH = CarbonUtils.getCarbonRepository() + File.separator - + "jaggeryapps" + File.separator + "devicemgt" + File.separator + "app" + File.separator + "units" - + File.separator; - - private static final String UNIT_PREFIX = "cdmf.unit.device.type"; - - @Override - public void init(ConfigurationContext configurationContext) { - } - - @Override - public void setDirectory(String s) { - - } - - @Override - public void setExtension(String s) { - - } - - @Override - public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException { - if (!deploymentFileData.getFile().isDirectory()) { - return; - } - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); - if (tenantDomain != null && !tenantDomain.isEmpty()) { - File jaggeryAppPath = new File( - DEVICEMGT_JAGGERY_APP_PATH + tenantDomain + "." + deploymentFileData.getName()); - try { - if (!jaggeryAppPath.exists()) { - FileUtils.forceMkdir(jaggeryAppPath); - FileUtils.copyDirectory(deploymentFileData.getFile(), jaggeryAppPath); - File[] listOfFiles = jaggeryAppPath.listFiles(); - - for (int i = 0; i < listOfFiles.length; i++) { - if (listOfFiles[i].isFile()) { - String content = FileUtils.readFileToString(listOfFiles[i]); - FileUtils.writeStringToFile(listOfFiles[i], content.replaceAll(UNIT_PREFIX - , tenantDomain + "." + UNIT_PREFIX)); - } - } - } else { - log.debug("units already exists " + deploymentFileData.getName()); - } - this.deviceTypeDeployedUIMap.put(deploymentFileData.getAbsolutePath(), - jaggeryAppPath.getAbsolutePath()); - } catch (IOException e) { - if (jaggeryAppPath.exists()) { - try { - FileUtils.deleteDirectory(jaggeryAppPath); - } catch (IOException e1) { - log.error("Failed to delete directory " + jaggeryAppPath.getAbsolutePath()); - } - } - log.error("Cannot deploy deviceType ui : " + deploymentFileData.getName(), e); - throw new DeploymentException( - "Device type ui file " + deploymentFileData.getName() + " is not deployed ", e); - } - - } else { - log.error("Cannot deploy deviceType ui: " + deploymentFileData.getName()); - } - - - } - - @Override - public void undeploy(String filePath) throws DeploymentException { - try { - String jaggeryUnitPath = this.deviceTypeDeployedUIMap.remove(filePath); - FileUtils.deleteDirectory(new File(jaggeryUnitPath)); - log.info("Device Type units un deployed successfully."); - } catch (IOException e) { - throw new DeploymentException("Failed to remove the units: " + filePath); - } - } - -} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/ObjectFactory.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/ObjectFactory.java deleted file mode 100644 index be089a9ccc..0000000000 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/ObjectFactory.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2016, 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. - * - */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; - -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlElementDecl; -import javax.xml.bind.annotation.XmlRegistry; -import javax.xml.namespace.QName; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the org.wso2.carbon package. - *

An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -public class ObjectFactory { - - private final static QName _DeviceTypeConfiguration_QNAME = new QName("", "DeviceTypeConfiguration"); - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.wso2.carbon - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link DeviceTypeConfiguration } - * - */ - public DeviceTypeConfiguration createDeviceTypeConfiguration() { - return new DeviceTypeConfiguration(); - } - - /** - * Create an instance of {@link Operation } - * - */ - public Operation createOperation() { - return new Operation(); - } - - /** - * Create an instance of {@link Attributes } - * - */ - public Attributes createAttributes() { - return new Attributes(); - } - - /** - * Create an instance of {@link ProvisioningConfig } - * - */ - public ProvisioningConfig createProvisioningConfig() { - return new ProvisioningConfig(); - } - - /** - * Create an instance of {@link TableConfig } - * - */ - public TableConfig createTableConfig() { - return new TableConfig(); - } - - /** - * Create an instance of {@link Table } - * - */ - public Table createTable() { - return new Table(); - } - - /** - * Create an instance of {@link Property } - * - */ - public Property createProperty() { - return new Property(); - } - - /** - * Create an instance of {@link JndiConfig } - * - */ - public JndiConfig createJndiConfig() { - return new JndiConfig(); - } - - /** - * Create an instance of {@link FormParameters } - * - */ - public FormParameters createFormParameters() { - return new FormParameters(); - } - - /** - * Create an instance of {@link Features } - * - */ - public Features createFeatures() { - return new Features(); - } - - /** - * Create an instance of {@link Feature } - * - */ - public Feature createFeature() { - return new Feature(); - } - - /** - * Create an instance of {@link PushNotificationProvider } - * - */ - public PushNotificationProvider createPushNotificationProvider() { - return new PushNotificationProvider(); - } - - /** - * Create an instance of {@link DataSource } - * - */ - public DataSource createDataSource() { - return new DataSource(); - } - - /** - * Create an instance of {@link ConfigProperties } - * - */ - public ConfigProperties createConfigProperties() { - return new ConfigProperties(); - } - - /** - * Create an instance of {@link License } - * - */ - public License createLicense() { - return new License(); - } - - /** - * Create an instance of {@link DeviceDetails } - * - */ - public DeviceDetails createDeviceDetails() { - return new DeviceDetails(); - } - - /** - * Create an instance of {@link QueryParameters } - * - */ - public QueryParameters createQueryParameters() { - return new QueryParameters(); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link DeviceTypeConfiguration }{@code >}} - * - */ - @XmlElementDecl(namespace = "", name = "DeviceTypeConfiguration") - public JAXBElement createDeviceTypeConfiguration(DeviceTypeConfiguration value) { - return new JAXBElement(_DeviceTypeConfiguration_QNAME, DeviceTypeConfiguration.class, null, value); - } - -} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/internal/DeviceTypeManagementServiceComponent.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/internal/DeviceTypeManagementServiceComponent.java index 9c7d771c11..88761df2e1 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/internal/DeviceTypeManagementServiceComponent.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/internal/DeviceTypeManagementServiceComponent.java @@ -28,7 +28,7 @@ import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.utils.ConfigurationContextService; /** - * @scr.component name="org.wso2.carbon.device.mgt.iot.internal.DeviceTypeManagementServiceComponent" + * @scr.component name="org.wso2.carbon.device.mgt.iot.internal.DeviceTypeExtensionServiceComponent" * immediate="true" * @scr.reference name="config.context.service" * interface="org.wso2.carbon.utils.ConfigurationContextService" diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/util/DeviceTypeConfigUtil.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/util/DeviceTypeConfigUtil.java index 495a72b48d..4611deb8f3 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/util/DeviceTypeConfigUtil.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/util/DeviceTypeConfigUtil.java @@ -19,7 +19,7 @@ package org.wso2.carbon.device.mgt.extensions.device.type.deployer.util; import org.w3c.dom.Document; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.exception.DeviceTypeConfigurationException; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/util/DeviceTypePluginConstants.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/util/DeviceTypePluginConstants.java index 290fe93b7b..8b8ad98cf2 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/util/DeviceTypePluginConstants.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/util/DeviceTypePluginConstants.java @@ -22,9 +22,6 @@ package org.wso2.carbon.device.mgt.extensions.device.type.deployer.util; * This holds the constants used for this bundle. */ public class DeviceTypePluginConstants { - public static final String MEDIA_TYPE_XML = "application/xml"; - public static final String CHARSET_UTF8 = "UTF8"; - public static final String LANGUAGE_CODE_ENGLISH_US = "en_US"; public static final String CDMF_UI_TYPE = "devicetype/ui"; public static final String CDMF_UI_TYPE_DIR = "devicetypes-ui"; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/sample.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/sample.xml deleted file mode 100644 index 414bcaa8dd..0000000000 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/sample.xml +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - - - - abc - this is a feature - - - deviceId - - - test - - - - - - - - - - temperature sensor fitted - org.wso2.temperature.stream - this is a sensor - - celcius - atmeggga11234 - - - - temperature sensor fitted - org.wso2.temperature.stream - this is a sensor - - celcius - - - - - - - - - false - - - - true - - - - true - - - sample.mqtt.adapter - tcp://localhost:1883 - admin - admin - 0 - - true - - - - - - - en_US - 1.0.0 - This is license text - - - - true - 600000 - - - DEVICE_INFO - 1 - - - APPLICATION_LIST - 5 - - - DEVICE_LOCATION - 1 - - - - - - - jdbc/SampleDM_DB - - - - SAMPLE_DEVICE_ID - - column1 - column2 - -
-
-
- -
\ No newline at end of file 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 new file mode 100644 index 0000000000..05c100dbd4 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml @@ -0,0 +1,100 @@ + + + + + + + device-mgt-extensions + org.wso2.carbon.devicemgt + 3.0.46-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.device.mgt.extensions.pull.notification + bundle + WSO2 Carbon - Pull Notification Provider Implementation + WSO2 Carbon - Pull Notification Provider Implementation + http://wso2.org + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + + + org.eclipse.osgi + org.eclipse.osgi + + + org.eclipse.osgi + org.eclipse.osgi.services + + + org.eclipse.osgi + org.eclipse.osgi.services + + + org.wso2.carbon.devicemgt + org.wso2.carbon.policy.mgt.core + + + + + + + org.apache.felix + maven-scr-plugin + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.device.mgt.version} + Pull Notification Provider Bundle + + !org.wso2.carbon.device.mgt.extensions.pull.notification.internal, + org.wso2.carbon.device.mgt.extensions.pull.notification.* + + + org.osgi.framework, + org.osgi.service.component, + org.apache.commons.logging, + org.wso2.carbon.device.mgt.common.*, + org.wso2.carbon.device.mgt.core.service + org.wso2.carbon.policy.mgt.core.*, + org.wso2.carbon.policy.mgt.core, + com.google.gson, + org.wso2.carbon.device.mgt.core.service.* + + + + + + + + diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/src/main/java/org/wso2/carbon/device/mgt/extensions/pull/notification/PullNotificationSubscriberImpl.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/src/main/java/org/wso2/carbon/device/mgt/extensions/pull/notification/PullNotificationSubscriberImpl.java new file mode 100644 index 0000000000..bcf8dece8a --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/src/main/java/org/wso2/carbon/device/mgt/extensions/pull/notification/PullNotificationSubscriberImpl.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.extensions.pull.notification; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationExecutionFailedException; +import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber; +import org.wso2.carbon.device.mgt.extensions.pull.notification.internal.PullNotificationDataHolder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class PullNotificationSubscriberImpl implements PullNotificationSubscriber { + + public final class OperationCodes { + private OperationCodes() { + throw new AssertionError(); + } + public static final String POLICY_MONITOR = "POLICY_MONITOR"; + } + + + private static final Log log = LogFactory.getLog(PullNotificationSubscriberImpl.class); + + public void init(Map properties) { + + } + + @Override + public void execute(DeviceIdentifier deviceIdentifier, Operation operation) throws PullNotificationExecutionFailedException { + try { + if (!Operation.Status.ERROR.equals(operation.getStatus()) && operation.getCode() != null && + OperationCodes.POLICY_MONITOR.equals(operation.getCode())) { + if (log.isDebugEnabled()) { + log.info("Received compliance status from POLICY_MONITOR operation ID: " + operation.getId()); + } + List features = getComplianceFeatures(operation.getPayLoad()); + PullNotificationDataHolder.getInstance().getPolicyManagerService() + .checkCompliance(deviceIdentifier, features); + + } else { + PullNotificationDataHolder.getInstance().getDeviceManagementProviderService().updateOperation( + deviceIdentifier, operation); + } + } catch (OperationManagementException e) { + throw new PullNotificationExecutionFailedException(e); + } catch (PolicyComplianceException e) { + throw new PullNotificationExecutionFailedException("Invalid payload format compliant feature", e); + } + } + + public void clean() { + + } + + private static List getComplianceFeatures(Object compliancePayload) throws + PolicyComplianceException { + String compliancePayloadString = new Gson().toJson(compliancePayload); + if (compliancePayload == null) { + return null; + } + // Parsing json string to get compliance features. + JsonElement jsonElement = new JsonParser().parse(compliancePayloadString); + JsonArray jsonArray = jsonElement.getAsJsonArray(); + Gson gson = new Gson(); + ComplianceFeature complianceFeature; + List complianceFeatures = new ArrayList(jsonArray.size()); + + for (JsonElement element : jsonArray) { + complianceFeature = gson.fromJson(element, ComplianceFeature.class); + complianceFeatures.add(complianceFeature); + } + return complianceFeatures; + } +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/src/main/java/org/wso2/carbon/device/mgt/extensions/pull/notification/internal/PullNotificationDataHolder.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/src/main/java/org/wso2/carbon/device/mgt/extensions/pull/notification/internal/PullNotificationDataHolder.java new file mode 100644 index 0000000000..a9f7888c43 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/src/main/java/org/wso2/carbon/device/mgt/extensions/pull/notification/internal/PullNotificationDataHolder.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.extensions.pull.notification.internal; + +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.policy.mgt.core.PolicyManagerService; + +public class PullNotificationDataHolder { + + private DeviceManagementProviderService deviceManagementProviderService; + private PolicyManagerService policyManagerService; + + private static PullNotificationDataHolder thisInstance = new PullNotificationDataHolder(); + + public static PullNotificationDataHolder getInstance() { + return thisInstance; + } + + public DeviceManagementProviderService getDeviceManagementProviderService() { + return deviceManagementProviderService; + } + + public void setDeviceManagementProviderService(DeviceManagementProviderService deviceManagementProviderService) { + this.deviceManagementProviderService = deviceManagementProviderService; + } + + public PolicyManagerService getPolicyManagerService() { + return policyManagerService; + } + + public void setPolicyManagerService(PolicyManagerService policyManagerService) { + this.policyManagerService = policyManagerService; + } +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/src/main/java/org/wso2/carbon/device/mgt/extensions/pull/notification/internal/PullNotificationServiceComponent.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/src/main/java/org/wso2/carbon/device/mgt/extensions/pull/notification/internal/PullNotificationServiceComponent.java new file mode 100644 index 0000000000..351e514706 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/src/main/java/org/wso2/carbon/device/mgt/extensions/pull/notification/internal/PullNotificationServiceComponent.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.extensions.pull.notification.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.policy.mgt.core.PolicyManagerService; + +/** + * @scr.component name="org.wso2.carbon.device.mgt.extensions.pull.notification.internal.PullNotificationServiceComponent" immediate="true" + * @scr.reference name="carbon.device.mgt.provider" + * interface="org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService" + * cardinality="1..1" + * policy="dynamic" + * bind="setDeviceManagementProviderService" + * unbind="unsetDeviceManagementProviderService" + * @scr.reference name="org.wso2.carbon.policy.mgt.core" + * interface="org.wso2.carbon.policy.mgt.core.PolicyManagerService" + * cardinality="1..1" + * policy="dynamic" + * bind="setPolicyManagerService" + * unbind="unsetPolicyManagerService" + */ +public class PullNotificationServiceComponent { + + private static final Log log = LogFactory.getLog(PullNotificationServiceComponent.class); + + @SuppressWarnings("unused") + protected void activate(ComponentContext componentContext) { + try { + //Do nothing + if (log.isDebugEnabled()) { + log.debug("pull notification provider implementation bundle has been successfully " + + "initialized"); + } + } catch (Throwable e) { + log.error("Error occurred while initializing pull notification provider " + + "implementation bundle", e); + } + } + + protected void deactivate(ComponentContext componentContext) { + //Do nothing + } + + protected void setDeviceManagementProviderService(DeviceManagementProviderService deviceManagementProviderService) { + PullNotificationDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService); + } + + protected void unsetDeviceManagementProviderService(DeviceManagementProviderService deviceManagementProviderService) { + PullNotificationDataHolder.getInstance().setDeviceManagementProviderService(null); + } + + protected void setPolicyManagerService(PolicyManagerService policyManagerService) { + PullNotificationDataHolder.getInstance().setPolicyManagerService(policyManagerService); + } + + protected void unsetPolicyManagerService(PolicyManagerService policyManagerService) { + PullNotificationDataHolder.getInstance().setPolicyManagerService(null); + } + +} 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 7c8b6fc6f0..ecfd3e1276 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 - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java index da488c5435..7085f1244b 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java @@ -57,7 +57,7 @@ public class FCMNotificationStrategy implements NotificationStrategy { public void execute(NotificationContext ctx) throws PushNotificationExecutionFailedException { try { Device device = - FCMDataHolder.getInstance().getDeviceManagementProviderService().getDevice(ctx.getDeviceId()); + FCMDataHolder.getInstance().getDeviceManagementProviderService().getDeviceWithTypeProperties(ctx.getDeviceId()); this.sendWakeUpCall(ctx.getOperation().getCode(), device); } catch (DeviceManagementException e) { throw new PushNotificationExecutionFailedException("Error occurred while retrieving device information", e); diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml similarity index 57% rename from components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/pom.xml rename to components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml index a75583c06c..7cc0b1213d 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml @@ -1,114 +1,78 @@ + - dynamic-client-registration + device-mgt-extensions org.wso2.carbon.devicemgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml 4.0.0 - org.wso2.carbon.dynamic.client.web.app.registration - 2.0.63-SNAPSHOT + org.wso2.carbon.device.mgt.extensions.push.notification.provider.http bundle - WSO2 Carbon - Dynamic client web app registration - WSO2 Carbon - Dynamic Client Web-app Registration Service + WSO2 Carbon - HTTP Based Push Notification Provider Implementation + WSO2 Carbon - HTTP Based Push Notification Provider Implementation http://wso2.org - - - - org.apache.felix - maven-scr-plugin - - - org.apache.felix - maven-bundle-plugin - 1.4.0 - true - - - ${project.artifactId} - ${project.artifactId} - ${carbon.device.mgt.version} - Dynamic Client Web App Registration Bundle - org.wso2.carbon.dynamic.client.web.app.registration.internal - - !org.wso2.carbon.dynamic.client.web.app.registration.internal, - org.wso2.carbon.dynamic.client.web.app.registration.* - - - javax.xml.bind.*, - com.google.*, - javax.net.ssl, - javax.servlet, - org.apache.axis2.context, - org.apache.catalina, - org.apache.catalina.core, - org.apache.commons.*, - org.apache.http, - org.apache.http.*, - org.osgi.framework, - org.osgi.service.component, - org.wso2.carbon.context, - org.wso2.carbon.core, - org.wso2.carbon.core.security, - org.wso2.carbon.dynamic.client.*, - org.wso2.carbon.registry.*, - org.wso2.carbon.user.*, - org.wso2.carbon.utils - - - - - - - org.eclipse.osgi - org.eclipse.osgi + org.wso2.carbon.governance + org.wso2.carbon.governance.api - org.eclipse.osgi - org.eclipse.osgi.services + org.wso2.carbon + org.wso2.carbon.registry.api + + + org.wso2.carbon + org.wso2.carbon.registry.core + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core - org.testng - testng + org.apache.ws.commons.axiom.wso2 + axiom org.wso2.carbon org.wso2.carbon.utils - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.mgt + org.wso2.orbit.org.scannotation + scannotation - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth + org.eclipse.osgi + org.eclipse.osgi - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.core + org.eclipse.osgi + org.eclipse.osgi.services org.wso2.tomcat @@ -119,28 +83,65 @@ tomcat-servlet-api - org.wso2.carbon - org.wso2.carbon.logging - - - org.wso2.carbon - org.wso2.carbon.user.core - - - org.wso2.carbon - org.wso2.carbon.registry.core + javax.ws.rs + jsr311-api - org.wso2.carbon.devicemgt - org.wso2.carbon.dynamic.client.registration + org.apache.axis2.wso2 + axis2 - org.apache.httpcomponents - httpclient + commons-lang.wso2 + commons-lang com.google.code.gson gson + + org.json.wso2 + json + + + + + + org.apache.felix + maven-scr-plugin + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.device.mgt.version} + MQTT Based Push Notification Provider Bundle + + !org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.internal, + org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.* + + + org.apache.commons.logging, + org.osgi.service.component, + org.wso2.carbon.context, + org.wso2.carbon.device.mgt.common.operation.mgt, + org.wso2.carbon.device.mgt.common.push.notification, + org.wso2.carbon.device.mgt.common, + org.wso2.carbon.device.mgt.core.service, + org.osgi.framework, + org.wso2.carbon.device.mgt.core.operation.mgt, + org.wso2.carbon.core, + com.google.gson, + org.apache.commons.httpclient.* + + + + + + + diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/dao/DeviceTypePluginDAOManager.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/http/HTTPBasedPushNotificationProvider.java similarity index 50% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/dao/DeviceTypePluginDAOManager.java rename to components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/http/HTTPBasedPushNotificationProvider.java index 10a9b018b3..5f083400b1 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/dao/DeviceTypePluginDAOManager.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/http/HTTPBasedPushNotificationProvider.java @@ -16,24 +16,22 @@ * under the License. * */ +package org.wso2.carbon.device.mgt.extensions.push.notification.provider.http; -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.dao; +import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationProvider; -public class DeviceTypePluginDAOManager { +public class HTTPBasedPushNotificationProvider implements PushNotificationProvider { - private DeviceTypePluginDAO deviceTypePluginDAO; - private DeviceTypeDAOHandler deviceTypeDAOHandler; - - public DeviceTypePluginDAOManager(String datasourceName, DeviceDAODefinition deviceDAODefinition) { - deviceTypeDAOHandler = new DeviceTypeDAOHandler(datasourceName); - deviceTypePluginDAO = new DeviceTypePluginDAO(deviceDAODefinition, deviceTypeDAOHandler); + @Override + public String getType() { + return "HTTP"; } - public DeviceTypePluginDAO getDeviceDAO() { - return deviceTypePluginDAO; + @Override + public NotificationStrategy getNotificationStrategy(PushNotificationConfig config) { + return new HTTPNotificationStrategy(config); } - public DeviceTypeDAOHandler getDeviceTypeDAOHandler() { - return deviceTypeDAOHandler; - } -} \ No newline at end of file +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/http/HTTPMessageExecutor.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/http/HTTPMessageExecutor.java new file mode 100644 index 0000000000..d833856883 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/http/HTTPMessageExecutor.java @@ -0,0 +1,94 @@ +package org.wso2.carbon.device.mgt.extensions.push.notification.provider.http; + +import com.google.gson.Gson; +import org.apache.commons.httpclient.HostConfiguration; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.methods.EntityEnclosingMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.StringRequestEntity; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.InvalidConfigurationException; +import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext; + +import java.net.UnknownHostException; + +public class HTTPMessageExecutor implements Runnable { + + private String url; + private String authorizationHeader; + private String payload; + private HostConfiguration hostConfiguration; + private HttpClient httpClient; + private static final String APPLIATION_JSON = "application/json"; + private static final String AUTHORIZATION_HEADER = "Authorization"; + private static final Log log = LogFactory.getLog(HTTPMessageExecutor.class); + + public HTTPMessageExecutor(NotificationContext notificationContext, String authorizationHeader, String url + , HostConfiguration hostConfiguration, HttpClient httpClient) { + this.url = url; + this.authorizationHeader = authorizationHeader; + Gson gson = new Gson(); + this.payload = gson.toJson(notificationContext); + this.hostConfiguration = hostConfiguration; + this.httpClient = httpClient; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getAuthorizationHeader() { + return authorizationHeader; + } + + public void setAuthorizationHeader(String authorizationHeader) { + this.authorizationHeader = authorizationHeader; + } + + public String getPayload() { + return payload; + } + + public void setPayload(String payload) { + this.payload = payload; + } + + public HttpClient getHttpClient() { + return httpClient; + } + + public void setHttpClient(HttpClient httpClient) { + this.httpClient = httpClient; + } + + @Override + public void run() { + EntityEnclosingMethod method = null; + + try { + method = new PostMethod(this.getUrl()); + method.setRequestEntity(new StringRequestEntity(this.getPayload(), APPLIATION_JSON, "UTF-8")); + if (authorizationHeader != null && authorizationHeader.isEmpty()) { + method.setRequestHeader(AUTHORIZATION_HEADER, authorizationHeader); + } + + this.getHttpClient().executeMethod(hostConfiguration, method); + + } catch (UnknownHostException e) { + log.error("Push Notification message dropped " + url, e); + throw new InvalidConfigurationException("invalid host: url", e); + } catch (Throwable e) { + log.error("Push Notification message dropped ", e); + throw new InvalidConfigurationException("Push Notification message dropped, " + e.getMessage(), e); + } finally { + if (method != null) { + method.releaseConnection(); + } + } + } +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/http/HTTPNotificationStrategy.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/http/HTTPNotificationStrategy.java new file mode 100644 index 0000000000..2e4e237c69 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/http/HTTPNotificationStrategy.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2016, 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. + * + */ +package org.wso2.carbon.device.mgt.extensions.push.notification.provider.http; + +import org.apache.commons.httpclient.HostConfiguration; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.InvalidConfigurationException; +import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext; +import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationExecutionFailedException; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; + +public class HTTPNotificationStrategy implements NotificationStrategy { + + private static final Log log = LogFactory.getLog(HTTPNotificationStrategy.class); + private final PushNotificationConfig config; + private static final String URL_PROPERTY = "url"; + private static final String AUTHORIZATION_HEADER_PROPERTY = "authorization"; + private String endpoint; + private static ExecutorService executorService; + private HttpClient httpClient = null; + private HostConfiguration hostConfiguration; + private String authorizationHeaderValue; + private String uri; + + public HTTPNotificationStrategy(PushNotificationConfig config) { + this.config = config; + if (this.config == null) { + throw new InvalidConfigurationException("Properties Cannot be found"); + } + endpoint = config.getProperties().get(URL_PROPERTY); + if (endpoint == null || endpoint.isEmpty()) { + throw new InvalidConfigurationException("Property - 'url' cannot be found"); + } + try { + this.uri = endpoint; + URL url = new URL(endpoint); + hostConfiguration = new HostConfiguration(); + hostConfiguration.setHost(url.getHost(), url.getPort(), url.getProtocol()); + this.authorizationHeaderValue = config.getProperties().get(AUTHORIZATION_HEADER_PROPERTY); + executorService = Executors.newFixedThreadPool(1); + httpClient = new HttpClient(); + } catch (MalformedURLException e) { + throw new InvalidConfigurationException("Property - 'url' is malformed.", e); + } + } + + @Override + public void init() { + + } + + @Override + public void execute(NotificationContext ctx) throws PushNotificationExecutionFailedException { + try { + executorService.submit(new HTTPMessageExecutor(ctx, authorizationHeaderValue, uri, hostConfiguration + , httpClient)); + } catch (RejectedExecutionException e) { + log.error("Failed to publish to external endpoint url: " + endpoint, e); + } + } + + @Override + public NotificationContext buildContext() { + return null; + } + + @Override + public void undeploy() { + executorService.shutdown(); + } + + @Override + public PushNotificationConfig getConfig() { + return config; + } + +} + diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/http/internal/HTTPPushNotificationServiceComponent.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/http/internal/HTTPPushNotificationServiceComponent.java new file mode 100644 index 0000000000..b16e1728d9 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/http/internal/HTTPPushNotificationServiceComponent.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2016, 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. + * + */ +package org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; + +/** + * @scr.component name="org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.internal.HTTPPushNotificationServiceComponent" immediate="true" + */ +public class HTTPPushNotificationServiceComponent { + + private static final Log log = LogFactory.getLog(HTTPPushNotificationServiceComponent.class); + + @SuppressWarnings("unused") + protected void activate(ComponentContext componentContext) { + try { + if (log.isDebugEnabled()) { + log.debug("Initializing HTTP based push notification provider implementation bundle"); + } + //Do nothing + if (log.isDebugEnabled()) { + log.debug("HTTP based push notification provider implementation bundle has been successfully " + + "initialized"); + } + } catch (Throwable e) { + log.error("Error occurred while initializing HTTP based push notification provider " + + "implementation bundle", e); + } + } + +} 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 e954b928ce..4e8aa8ee60 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 - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategy.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategy.java index 8af53af6b2..59653e7831 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategy.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategy.java @@ -21,8 +21,8 @@ package org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.InvalidConfigurationException; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -import org.wso2.carbon.device.mgt.common.policy.mgt.Profile; import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext; import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; @@ -46,36 +46,52 @@ public class MQTTNotificationStrategy implements NotificationStrategy { private String mqttAdapterName; private static final Log log = LogFactory.getLog(MQTTNotificationStrategy.class); private final PushNotificationConfig config; + private final String providerTenantDomain; + private static final Object lockObj = new Object(); public MQTTNotificationStrategy(PushNotificationConfig config) { this.config = config; OutputEventAdapterConfiguration adapterConfig = new OutputEventAdapterConfiguration(); adapterConfig.setType(MQTTAdapterConstants.MQTT_ADAPTER_TYPE); - mqttAdapterName = config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_NAME); - adapterConfig.setName(mqttAdapterName); adapterConfig.setMessageFormat(MessageType.TEXT); Map configProperties = new HashMap(); - String brokerUrl = config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_BROKER_URL); - if (brokerUrl != null && !brokerUrl.isEmpty()) { - configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_BROKER_URL, brokerUrl); + if (config.getProperties() != null && config.getProperties().size() > 0) { + String brokerUrl = config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_BROKER_URL); + if (brokerUrl != null && !brokerUrl.isEmpty()) { + configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_BROKER_URL, brokerUrl); + } + mqttAdapterName = config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_NAME); + configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_USERNAME, + config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_USERNAME)); + configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_PASSWORD, + config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_PASSWORD)); + configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_CLEAR_SESSION, + config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_CLEAR_SESSION)); + configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_SCOPES, + config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_SCOPES)); + configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_MESSAGE_QOS, + config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_MESSAGE_QOS)); + } else { + mqttAdapterName = "mqtt.adapter." + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain() + .toLowerCase(); } - configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_USERNAME, - config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_USERNAME)); - configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_PASSWORD, - config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_PASSWORD)); - configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_CLEAR_SESSION, - config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_CLEAR_SESSION)); - configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_SCOPES, - config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_SCOPES)); - configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_MESSAGE_QOS, - config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_MESSAGE_QOS)); + adapterConfig.setName(mqttAdapterName); adapterConfig.setStaticProperties(configProperties); try { - MQTTDataHolder.getInstance().getOutputEventAdapterService().create(adapterConfig); + synchronized (lockObj) { + try { + MQTTDataHolder.getInstance().getOutputEventAdapterService().isPolled(mqttAdapterName); + } catch (OutputEventAdapterException e) { + //event adapter not created + MQTTDataHolder.getInstance().getOutputEventAdapterService().create(adapterConfig); + } + } } catch (OutputEventAdapterException e) { throw new InvalidConfigurationException("Error occurred while initializing MQTT output event adapter", e); } + providerTenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain() + .toLowerCase(); } @Override @@ -85,42 +101,73 @@ public class MQTTNotificationStrategy implements NotificationStrategy { @Override public void execute(NotificationContext ctx) throws PushNotificationExecutionFailedException { + String adapterName = mqttAdapterName; + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); + if (!providerTenantDomain.equals(tenantDomain)) { + //this is to handle the device type shared with all tenant mode. + + adapterName = "mqtt.adapter." + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain() + .toLowerCase(); + try { + MQTTDataHolder.getInstance().getOutputEventAdapterService().isPolled(adapterName); + } catch (OutputEventAdapterException e) { + //event adapter not created + synchronized (lockObj) { + OutputEventAdapterConfiguration adapterConfig = new OutputEventAdapterConfiguration(); + adapterConfig.setType(MQTTAdapterConstants.MQTT_ADAPTER_TYPE); + adapterConfig.setMessageFormat(MessageType.TEXT); + adapterConfig.setName(adapterName); + Map configProperties = new HashMap(); + adapterConfig.setStaticProperties(configProperties); + try { + MQTTDataHolder.getInstance().getOutputEventAdapterService().create(adapterConfig); + } catch (OutputEventAdapterException e1) { + throw new PushNotificationExecutionFailedException + ("Error occurred while initializing MQTT output event adapter for shared tenant: " + + tenantDomain, e); + } + } + } + + } Operation operation = ctx.getOperation(); Properties properties = operation.getProperties(); if (properties != null && properties.get(MQTT_ADAPTER_TOPIC) != null) { Map dynamicProperties = new HashMap<>(); dynamicProperties.put("topic", (String) properties.get(MQTT_ADAPTER_TOPIC)); - MQTTDataHolder.getInstance().getOutputEventAdapterService().publish(mqttAdapterName, dynamicProperties, + MQTTDataHolder.getInstance().getOutputEventAdapterService().publish(adapterName, dynamicProperties, operation.getPayLoad()); } else { if (PolicyOperation.POLICY_OPERATION_CODE.equals(operation.getCode())) { PolicyOperation policyOperation = (PolicyOperation) operation; List profileOperations = policyOperation.getProfileOperations(); - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); String deviceType = ctx.getDeviceId().getType(); String deviceId = ctx.getDeviceId().getId(); for (ProfileOperation profileOperation : profileOperations) { Map dynamicProperties = new HashMap<>(); String topic = tenantDomain + "/" - + deviceType + "/" + deviceId + "/" + profileOperation.getType() + + deviceType + "/" + deviceId + "/operation/" + profileOperation.getType() .toString().toLowerCase() + "/" + profileOperation.getCode().toLowerCase(); dynamicProperties.put("topic", topic); - MQTTDataHolder.getInstance().getOutputEventAdapterService().publish(mqttAdapterName, dynamicProperties, + MQTTDataHolder.getInstance().getOutputEventAdapterService().publish(adapterName, dynamicProperties, profileOperation.getPayLoad()); } } else { Map dynamicProperties = new HashMap<>(); String topic = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true) + "/" - + ctx.getDeviceId().getType() + "/" + ctx.getDeviceId().getId() + "/" + operation.getType() - .toString().toLowerCase() + "/" + operation.getCode(); + + ctx.getDeviceId().getType() + "/" + ctx.getDeviceId().getId() + "/operation/" + + operation.getType().toString().toLowerCase() + "/" + operation.getCode() + "/" + operation.getId(); dynamicProperties.put("topic", topic); - if (operation.getPayLoad() == null) { - operation.setPayLoad(""); + Object payload; + if ("command".equals(operation.getType().toString().toLowerCase())) { + payload = operation.getCode(); + } else { + payload = operation.getPayLoad(); } - MQTTDataHolder.getInstance().getOutputEventAdapterService().publish(mqttAdapterName, dynamicProperties, - operation.getPayLoad()); + MQTTDataHolder.getInstance().getOutputEventAdapterService().publish(adapterName, dynamicProperties, + payload); } 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 b767cb933e..451a1d6515 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 - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/xmpp/XMPPNotificationStrategy.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/xmpp/XMPPNotificationStrategy.java index af3a1c6c4b..d091ecfd9d 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/xmpp/XMPPNotificationStrategy.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/xmpp/XMPPNotificationStrategy.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.InvalidConfigurationException; import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext; import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; diff --git a/components/device-mgt-extensions/pom.xml b/components/device-mgt-extensions/pom.xml index febe8a00f7..34a7bec6a1 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 - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../../pom.xml @@ -34,10 +34,12 @@ http://wso2.org + org.wso2.carbon.device.mgt.extensions.push.notification.provider.http org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp org.wso2.carbon.device.mgt.extensions.device.type.deployer + org.wso2.carbon.device.mgt.extensions.pull.notification diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml index 04bee77b9a..64d2f9dfbc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml @@ -3,7 +3,7 @@ org.wso2.carbon.devicemgt device-mgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml index 679b7264c5..f4657a1210 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml @@ -66,10 +66,6 @@ org.wso2.carbon org.wso2.carbon.utils - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.core - org.wso2.carbon.analytics-common org.wso2.carbon.databridge.agent @@ -118,6 +114,7 @@ org.osgi.framework, org.osgi.service.component, org.apache.commons.logging.*, + org.wso2.carbon.utils.multitenancy, org.wso2.carbon.context;version="${carbon.kernel.version.range}", org.wso2.carbon.utils;version="${carbon.kernel.version.range}", org.wso2.carbon.databridge.*;version="${carbon.analytics.common.version.range}", @@ -126,14 +123,15 @@ org.wso2.carbon.registry.indexing.*; version="${carbon.registry.imp.pkg.version.range}", org.json;version="${commons-json.version}", javax.xml.*, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, org.w3c.dom, - org.wso2.carbon.base + org.wso2.carbon.base, + org.wso2.carbon.utils.multitenancy - + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/service/EventsPublisherServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/service/EventsPublisherServiceImpl.java index 63e5bee1a6..4c039221c8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/service/EventsPublisherServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/service/EventsPublisherServiceImpl.java @@ -21,10 +21,12 @@ package org.wso2.carbon.device.mgt.analytics.data.publisher.service; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.databridge.agent.DataPublisher; import org.wso2.carbon.databridge.commons.utils.DataBridgeCommonsUtils; import org.wso2.carbon.device.mgt.analytics.data.publisher.DeviceDataPublisher; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; /** * This is the implementation of Osgi Service which can be used to publish and retireved @@ -39,23 +41,37 @@ public class EventsPublisherServiceImpl implements EventsPublisherService { * @param metaDataArray - meta data that needs to pushed * @param correlationDataArray - correlation data that needs to be pushed * @param payloadDataArray - payload data that needs to be pushed - * @return + * @return if success returns true * @throws DataPublisherConfigurationException */ @Override public boolean publishEvent(String streamName, String version, Object[] metaDataArray, Object[] correlationDataArray, Object[] payloadDataArray) throws DataPublisherConfigurationException { - DataPublisher dataPublisher = DeviceDataPublisher.getInstance().getDataPublisher(); - if (dataPublisher != null) { - String streamId = DataBridgeCommonsUtils.generateStreamId(streamName, version); - return dataPublisher.tryPublish(streamId, System.currentTimeMillis(), metaDataArray, correlationDataArray, - payloadDataArray); - } else { - return false; - } - } - - + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (metaDataArray == null || metaDataArray.length == 0) { + throw new DataPublisherConfigurationException("meta data[0] should have the device Id field"); + } else { + metaDataArray[0] = tenantDomain + "@" + metaDataArray[0]; + } + } + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext() + .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); + try { + DataPublisher dataPublisher = DeviceDataPublisher.getInstance().getDataPublisher(); + if (dataPublisher != null) { + String streamId = DataBridgeCommonsUtils.generateStreamId(streamName, version); + return dataPublisher.tryPublish(streamId, System.currentTimeMillis(), metaDataArray, + correlationDataArray, + payloadDataArray); + } else { + return false; + } + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } } \ No newline at end of file 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 6159d1ba32..dd86262e54 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 - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml @@ -38,8 +38,8 @@ maven-compiler-plugin - 1.7 - 1.7 + 1.8 + 1.8 @@ -167,6 +167,16 @@ org.wso2.carbon.device.mgt.common provided + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.analytics.data.publisher + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.extensions + provided + org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.core @@ -281,33 +291,77 @@ javax.ws.rs javax.ws.rs-api + + org.wso2.carbon.commons + org.wso2.carbon.application.mgt.stub + provided + - org.wso2.carbon.analytics-common - org.wso2.carbon.event.receiver.stub + org.wso2.carbon.analytics + org.wso2.carbon.analytics.api provided - org.wso2.carbon.analytics-common - org.wso2.carbon.event.stream.stub + org.wso2.carbon.analytics + org.wso2.carbon.analytics.datasource.commons provided - - org.wso2.carbon.commons - org.wso2.carbon.application.mgt.stub - provided - org.wso2.carbon.devicemgt org.wso2.carbon.identity.jwt.client.extension provided + + org.wso2.carbon + org.wso2.carbon.registry.core + provided + + + org.wso2.carbon.registry + org.wso2.carbon.registry.resource + provided + org.wso2.carbon.identity.framework org.wso2.carbon.identity.user.store.count ${carbon.identity.framework.version} provided - + + org.wso2.carbon.analytics + org.wso2.carbon.analytics.datasource.commons + provided + + + org.wso2.carbon.analytics + org.wso2.carbon.analytics.api + provided + + + org.wso2.carbon.analytics + org.wso2.carbon.analytics.dataservice.commons + provided + + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.receiver.stub + provided + + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.stream.stub + provided + + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.publisher.stub + provided + + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.stream.persistence.stub + provided + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/OperationRequest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/OperationRequest.java new file mode 100644 index 0000000000..d8cd2ec769 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/OperationRequest.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * 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. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.beans; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; + +import java.util.List; + +@ApiModel(value = "OperationRequest", description = "Operation details together with deviceIdentifier") +public class OperationRequest { + + @ApiModelProperty(name = "deviceIdentifiers", value = "list of devices that needs to be verified against the user", required = true) + List deviceIdentifiers; + @ApiModelProperty(name = "operation", value = "operation data", required = false) + Operation operation; + + public List getDeviceIdentifiers() { + return deviceIdentifiers; + } + + public void setDeviceIdentifiers(List deviceIdentifiers) { + this.deviceIdentifiers = deviceIdentifiers; + } + + public Operation getOperation() { + return operation; + } + + public void setOperation(Operation operation) { + this.operation = operation; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/Attribute.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/Attribute.java new file mode 100644 index 0000000000..276fea9ee4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/Attribute.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.beans.analytics; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; + +/** + * This hold the attribute definition. + */ +public class Attribute { + + @ApiModelProperty(value = "Event Attribute Name") + @JsonProperty("name") + private String name; + @ApiModelProperty(value = "Event Attribute Type") + @JsonProperty("type") + private AttributeType type; + + public Attribute() { + + } + + public Attribute(String name, AttributeType attributeType) { + this.name = name; + this.type = attributeType; + } + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public AttributeType getType() { + return type; + } + + public void setType(AttributeType type) { + this.type = type; + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/AttributeType.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/AttributeType.java new file mode 100644 index 0000000000..23235612b9 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/AttributeType.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.beans.analytics; + +/** + * This hold the definition of the attribute type for the attributes. + */ +public enum AttributeType { + STRING, LONG, BOOL, INT, FLOAT, DOUBLE; + + @Override + public String toString() { + return super.toString().toLowerCase(); + } +} + 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 new file mode 100644 index 0000000000..7ff162b357 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/DeviceTypeEvent.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.beans.analytics; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; + +/** + * This hold stats data record + */ +public class DeviceTypeEvent { + + private EventAttributeList eventAttributes; + private TransportType transport; + + @ApiModelProperty(value = "Attributes related to device type event") + @JsonProperty("eventAttributes") + public EventAttributeList getEventAttributeList() { + return eventAttributes; + } + + public void setEventAttributeList( + EventAttributeList eventAttributes) { + this.eventAttributes = eventAttributes; + } + + @ApiModelProperty(value = "Transport to be used for device to server communication.") + @JsonProperty("transport") + public TransportType getTransportType() { + return transport; + } + + public void setTransportType(TransportType transport) { + this.transport = transport; + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/EventAttributeList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/EventAttributeList.java new file mode 100644 index 0000000000..fe9bd39e03 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/EventAttributeList.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.beans.analytics; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.jaxrs.beans.BasePaginatedResult; + +import java.util.ArrayList; +import java.util.List; + +/** + * This holds event attributes + */ +public class EventAttributeList { + + private List attributes = new ArrayList<>(); + + @ApiModelProperty(value = "List of Event Attributes") + @JsonProperty("attributes") + public List getList() { + return attributes; + } + + public void setList(List attributes) { + this.attributes = attributes; + } + +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/EventRecords.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/EventRecords.java new file mode 100644 index 0000000000..0dacde3833 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/EventRecords.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.beans.analytics; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; +import org.wso2.carbon.device.mgt.common.Device; + +import java.util.ArrayList; +import java.util.List; +import org.wso2.carbon.analytics.datasource.commons.Record; +import org.wso2.carbon.device.mgt.jaxrs.beans.BasePaginatedResult; + +/** + * This hold stats data record + */ +public class EventRecords extends BasePaginatedResult { + + private List records = new ArrayList<>(); + + @ApiModelProperty(value = "List of records returned") + @JsonProperty("records") + public List getRecord() { + return records; + } + + public void setList(List records) { + this.records = records; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + + sb.append(" count: ").append(getCount()).append(",\n"); + sb.append(" records: [").append(records).append("\n"); + sb.append("]}\n"); + return sb.toString(); + } + +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/TransportType.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/TransportType.java new file mode 100644 index 0000000000..58eae4e616 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/TransportType.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.beans.analytics; + +/** + * This hold the default transport types support by the server. + */ +public enum TransportType { + HTTP, MQTT; +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java index bf99446804..62f07e362c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java @@ -140,6 +140,93 @@ public interface ActivityInfoProviderService { @HeaderParam("If-Modified-Since") String ifModifiedSince); + @GET + @Path("/{id}/{devicetype}/{deviceid}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Details of an Activity for a specific device", + notes = "Retrieve the details of a specific activity/operation, such as the meta information of " + + "an operation, including the responses from a given device", + tags = "Activity Info Provider", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:get-activity") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the activity details.", + response = Activity.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. \n Empty body because the client already has the latest version of " + + "the requested resource."), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 404, + message = "Not Found. \n No activity found with the given ID.", + 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 activity data.", + response = ErrorResponse.class) + }) + Response getActivityByDevice( + @ApiParam( + name = "id", + value = "Activity id of the operation/activity.", + required = true, + defaultValue = "ACTIVITY_1") + @PathParam("id") + @Size(max = 45) + String id, + @ApiParam( + name = "devicetype", + value = "The device type name, such as ios, android, windows or fire-alarm.", + required = true) + @PathParam("devicetype") + @Size(max = 45) + String type, + @ApiParam( + name = "deviceid", + value = "The device identifier of the device you want ot get details.", + required = true) + @PathParam("deviceid") + @Size(max = 45) + String deviceid, + @ApiParam( + name = "If-Modified-Since", + value = "Checks if the requested variant was modified, since the specified date-time\n." + + "Provide the value in the Java Date Format: EEE, d MMM yyyy HH:mm:ss Z\n." + + "Example: Mon, 05 Jan 2014 15:10:00 +0200", + required = false) + @HeaderParam("If-Modified-Since") String ifModifiedSince); + @GET @ApiOperation( produces = MediaType.APPLICATION_JSON, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceAgentService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceAgentService.java new file mode 100644 index 0000000000..ce442701e1 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceAgentService.java @@ -0,0 +1,608 @@ +/* + * Copyright (c) 2016, 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. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.service.api; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Extension; +import io.swagger.annotations.ExtensionProperty; +import io.swagger.annotations.Info; +import io.swagger.annotations.ResponseHeader; +import io.swagger.annotations.SwaggerDefinition; +import io.swagger.annotations.Tag; +import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList; +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; + +import javax.validation.Valid; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +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; +import java.util.Map; + +@SwaggerDefinition( + info = @Info( + version = "1.0.0", + title = "", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = "name", value = "DeviceAgent Service"), + @ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/device/agent"), + }) + } + ), + tags = { + @Tag(name = "device_agent, device_management", description = "") + } +) +@Api(value = "Device Agent", description = "Device Agent Service") +@Path("/device/agent") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +@Scopes( + scopes = { + @Scope( + name = "Enroll Device", + description = "Register a device", + key = "perm:device:enroll", + permissions = {"/device-mgt/devices/owning-device/add"} + ), + @Scope( + name = "Modify Device", + description = "Modify a device", + key = "perm:device:modify", + permissions = {"/device-mgt/devices/owning-device/modify"} + ), + @Scope( + name = "Disenroll Device", + description = "Disenroll a device", + key = "perm:device:disenroll", + permissions = {"/device-mgt/devices/owning-device/remove"} + ), + @Scope( + name = "Publish Event", + description = "publish device event", + key = "perm:device:publish-event", + permissions = {"/device-mgt/devices/owning-device/event"} + ), + @Scope( + name = "Getting Device Operation Details", + description = "Getting Device Operation Details", + key = "perm:device:operations", + permissions = {"/device-mgt/devices/owning-device/view"} + ) + } +) +public interface DeviceAgentService { + + @POST + @Path("/enroll") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Create a device instance", + notes = "Create a device Instance", + tags = "Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:enroll") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully created a device instance.", + 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 deviceType with the specified device type 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 enrollDevice(@ApiParam(name = "device", value = "Device object with data.", required = true) + @Valid Device device); + + @DELETE + @Path("/enroll/{type}/{id}") + @ApiOperation( + httpMethod = "DELETE", + value = "Unregistering a Device", + notes = "Use this REST API to unregister a device.", + tags = "Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:disenroll") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully disenrolled the device."), + @ApiResponse( + code = 404, + message = "Not Found. \n The specified resource does not exist."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while dis-enrolling the device.") + }) + Response disEnrollDevice( + @ApiParam(name = "type", value = "The unique device identifier.") @PathParam("type") String type, + @ApiParam(name = "id", value = "The unique device identifier.") @PathParam("id") String id); + + @PUT + @Path("/enroll/{type}/{id}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "modify device", + notes = "modify device", + tags = "Device Agent Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:modify") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully updated device instance.", + 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 deviceType with the specified device type 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 updateDevice(@ApiParam(name = "type", value = "The device type, such as ios, android or windows....etc", required = true) + @PathParam("type") String type, + @ApiParam(name = "id", value = "The device id.", required = true) + @PathParam("id") String deviceId, + @ApiParam(name = "device", value = "Device object with data.", required = true) + @Valid Device updateDevice); + + @POST + @Path("/events/publish/{type}/{deviceId}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + consumes = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Publishing Events", + notes = "Publish events received by the device client to the WSO2 Data Analytics Server (DAS) using this API.", + tags = "Device Agent Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:publish-event") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse(code = 200, message = "OK. \n Successfully published the event", + 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 = 303, + message = "See Other. \n The source can be retrieved from the URL specified in the location header.", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The Source URL of the document.")}), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error."), + @ApiResponse( + code = 415, + message = "Unsupported media type. \n The format of the requested entity was not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while publishing events.") + }) + Response publishEvents( + @ApiParam( + name = "payloadData", + value = "Information of the agent event to be published on DAS.") + @Valid + Map payloadData, + @ApiParam( + name = "type", + value = "name of the device type") + @PathParam("type") String type, + @ApiParam( + name = "deviceId", + value = "deviceId of the device") + @PathParam("deviceId") String deviceId); + + @POST + @Path("/events/publish/data/{type}/{deviceId}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + consumes = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Publishing Events data only", + notes = "Publish events received by the device client to the WSO2 Data Analytics Server (DAS) using this API.", + tags = "Device Agent Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:publish-event") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse(code = 200, message = "OK. \n Successfully published the event", + 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 = 303, + message = "See Other. \n The source can be retrieved from the URL specified in the location header.", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The Source URL of the document.")}), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error."), + @ApiResponse( + code = 415, + message = "Unsupported media type. \n The format of the requested entity was not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while publishing events.") + }) + Response publishEvents( + @ApiParam( + name = "payloadData", + value = "Information of the agent event to be published on DAS.") + @Valid + List payloadData, + @ApiParam( + name = "type", + value = "name of the device type") + @PathParam("type") String type, + @ApiParam( + name = "deviceId", + value = "deviceId of the device") + @PathParam("deviceId") String deviceId); + + @GET + @Path("/pending/operations/{type}/{id}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + consumes = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get pending operation of the given device", + notes = "Returns the Operations.", + tags = "Device Agent Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:operations") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully retrieved the operations.", + response = OperationList.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. Empty body because the client already has the latest " + + "version of the requested resource."), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n No device is found under the provided type and id.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while retrieving information requested device.", + response = ErrorResponse.class) + }) + Response getPendingOperations(@ApiParam(name = "type", value = "The device type, such as ios, android or windows.", required = true) + @PathParam("type") String type, + @ApiParam(name = "id", value = "The device id.", required = true) + @PathParam("id") String deviceId); + + @GET + @Path("/next-pending/operation/{type}/{id}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + consumes = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get pending operation of the given device", + notes = "Returns the Operation.", + tags = "Device Agent Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:operations") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully retrieved the operation.", + response = Operation.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. Empty body because the client already has the latest " + + "version of the requested resource."), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n No device is found under the provided type and id.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while retrieving information requested device.", + response = ErrorResponse.class) + }) + Response getNextPendingOperation(@ApiParam(name = "type", value = "The device type, such as ios, android or windows.", required = true) + @PathParam("type") String type, + @ApiParam(name = "id", value = "The device id.", required = true) + @PathParam("id") String deviceId); + + @PUT + @Path("/operations/{type}/{id}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + consumes = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Update Operation", + notes = "Update the Operations.", + tags = "Device Agent Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:operations") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully updated the operations.", + 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. Empty body because the client already has the latest " + + "version of the requested resource."), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n No device is found under the provided type and id.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while retrieving information requested device.", + response = ErrorResponse.class) + }) + Response updateOperation(@ApiParam(name = "type", value = "The device type, such as ios, android or windows.", required = true) + @PathParam("type") String type, + @ApiParam(name = "id", value = "The device id.", required = true) + @PathParam("id") String deviceId, + @ApiParam(name = "operation", value = "Operation object with data.", required = true) + @Valid Operation operation); + + @GET + @Path("/status/operations/{type}/{id}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + consumes = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get pending operation of the given device", + notes = "Returns the Operations.", + tags = "Device Agent Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device:operations") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully retrieved the operations.", + response = OperationList.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. Empty body because the client already has the latest " + + "version of the requested resource."), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n No device is found under the provided type and id.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while retrieving information requested device.", + response = ErrorResponse.class) + }) + Response getOperationsByDeviceAndStatus(@ApiParam(name = "type", value = "The device type, such as ios, android or windows.", required = true) + @PathParam("type") String type, + @ApiParam(name = "id", value = "The device id.", required = true) + @PathParam("id") String deviceId, + @ApiParam(name = "status", value = "status of the operation.", required = true) + @QueryParam("status")Operation.Status status); + +} 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 new file mode 100644 index 0000000000..8b6d7ed030 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceEventManagementService.java @@ -0,0 +1,347 @@ +package org.wso2.carbon.device.mgt.jaxrs.service.api; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Extension; +import io.swagger.annotations.ExtensionProperty; +import io.swagger.annotations.Info; +import io.swagger.annotations.ResponseHeader; +import io.swagger.annotations.SwaggerDefinition; +import io.swagger.annotations.Tag; +import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; +import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceTypeList; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.DeviceTypeEvent; +import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventAttributeList; +import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventRecords; +import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.TransportType; +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; + +import javax.validation.Valid; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@SwaggerDefinition( + info = @Info( + version = "1.0.0", + title = "", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = "name", value = "DeviceEventManagement"), + @ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/events"), + }) + } + ), + tags = { + @Tag(name = "device_management", description = "") + } +) +@Scopes( + scopes = { + @Scope( + name = "Add or Delete Event Definition for device type", + description = "Add or Delete Event Definition for device type", + key = "perm:device-types:events", + permissions = {"/device-mgt/device-type/add"} + ), + @Scope( + name = "Get Events Details of a Device Type", + description = "Get Events Details of a Device Type", + key = "perm:device-types:events:view", + permissions = {"/device-mgt/devices/owning-device/view"} + ) + } +) +@Path("/events") +@Api(value = "Device Event Management", description = "This API corresponds to all tasks related to device " + + "event management") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public interface DeviceEventManagementService { + + @POST + @Path("/{type}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Add Event Type Defnition", + notes = "Add the event definition for the 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 = "name of the device type", required = false) + @PathParam("type")String deviceType, + @ApiParam(name = "deviceTypeEvent", value = "DeviceTypeEvent object with data.", required = true) + @Valid DeviceTypeEvent deviceTypeEvent); + + @DELETE + @Path("/{type}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "DELETE", + value = "Delete Event Type Defnition", + notes = "Delete the event definition for the 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 deleted the event definition.", + 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 deleteDeviceTypeEventDefinitions(@ApiParam(name = "type", value = "name of the device type", required = false) + @PathParam("type")String deviceType); + + @GET + @Path("/{type}/{deviceId}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Device Events", + notes = "Get the events for the device.", + tags = "Device Event Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the event definition.", + response = EventRecords.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"), + @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 getData(@ApiParam(name = "deviceId", value = "id of the device ", required = false) + @PathParam("deviceId") String deviceId, + @ApiParam(name = "from", value = "unix timestamp to retrieve", required = false) + @QueryParam("from") long from, + @ApiParam(name = "to", value = "unix time to retrieve", required = false) + @QueryParam("to") long to, + @ApiParam(name = "type", value = "name of the device type", required = false) + @PathParam("type") String deviceType, + @ApiParam(name = "offset", value = "offset of the records that needs to be picked up", required = false) + @QueryParam("offset") int offset, + @ApiParam(name = "limit", value = "limit of the records that needs to be picked up", required = false) + @QueryParam("limit") int limit); + + @GET + @Path("last-known/{type}/{deviceId}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Last Known Device Events", + notes = "Get the Last Known events for the device.", + tags = "Device Event Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the event.", + response = EventRecords.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"), + @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 getLastKnownData(@ApiParam(name = "deviceId", value = "id of the device ", required = false) + @PathParam("deviceId") String deviceId, + @ApiParam(name = "type", value = "name of the device type", required = false) + @PathParam("type") String deviceType); + + @GET + @Path("/{type}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Event Type Defnition", + notes = "Get the event definition for the device.", + tags = "Device Event Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the event defintion.", + response = DeviceTypeEvent.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"), + @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 getDeviceTypeEventDefinition(@ApiParam(name = "type", value = "name of the device type", required = false) + @PathParam("type")String deviceType) ; + +} 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 ddbdfcdc08..53de86e45d 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 @@ -32,17 +32,22 @@ import io.swagger.annotations.Tag; import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scopes; 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.Feature; import org.wso2.carbon.device.mgt.common.app.mgt.Application; +import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData; import org.wso2.carbon.device.mgt.common.search.SearchContext; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList; +import org.wso2.carbon.device.mgt.jaxrs.beans.OperationRequest; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; +import javax.validation.Valid; import javax.validation.constraints.Size; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -56,6 +61,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; /** * Device related REST-API. This can be used to manipulated device related details. @@ -221,6 +227,12 @@ public interface DeviceManagementService { required = false) @QueryParam("user") String user, + @ApiParam( + name = "userPattern", + value = "The pattern of username of the owner of the device.", + required = false) + @QueryParam("userPattern") + String userPattern, @ApiParam( name = "role", value = "A role of device owners. Ex : store-admin", @@ -267,6 +279,13 @@ public interface DeviceManagementService { required = false) @HeaderParam("If-Modified-Since") String timestamp, + @ApiParam( + name = "requireDeviceInfo", + value = "Boolean flag indicating whether to include device-info (location, application list etc) \n" + + " to the device object.", + required = false) + @QueryParam("requireDeviceInfo") + boolean requireDeviceInfo, @ApiParam( name = "offset", value = "The starting pagination index for the complete list of qualified items.", @@ -333,6 +352,13 @@ public interface DeviceManagementService { }) @Path("/user-devices") Response getDeviceByUser( + @ApiParam( + name = "requireDeviceInfo", + value = "Boolean flag indicating whether to include device-info (location, application list etc) \n" + + " to the device object.", + required = false) + @QueryParam("requireDeviceInfo") + boolean requireDeviceInfo, @ApiParam( name = "offset", value = "The starting pagination index for the complete list of qualified items.", @@ -423,6 +449,60 @@ public interface DeviceManagementService { @HeaderParam("If-Modified-Since") String ifModifiedSince); + @PUT + @Path("/{type}/{id}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get device enrollment status", + notes = "Get device enrollment status", + tags = "Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully created a device instance.", + 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 deviceType with the specified device type 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 isEnrolled(@ApiParam(name = "type", value = "The device type, such as ios, android or windows.", required = true) + @PathParam("type") String type, + @ApiParam(name = "id", value = "The device id.", required = true) + @PathParam("id") String deviceId); @GET @Path("/{type}/{id}/location") @@ -1233,4 +1313,62 @@ public interface DeviceManagementService { @QueryParam("newStatus") EnrolmentInfo.Status newStatus); + @POST + @Path("/{type}/operations") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + consumes = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Add operation to set of devices for a given device type", + notes = "Returns the Activity Related to the operation.", + tags = "Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:operations") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 201, + message = "OK. \n Successfully added the operation.", + response = Activity.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. Empty body because the client already has the latest " + + "version of the requested resource."), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n No device is found under the provided type and id.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while retrieving information requested device.", + response = ErrorResponse.class) + }) + Response addOperation(@ApiParam(name = "type", value = "The device type, such as ios, android or windows... etc.", required = true) + @PathParam("type") String type, + @ApiParam(name = "deviceOperation", value = "Operation object with device ids.", required = true) + @Valid OperationRequest operationRequest); + + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceTypeManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceTypeManagementService.java index b71c918fca..390bb2dca4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceTypeManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceTypeManagementService.java @@ -31,6 +31,7 @@ import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ResponseHeader; import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scopes; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceTypeList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; @@ -206,4 +207,103 @@ public interface DeviceTypeManagementService { @HeaderParam("If-Modified-Since") String ifModifiedSince); + @GET + @Path("/all/{type}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Details of a Device Type", + notes = "Get the details of a device by searching via the device type and the tenant domain.", + response = DeviceType.class, + tags = "Device Type Management Administrative Service", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:types") + }) + } + ) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the device type.", + response = DeviceType.class, + responseContainer = "List", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 304, + message = "Not Modified. Empty body because the client already has the latest version of the " + + "requested resource.\n"), + @ApiResponse( + code = 401, + message = "Unauthorized.\n The unauthorized access to the requested resource.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found.\n The specified device does not exist", + 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 device list.", + response = ErrorResponse.class) + }) + Response getDeviceTypeByName( + @ApiParam( + name = "type", + value = "The device type name, such as ios, android, windows or fire-alarm.", + required = true) + @PathParam("type") + @Size(min = 2, max = 45) + String type); + + @GET + @Path("/all") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Retrieve device types information", + notes = "Retrieve device types information.", + response = DeviceType.class, + tags = "Device Type Management Administrative Service", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:types") + }) + } + ) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the device type.", + response = DeviceType.class, + responseContainer = "List", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 304, + message = "Not Modified. Empty body because the client already has the latest version of the " + + "requested resource.\n"), + @ApiResponse( + code = 401, + message = "Unauthorized.\n The unauthorized access to the requested resource.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found.\n The specified device does not exist", + 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 device list.", + response = ErrorResponse.class) + }) + Response getDeviceTypes(); + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java new file mode 100644 index 0000000000..094781fe79 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java @@ -0,0 +1,478 @@ +/* + * Copyright (c) 2017, 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. + */ + + +package org.wso2.carbon.device.mgt.jaxrs.service.api; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Extension; +import io.swagger.annotations.ExtensionProperty; +import io.swagger.annotations.Info; +import io.swagger.annotations.ResponseHeader; +import io.swagger.annotations.SwaggerDefinition; +import io.swagger.annotations.Tag; +import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; +import org.wso2.carbon.device.mgt.common.geo.service.Alert; +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; + +import javax.validation.Valid; +import javax.validation.constraints.Size; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +@SwaggerDefinition( + info = @Info( + version = "1.0.0", + title = "", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = "name", value = "geo_services"), + @ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/geo-services"), + }) + } + ), + tags = { + @Tag(name = "device_management", description = "") + } +) +@Scopes( + scopes = { + @Scope( + name = "View Analytics", + description = "", + key = "perm:geo-service:analytics-view", + permissions = {"/device-mgt/devices/owning-device/view-analytics"} + ), + @Scope( + name = "Manage Alerts", + description = "", + key = "perm:geo-service:alerts-manage", + permissions = {"/device-mgt/devices/owning-device/manage-alerts"} + ) + } +) +@Path("/geo-services") +@Api(value = "Geo Service", + description = "This carries all the resources related to the geo service functionalities.") +public interface GeoLocationBasedService { + /** + * Retrieve Analytics for the device type + */ + @GET + @Path("stats/{deviceType}/{deviceId}") + @ApiOperation( + consumes = "application/json", + produces = "application/json", + httpMethod = "GET", + value = "Retrieve Analytics for the device type", + notes = "", + response = Response.class, + tags = "Geo Service Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:analytics-view") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @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 Device Identifiers found.", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response getGeoDeviceStats( + @ApiParam( + name = "deviceId", + value = "The registered device Id.", + required = true) + @PathParam("deviceId") String deviceId, + @ApiParam( + name = "device-type", + value = "The device type, such as ios, android or windows.", + required = true) + @PathParam("deviceType") + @Size(max = 45) + String deviceType, + @ApiParam( + name = "from", + value = "Get stats from what time", + required = true) + @QueryParam("from") long from, + @ApiParam( + name = "to", + value = "Get stats up to what time", + required = true) + @QueryParam("to") long to); + + /** + * Create Geo alerts + */ + @POST + @Path("alerts/{alertType}/{deviceType}/{deviceId}") + @ApiOperation( + consumes = "application/json", + produces = "application/json", + httpMethod = "GET", + value = "Create Geo alerts for the device", + notes = "", + response = Response.class, + tags = "Geo Service Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid Device Identifiers found.", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response createGeoAlerts( + @ApiParam( + name = "alert", + value = "The alert object", + required = true) + @Valid Alert alert, + @ApiParam( + name = "deviceId", + value = "The registered device Id.", + required = true) + @PathParam("deviceId") String deviceId, + @ApiParam( + name = "device-type", + value = "The device type, such as ios, android or windows.", + required = true) + @PathParam("deviceType") + @Size(max = 45) + String deviceType, + @ApiParam( + name = "alertType", + value = "The alert type, such as Within, Speed, Stationary", + required = true) + @PathParam("alertType") String alertType); + + /** + * Update Geo alerts + */ + @PUT + @Path("alerts/{alertType}/{deviceType}/{deviceId}") + @ApiOperation( + consumes = "application/json", + produces = "application/json", + httpMethod = "GET", + value = "Update Geo alerts for the device", + notes = "", + response = Response.class, + tags = "Geo Service Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid Device Identifiers found.", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response updateGeoAlerts( + @ApiParam( + name = "alert", + value = "The alert object", + required = true) + @Valid Alert alert, + @ApiParam( + name = "deviceId", + value = "The registered device Id.", + required = true) + @PathParam("deviceId") String deviceId, + @ApiParam( + name = "device-type", + value = "The device type, such as ios, android or windows.", + required = true) + @PathParam("deviceType") + @Size(max = 45) + String deviceType, + @ApiParam( + name = "alertType", + value = "The alert type, such as Within, Speed, Stationary", + required = true) + @PathParam("alertType") String alertType); + + /** + * Retrieve Geo alerts + */ + @GET + @Path("alerts/{alertType}/{deviceType}/{deviceId}") + @ApiOperation( + consumes = "application/json", + produces = "application/json", + httpMethod = "GET", + value = "Retrieve Geo alerts for the device", + notes = "", + response = Response.class, + tags = "Geo Service Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @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 Device Identifiers found.", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response getGeoAlerts( + @ApiParam( + name = "deviceId", + value = "The registered device Id.", + required = true) + @PathParam("deviceId") String deviceId, + @ApiParam( + name = "device-type", + value = "The device type, such as ios, android or windows.", + required = true) + @PathParam("deviceType") + @Size(max = 45) + String deviceType, + @ApiParam( + name = "alertType", + value = "The alert type, such as Within, Speed, Stationary", + required = true) + @PathParam("alertType") String alertType); + + /** + * Retrieve Geo alerts history + */ + @GET + @Path("alerts/history/{deviceType}/{deviceId}") + @ApiOperation( + consumes = "application/json", + produces = "application/json", + httpMethod = "GET", + value = "Retrieve Geo alerts history for the device", + notes = "", + response = Response.class, + tags = "Geo Service Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @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 Device Identifiers found.", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response getGeoAlertsHistory( + @ApiParam( + name = "deviceId", + value = "The registered device Id.", + required = true) + @PathParam("deviceId") String deviceId, + @ApiParam( + name = "device-type", + value = "The device type, such as ios, android or windows.", + required = true) + @PathParam("deviceType") + @Size(max = 45) + String deviceType, + @ApiParam( + name = "from", + value = "Get stats from what time", + required = true) + @QueryParam("from") long from, + @ApiParam( + name = "to", + value = "Get stats up to what time", + required = true) + @QueryParam("to") long to); + + @DELETE + @Path("alerts/{alertType}/{deviceType}/{deviceId}") + @ApiOperation( + consumes = "application/json", + produces = "application/json", + httpMethod = "DELETE", + value = "Deletes Geo alerts for the device", + notes = "", + response = Response.class, + tags = "Geo Service Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid Device Identifiers found.", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response removeGeoAlerts( + @ApiParam( + name = "deviceId", + value = "The registered device Id.", + required = true) + @PathParam("deviceId") String deviceId, + @ApiParam( + name = "deviceType", + value = "The device type, such as ios, android or windows.", + required = true) + @PathParam("deviceType") String deviceType, + @ApiParam( + name = "alertType", + value = "The alert type, such as Within, Speed, Stationary", + required = true) + @PathParam("alertType") String alertType, + @ApiParam( + name = "queryName", + value = "The query name.", + required = true) + @QueryParam("queryName") String queryName); +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceAccessAuthorizationAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceAccessAuthorizationAdminService.java index 8a46b9b194..6a4b12d72e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceAccessAuthorizationAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceAccessAuthorizationAdminService.java @@ -115,4 +115,43 @@ public interface DeviceAccessAuthorizationAdminService { response = ErrorResponse.class) }) Response isAuthorized(AuthorizationRequest authorizationRequest); + + @POST + @Path("/stat") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Check for device access authorization for stat\n", + notes = "This is an internal API that can be used to check for authorization.", + response = DeviceAuthorizationResult.class, + tags = "Authorization Administrative Service", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:authorization:verify") + }) + }) + + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK. \n Authorized device list will be delivered to the requested services", + response = DeviceAuthorizationResult.class), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n The specified resource does not exist."), + @ApiResponse( + code = 415, + message = "Unsupported media type. \n The entity of the request was in a not supported format."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while checking the authorization" + + " for a specified set of devices.", + response = ErrorResponse.class) + }) + Response isAuthorizedForStat(AuthorizationRequest authorizationRequest); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypePublisherAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceAnalyticsArtifactUploaderAdminService.java similarity index 94% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypePublisherAdminService.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceAnalyticsArtifactUploaderAdminService.java index d3c3ee25c2..94220ef8cd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypePublisherAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceAnalyticsArtifactUploaderAdminService.java @@ -38,8 +38,8 @@ import javax.ws.rs.core.Response; title = "", extensions = { @Extension(properties = { - @ExtensionProperty(name = "name", value = "DeviceTypePublisherAdminService"), - @ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/admin/devicetype"), + @ExtensionProperty(name = "name", value = "DeviceAnalyticsArtifactUploaderAdminService"), + @ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/admin/publish-artifact"), }) } ), @@ -47,7 +47,7 @@ import javax.ws.rs.core.Response; @Tag(name = "device_management", description = "") } ) -@Path("/admin/devicetype") +@Path("/admin/publish-artifact") @Api(value = "Devicetype deployment Administrative Service", description = "This an API intended to be used to " + "deploy device type components" + "Further, this is strictly restricted to admin users only ") @@ -62,7 +62,7 @@ import javax.ws.rs.core.Response; } ) -public interface DeviceTypePublisherAdminService { +public interface DeviceAnalyticsArtifactUploaderAdminService { @POST @Path("/deploy/{type}") diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementAdminService.java new file mode 100644 index 0000000000..aa90b5b304 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementAdminService.java @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2016, 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. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.service.api.admin; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Extension; +import io.swagger.annotations.ExtensionProperty; +import io.swagger.annotations.Info; +import io.swagger.annotations.ResponseHeader; +import io.swagger.annotations.SwaggerDefinition; +import io.swagger.annotations.Tag; +import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceTypeList; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; + +import javax.validation.constraints.Size; +import javax.ws.rs.Consumes; +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.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@SwaggerDefinition( + info = @Info( + version = "1.0.0", + title = "", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = "name", value = "DeviceTypeManagementAdminService"), + @ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/admin/device-types"), + }) + } + ), + tags = { + @Tag(name = "device_management", description = "") + } +) +@Path("/admin/device-types") +@Api(value = "Device Type Management Administrative Service", description = "This an API intended to be used by " + + "'internal' components to log in as an admin user and do a selected number of operations. " + + "Further, this is strictly restricted to admin users only ") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +@Scopes( + scopes = { + @Scope( + name = "Getting Details of a Device", + description = "Getting Details of a Device", + key = "perm:admin:device-type", + permissions = {"/device-mgt/admin/device-type"} + ) + } +) +public interface DeviceTypeManagementAdminService { + + @GET + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting the Supported Device Type with Meta Definition", + notes = "Get the list of device types supported by WSO2 IoT.", + tags = "Device Type Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the list of supported device types.", + response = DeviceTypeList.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. \n Empty body because the client already has the latest version " + + "of the requested resource.\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 getDeviceTypes(); + + @POST + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Add a Device Type", + notes = "Add the details of a device type.", + tags = "Device Type Management Administrative Service", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type") + }) + } + ) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully added the device type.", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 304, + message = "Not Modified. Empty body because the client already has the latest version of the " + + "requested resource.\n"), + @ApiResponse( + code = 401, + message = "Unauthorized.\n The unauthorized access to the requested resource.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found.\n The specified device does not exist", + 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 device list.", + response = ErrorResponse.class) + }) + Response addDeviceType(@ApiParam( + name = "type", + value = "The device type such as ios, android, windows or fire-alarm.", + required = true)DeviceType deviceType); + + @PUT + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Update Device Type", + notes = "Update the details of a device type.", + response = DeviceType.class, + tags = "Device Type Management Administrative Service", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type") + }) + } + ) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully updated the device type.", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 304, + message = "Not Modified. Empty body because the client already has the latest version of the " + + "requested resource.\n"), + @ApiResponse( + code = 401, + message = "Unauthorized.\n The unauthorized access to the requested resource.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found.\n The specified device does not exist", + 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 device list.", + response = ErrorResponse.class) + }) + Response updateDeviceType(@ApiParam( + name = "type", + value = "The device type such as ios, android, windows or fire-alarm.", + required = true) DeviceType deviceType); + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java index 6ef0a8664d..2b39044d17 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; @@ -72,6 +73,43 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService } } + + @GET + @Override + @Path("/{id}/{devicetype}/{deviceid}") + public Response getActivityByDevice(@PathParam("id") + @Size(max = 45) String id, + @PathParam("devicetype") + @Size(max = 45) String devicetype, + @PathParam("deviceid") + @Size(max = 45) String deviceid, + @HeaderParam("If-Modified-Since") String ifModifiedSince) { + Activity activity; + DeviceManagementProviderService dmService; + try { + RequestValidationUtil.validateActivityId(id); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceid); + deviceIdentifier.setType(devicetype); + + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); + activity = dmService.getOperationByActivityIdAndDevice(id, deviceIdentifier); + if (activity == null) { + return Response.status(404).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("No activity can be " + + "found upon the provided activity id '" + id + "'").build()).build(); + } + return Response.status(Response.Status.OK).entity(activity).build(); + } catch (OperationManagementException e) { + String msg = "ErrorResponse occurred while fetching the activity for the supplied id."; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + } + + @GET @Override public Response getActivities(@QueryParam("since") String since, @QueryParam("offset") int offset, @@ -83,6 +121,10 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService long timestamp = 0; boolean isIfModifiedSinceSet = false; boolean isSinceSet = false; + if (log.isDebugEnabled()) { + log.debug("getActivities since: " + since + " , offset: " + offset + " ,limit: " + limit + " ," + + "ifModifiedSince: " + ifModifiedSince); + } RequestValidationUtil.validatePaginationParameters(offset, limit); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { Date ifSinceDate; @@ -112,14 +154,32 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService timestamp = sinceTimestamp / 1000; } + if (timestamp == 0) { + //If timestamp is not sent by the user, a default value is set, that is equal to current time-12 hours. + long time = System.currentTimeMillis() / 1000; + timestamp = time - 42300; + } + if (log.isDebugEnabled()) { + log.debug("getActivities final timestamp " + timestamp); + } + List activities; ActivityList activityList = new ActivityList(); DeviceManagementProviderService dmService; try { + if (log.isDebugEnabled()) { + log.debug("Calling database to get activities."); + } dmService = DeviceMgtAPIUtils.getDeviceManagementService(); activities = dmService.getActivitiesUpdatedAfter(timestamp, limit, offset); activityList.setList(activities); + if (log.isDebugEnabled()) { + log.debug("Calling database to get activity count."); + } int count = dmService.getActivityCountUpdatedAfter(timestamp); + if (log.isDebugEnabled()) { + log.debug("Activity count: " + count); + } activityList.setCount(count); if (activities == null || activities.size() == 0) { if (isIfModifiedSinceSet) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java new file mode 100644 index 0000000000..c72dfd9197 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java @@ -0,0 +1,574 @@ +/* + * Copyright (c) 2016, 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. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.service.impl; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.InvalidConfigurationException; +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.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList; +import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.Attribute; +import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.AttributeType; +import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventAttributeList; +import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceAgentService; +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +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.validation.Valid; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +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.core.Response; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@Path("/device/agent") +public class DeviceAgentServiceImpl implements DeviceAgentService { + private static final Log log = LogFactory.getLog(DeviceAgentServiceImpl.class); + private static final String POLICY_MONITOR = "POLICY_MONITOR"; + @POST + @Path("/enroll") + @Override + public Response enrollDevice(@Valid Device device) { + if (device == null) { + String errorMessage = "The payload of the device enrollment is incorrect."; + return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); + } + try { + DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); + if (device.getType() == null || device.getDeviceIdentifier() == null) { + String errorMessage = "The payload of the device enrollment is incorrect."; + return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); + } + Device existingDevice = dms.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + if (existingDevice != null && existingDevice.getEnrolmentInfo() != null && existingDevice + .getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) { + String errorMessage = "An active enrolment exists"; + return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); + } + device.getEnrolmentInfo().setOwner(DeviceMgtAPIUtils.getAuthenticatedUser()); + device.getEnrolmentInfo().setDateOfEnrolment(System.currentTimeMillis()); + device.getEnrolmentInfo().setDateOfLastUpdate(System.currentTimeMillis()); + boolean status = dms.enrollDevice(device); + return Response.status(Response.Status.OK).entity(status).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while enrolling the device, which carries the id '" + + device.getDeviceIdentifier() + "'"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (InvalidConfigurationException e) { + log.error("failed to add operation", e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } + } + + @DELETE + @Path("/enroll/{type}/{id}") + @Override + public Response disEnrollDevice(@PathParam("type") String type, @PathParam("id") String id) { + boolean result; + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, type); + try { + result = DeviceMgtAPIUtils.getDeviceManagementService().disenrollDevice(deviceIdentifier); + if (result) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NO_CONTENT).entity(type + " device that carries id '" + id + + "' has not been dis-enrolled").build(); + } + } catch (DeviceManagementException e) { + String msg = "Error occurred while enrolling the device, which carries the id '" + id + "'"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @PUT + @Path("/enroll/{type}/{id}") + @Override + public Response updateDevice(@PathParam("type") String type, @PathParam("id") String id, @Valid Device updateDevice) { + Device device; + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(id); + deviceIdentifier.setType(type); + try { + device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier); + } catch (DeviceManagementException e) { + String msg = "Error occurred while getting enrollment details of the device that carries the id '" + + id + "'"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + + if (updateDevice == null) { + String errorMessage = "The payload of the device enrollment is incorrect."; + log.error(errorMessage); + return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); + } + if (device == null) { + String errorMessage = "The device to be modified doesn't exist."; + log.error(errorMessage); + return Response.status(Response.Status.NOT_FOUND).entity(errorMessage).build(); + } + if (device.getEnrolmentInfo().getStatus() == EnrolmentInfo.Status.ACTIVE ) { + DeviceAccessAuthorizationService deviceAccessAuthorizationService = + DeviceMgtAPIUtils.getDeviceAccessAuthorizationService(); + boolean status; + try { + status = deviceAccessAuthorizationService.isUserAuthorized(new DeviceIdentifier(id, type)); + } catch (DeviceAccessAuthorizationException e) { + String msg = "Error occurred while modifying enrollment of the Android device that carries the id '" + + id + "'"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + if (!status) { + return Response.status(Response.Status.UNAUTHORIZED).build(); + } + } + if(updateDevice.getEnrolmentInfo() != null) { + device.getEnrolmentInfo().setDateOfLastUpdate(System.currentTimeMillis()); + device.setEnrolmentInfo(device.getEnrolmentInfo()); + } + device.getEnrolmentInfo().setOwner(DeviceMgtAPIUtils.getAuthenticatedUser()); + if(updateDevice.getDeviceInfo() != null) { + device.setDeviceInfo(updateDevice.getDeviceInfo()); + } + device.setDeviceIdentifier(id); + if(updateDevice.getDescription() != null) { + device.setDescription(updateDevice.getDescription()); + } + if(updateDevice.getName() != null) { + device.setName(updateDevice.getName()); + } + if(updateDevice.getFeatures() != null) { + device.setFeatures(updateDevice.getFeatures()); + } + if(updateDevice.getProperties() != null) { + device.setProperties(updateDevice.getProperties()); + } + boolean result; + try { + device.setType(type); + result = DeviceMgtAPIUtils.getDeviceManagementService().modifyEnrollment(device); + if (result) { + return Response.status(Response.Status.ACCEPTED).build(); + } else { + return Response.status(Response.Status.NOT_MODIFIED).build(); + } + } catch (DeviceManagementException e) { + String msg = "Error occurred while modifying enrollment of the Android device that carries the id '" + + id + "'"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @POST + @Path("/events/publish/{type}/{deviceId}") + @Override + public Response publishEvents(@Valid Map payload, @PathParam("type") String type + , @PathParam("deviceId") String deviceId) { + + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + EventStreamAdminServiceStub eventStreamAdminServiceStub = null; + try { + if (payload == null) { + String msg = "invalid payload structure"; + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } else { + boolean authorized = DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized + (new DeviceIdentifier(type, deviceId)); + if (!authorized) { + String msg = "Does not have permission to access the device."; + return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build(); + } + } + Object metaData[] = new Object[1]; + metaData[0] = deviceId; + EventAttributeList eventAttributeList = DeviceMgtAPIUtils.getDynamicEventCache().get(type); + if (eventAttributeList == null) { + String streamName = DeviceMgtAPIUtils.getStreamDefinition(type, tenantDomain); + eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub(); + EventStreamDefinitionDto eventStreamDefinitionDto = eventStreamAdminServiceStub.getStreamDefinitionDto( + streamName + ":" + Constants.DEFAULT_STREAM_VERSION); + if (eventStreamDefinitionDto == null) { + return Response.status(Response.Status.BAD_REQUEST).build(); + } else { + EventStreamAttributeDto[] eventStreamAttributeDtos = eventStreamDefinitionDto.getPayloadData(); + List attributes = new ArrayList<>(); + for (EventStreamAttributeDto eventStreamAttributeDto : eventStreamAttributeDtos) { + attributes.add(new Attribute(eventStreamAttributeDto.getAttributeName() + , AttributeType.valueOf(eventStreamAttributeDto.getAttributeType().toUpperCase()))); + + } + if (payload.size() != attributes.size()) { + String msg = "Payload does not match with the stream definition"; + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + eventAttributeList = new EventAttributeList(); + eventAttributeList.setList(attributes); + DeviceMgtAPIUtils.getDynamicEventCache().put(type, eventAttributeList); + } + } + int i = 0; + Object[] payloadData = new Object[eventAttributeList.getList().size()]; + for (Attribute attribute : eventAttributeList.getList()) { + if (attribute.getType() == AttributeType.INT) { + payloadData[i] = ((Double) payload.get(attribute.getName())).intValue(); + } else if (attribute.getType() == AttributeType.LONG) { + payloadData[i] = ((Double) payload.get(attribute.getName())).longValue(); + } else { + payloadData[i] = payload.get(attribute.getName()); + } + i++; + } + + if (DeviceMgtAPIUtils.getEventPublisherService().publishEvent(DeviceMgtAPIUtils.getStreamDefinition(type + , PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()) + , Constants.DEFAULT_STREAM_VERSION, metaData + , null, payloadData)) { + return Response.status(Response.Status.OK).build(); + } else { + String msg = "Error occurred while publishing the event."; + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } catch (DataPublisherConfigurationException e) { + String msg = "Error occurred while publishing the event."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (DeviceAccessAuthorizationException e) { + String msg = "Error occurred when checking for authorization"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (AxisFault e) { + log.error("Failed to retrieve 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(); + } finally { + if (eventStreamAdminServiceStub != null) { + try { + eventStreamAdminServiceStub.cleanup(); + } catch (AxisFault axisFault) { + log.warn("Failed to clean eventStreamAdminServiceStub"); + } + } + } + } + + @POST + @Path("/events/publish/data/{type}/{deviceId}") + @Override + public Response publishEvents(@Valid List payload, @PathParam("type") String type + , @PathParam("deviceId") String deviceId) { + + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + EventStreamAdminServiceStub eventStreamAdminServiceStub = null; + try { + if (payload == null) { + String msg = "Invalid payload structure"; + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } else { + boolean authorized = DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized + (new DeviceIdentifier(type, deviceId)); + if (!authorized) { + String msg = "Does not have permission to access the device."; + return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build(); + } + } + Object metaData[] = new Object[1]; + metaData[0] = deviceId; + EventAttributeList eventAttributeList = DeviceMgtAPIUtils.getDynamicEventCache().get(type); + if (eventAttributeList == null) { + String streamName = DeviceMgtAPIUtils.getStreamDefinition(type, tenantDomain); + eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub(); + EventStreamDefinitionDto eventStreamDefinitionDto = eventStreamAdminServiceStub.getStreamDefinitionDto( + streamName + ":" + Constants.DEFAULT_STREAM_VERSION); + if (eventStreamDefinitionDto == null) { + return Response.status(Response.Status.BAD_REQUEST).build(); + } else { + EventStreamAttributeDto[] eventStreamAttributeDtos = eventStreamDefinitionDto.getPayloadData(); + List attributes = new ArrayList<>(); + for (EventStreamAttributeDto eventStreamAttributeDto : eventStreamAttributeDtos) { + attributes.add(new Attribute(eventStreamAttributeDto.getAttributeName() + , AttributeType.valueOf(eventStreamAttributeDto.getAttributeType().toUpperCase()))); + + } + if (payload.size() != attributes.size()) { + String msg = "Payload does not match with the stream definition"; + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + eventAttributeList = new EventAttributeList(); + eventAttributeList.setList(attributes); + DeviceMgtAPIUtils.getDynamicEventCache().put(type, eventAttributeList); + } + } + int i = 0; + Object[] payloadData = new Object[eventAttributeList.getList().size()]; + for (Attribute attribute : eventAttributeList.getList()) { + if (attribute.getType() == AttributeType.INT) { + payloadData[i] = ((Double) payload.get(i)).intValue(); + } else if (attribute.getType() == AttributeType.LONG) { + payloadData[i] = ((Double) payload.get(i)).longValue(); + } else { + payloadData[i] = payload.get(i); + } + i++; + } + + if (DeviceMgtAPIUtils.getEventPublisherService().publishEvent(DeviceMgtAPIUtils.getStreamDefinition(type + , PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()) + , Constants.DEFAULT_STREAM_VERSION, metaData + , null, payloadData)) { + return Response.status(Response.Status.OK).build(); + } else { + String msg = "Error occurred while publishing the event."; + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } catch (DataPublisherConfigurationException e) { + String msg = "Error occurred while publishing the event."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (DeviceAccessAuthorizationException e) { + String msg = "Error occurred when checking for authorization"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (AxisFault e) { + log.error("Failed to retrieve 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(); + } finally { + if (eventStreamAdminServiceStub != null) { + try { + eventStreamAdminServiceStub.cleanup(); + } catch (AxisFault axisFault) { + log.warn("Failed to clean eventStreamAdminServiceStub"); + } + } + } + } + + @GET + @Path("/pending/operations/{type}/{id}") + public Response getPendingOperations(@PathParam("type") String type, @PathParam("id") String deviceId) { + try { + if (!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(type)) { + String errorMessage = "Device identifier list is empty"; + log.error(errorMessage); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, type); + if (!DeviceMgtAPIUtils.isValidDeviceIdentifier(deviceIdentifier)) { + String msg = "Device not found for identifier '" + deviceId + "'"; + log.error(msg); + return Response.status(Response.Status.NO_CONTENT).entity(msg).build(); + } + List operations = DeviceMgtAPIUtils.getDeviceManagementService().getPendingOperations( + deviceIdentifier); + OperationList operationsList = new OperationList(); + operationsList.setList(operations); + operationsList.setCount(operations.size()); + return Response.status(Response.Status.OK).entity(operationsList).build(); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); + } catch (DeviceManagementException e) { + String errorMessage = "Issue in retrieving deivce management service instance"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); + } + } + + @GET + @Path("/next-pending/operation/{type}/{id}") + public Response getNextPendingOperation(@PathParam("type") String type, @PathParam("id") String deviceId) { + try { + if (!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(type)) { + String errorMessage = "Device type is invalid"; + log.error(errorMessage); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, type); + if (!DeviceMgtAPIUtils.isValidDeviceIdentifier(deviceIdentifier)) { + String msg = "Device not found for identifier '" + deviceId + "'"; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + Operation operation = DeviceMgtAPIUtils.getDeviceManagementService().getNextPendingOperation( + deviceIdentifier); + return Response.status(Response.Status.OK).entity(operation).build(); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); + } catch (DeviceManagementException e) { + String errorMessage = "Issue in retrieving deivce management service instance"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); + } + } + + @PUT + @Path("/operations/{type}/{id}") + public Response updateOperation(@PathParam("type") String type, @PathParam("id") String deviceId, @Valid Operation operation) { + try { + if (!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(type)) { + String errorMessage = "Device type is invalid"; + log.error(errorMessage); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + if (operation == null) { + String errorMessage = "Operation cannot empty"; + log.error(errorMessage); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, type); + if (!DeviceMgtAPIUtils.isValidDeviceIdentifier(deviceIdentifier)) { + String msg = "Device not found for identifier '" + deviceId + "'"; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + if (!Operation.Status.ERROR.equals(operation.getStatus()) && operation.getCode() != null && + POLICY_MONITOR.equals(operation.getCode())) { + if (log.isDebugEnabled()) { + log.info("Received compliance status from POLICY_MONITOR operation ID: " + operation.getId()); + } + List features = getComplianceFeatures(operation.getPayLoad()); + DeviceMgtAPIUtils.getPolicyManagementService().checkCompliance(deviceIdentifier, features); + + } else { + DeviceMgtAPIUtils.getDeviceManagementService().updateOperation(deviceIdentifier, operation); + } + return Response.status(Response.Status.OK).build(); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); + } catch (DeviceManagementException e) { + String errorMessage = "Issue in retrieving deivce management service instance"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); + } catch (PolicyComplianceException e) { + String errorMessage = "Issue in retrieving deivce management service instance"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); + } + } + + @GET + @Path("/status/operations/{type}/{id}") + public Response getOperationsByDeviceAndStatus(@PathParam("type") String type, @PathParam("id") String deviceId, + @QueryParam("status") Operation.Status status) { + if (status == null) { + String errorMessage = "Status is empty"; + log.error(errorMessage); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + + try { + if (!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(type)) { + String errorMessage = "Invalid Device Type"; + log.error(errorMessage); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + List operations = DeviceMgtAPIUtils.getDeviceManagementService() + .getOperationsByDeviceAndStatus(new DeviceIdentifier(deviceId, type), status); + OperationList operationsList = new OperationList(); + operationsList.setList(operations); + operationsList.setCount(operations.size()); + return Response.status(Response.Status.OK).entity(operationsList).build(); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); + } catch (DeviceManagementException e) { + String errorMessage = "Issue in retrieving device management service"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); + } + } + + private static List getComplianceFeatures(Object compliancePayload) throws + PolicyComplianceException { + String compliancePayloadString = new Gson().toJson(compliancePayload); + if (compliancePayload == null) { + return null; + } + // Parsing json string to get compliance features. + JsonElement jsonElement = new JsonParser().parse(compliancePayloadString); + + JsonArray jsonArray = jsonElement.getAsJsonArray(); + Gson gson = new Gson(); + ComplianceFeature complianceFeature; + List complianceFeatures = new ArrayList(jsonArray.size()); + + for (JsonElement element : jsonArray) { + complianceFeature = gson.fromJson(element, ComplianceFeature.class); + complianceFeatures.add(complianceFeature); + } + return complianceFeatures; + } +} diff --git a/components/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 new file mode 100644 index 0000000000..5a16fbccdb --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceEventManagementServiceImpl.java @@ -0,0 +1,590 @@ +package org.wso2.carbon.device.mgt.jaxrs.service.impl; + +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.Stub; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.analytics.api.AnalyticsDataAPI; +import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil; +import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse; +import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry; +import org.wso2.carbon.analytics.dataservice.commons.SortByField; +import org.wso2.carbon.analytics.dataservice.commons.SortType; +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.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; +import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.DeviceTypeEvent; +import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventRecords; +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.EventAttributeList; +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.publisher.stub.EventPublisherAdminServiceCallbackHandler; +import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub; +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.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 org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; + +import javax.validation.Valid; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.List; + +/** + * This is used for device type integration with DAS, to create streams and receiver dynamically and a common endpoint + * to retrieve data. + */ +@Path("/events") +public class DeviceEventManagementServiceImpl implements DeviceEventManagementService { + + private static final Log log = LogFactory.getLog(DeviceEventManagementServiceImpl.class); + + private static final String DEFAULT_EVENT_STORE_NAME = "EVENT_STORE"; + private static final String DEFAULT_WEBSOCKET_PUBLISHER_ADAPTER_TYPE = "secured-websocket"; + private static final String OAUTH_MQTT_ADAPTER_TYPE = "oauth-mqtt"; + private static final String THRIFT_ADAPTER_TYPE = "iot-event"; + private static final String DEFAULT_DEVICE_ID_ATTRIBUTE = "deviceId"; + private static final String DEFAULT_META_DEVICE_ID_ATTRIBUTE = "meta_deviceId"; + private static final String MQTT_CONTENT_TRANSFORMER = "device-meta-transformer"; + private static final String MQTT_CONTENT_TRANSFORMER_TYPE = "contentTransformer"; + private static final String MQTT_CONTENT_VALIDATOR_TYPE = "contentValidator"; + private static final String MQTT_CONTENT_VALIDATOR = "default"; + private static final String TIMESTAMP_FIELD_NAME = "_timestamp"; + + /** + * Retrieves the stream definition from das for the given device type. + * @return dynamic event attribute list + */ + @GET + @Path("/{type}") + @Override + public Response getDeviceTypeEventDefinition(@PathParam("type") String deviceType) { + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + EventStreamAdminServiceStub eventStreamAdminServiceStub = null; + EventReceiverAdminServiceStub eventReceiverAdminServiceStub = null; + try { + if (deviceType == null || + !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { + String errorMessage = "Invalid device type"; + log.error(errorMessage); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain); + eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub(); + EventStreamDefinitionDto eventStreamDefinitionDto = eventStreamAdminServiceStub.getStreamDefinitionDto( + streamName + ":" + Constants.DEFAULT_STREAM_VERSION); + if (eventStreamDefinitionDto == null) { + return Response.status(Response.Status.NO_CONTENT).build(); + } + + EventStreamAttributeDto[] eventStreamAttributeDtos = eventStreamDefinitionDto.getPayloadData(); + EventAttributeList eventAttributeList = new EventAttributeList(); + List attributes = new ArrayList<>(); + for (EventStreamAttributeDto eventStreamAttributeDto : eventStreamAttributeDtos) { + attributes.add(new Attribute(eventStreamAttributeDto.getAttributeName() + , AttributeType.valueOf(eventStreamAttributeDto.getAttributeType().toUpperCase()))); + } + eventAttributeList.setList(attributes); + + DeviceTypeEvent deviceTypeEvent = new DeviceTypeEvent(); + deviceTypeEvent.setEventAttributeList(eventAttributeList); + deviceTypeEvent.setTransportType(TransportType.HTTP); + eventReceiverAdminServiceStub = DeviceMgtAPIUtils.getEventReceiverAdminServiceStub(); + EventReceiverConfigurationDto eventReceiverConfigurationDto = eventReceiverAdminServiceStub + .getActiveEventReceiverConfiguration(getReceiverName(deviceType, tenantDomain, TransportType.MQTT)); + if (eventReceiverConfigurationDto != null) { + deviceTypeEvent.setTransportType(TransportType.MQTT); + } + return Response.ok().entity(deviceTypeEvent).build(); + } catch (AxisFault e) { + log.error("Failed to retrieve 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(); + } finally { + cleanup(eventStreamAdminServiceStub); + cleanup(eventReceiverAdminServiceStub); + } + } + + /** + * Deploy Event Stream, Receiver, Publisher and Store Configuration. + */ + @POST + @Path("/{type}") + @Override + public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType, + @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, deviceType); + 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, 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(); + } + } + + /** + * Delete device type specific artifacts from DAS. + */ + @DELETE + @Path("/{type}") + @Override + public Response deleteDeviceTypeEventDefinitions(@PathParam("type") String deviceType) { + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + EventReceiverAdminServiceStub eventReceiverAdminServiceStub = null; + EventPublisherAdminServiceStub eventPublisherAdminServiceStub = null; + EventStreamAdminServiceStub eventStreamAdminServiceStub = null; + + EventReceiverAdminServiceStub tenantBasedEventReceiverAdminServiceStub = null; + EventStreamAdminServiceStub tenantBasedEventStreamAdminServiceStub = null; + try { + if (deviceType == null || + !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { + String errorMessage = "Invalid device type"; + return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); + } + String eventPublisherName = deviceType.trim().replace(" ", "_") + "_websocket_publisher"; + String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain); + eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub(); + if (eventStreamAdminServiceStub.getStreamDefinitionDto(streamName + ":" + Constants.DEFAULT_STREAM_VERSION) == null) { + return Response.status(Response.Status.NO_CONTENT).build(); + } + eventStreamAdminServiceStub.removeEventStreamDefinition(streamName, Constants.DEFAULT_STREAM_VERSION); + EventReceiverAdminServiceCallbackHandler eventReceiverAdminServiceCallbackHandler = + new EventReceiverAdminServiceCallbackHandler() {}; + EventPublisherAdminServiceCallbackHandler eventPublisherAdminServiceCallbackHandler = + new EventPublisherAdminServiceCallbackHandler() {}; + + + String eventReceiverName = getReceiverName(deviceType, tenantDomain, TransportType.MQTT); + eventReceiverAdminServiceStub = DeviceMgtAPIUtils.getEventReceiverAdminServiceStub(); + if (eventReceiverAdminServiceStub.getInactiveEventReceiverConfigurationContent(eventReceiverName) == null) { + eventReceiverName = getReceiverName(deviceType, tenantDomain, TransportType.HTTP); + } + eventReceiverAdminServiceStub.startundeployInactiveEventReceiverConfiguration(eventReceiverName + , eventReceiverAdminServiceCallbackHandler); + + eventPublisherAdminServiceStub = DeviceMgtAPIUtils.getEventPublisherAdminServiceStub(); + eventPublisherAdminServiceStub.startundeployInactiveEventPublisherConfiguration(eventPublisherName + , eventPublisherAdminServiceCallbackHandler); + + try { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); + if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { + tenantBasedEventReceiverAdminServiceStub = DeviceMgtAPIUtils.getEventReceiverAdminServiceStub(); + tenantBasedEventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub(); + tenantBasedEventStreamAdminServiceStub.removeEventStreamDefinition(streamName, + Constants.DEFAULT_STREAM_VERSION); + + tenantBasedEventReceiverAdminServiceStub.startundeployInactiveEventReceiverConfiguration( + eventReceiverName, eventReceiverAdminServiceCallbackHandler); + + } + } finally { + cleanup(tenantBasedEventReceiverAdminServiceStub); + cleanup(tenantBasedEventStreamAdminServiceStub); + PrivilegedCarbonContext.endTenantFlow(); + } + return Response.ok().build(); + } catch (AxisFault e) { + log.error("Failed to delete 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(); + } finally { + cleanup(eventStreamAdminServiceStub); + cleanup(eventPublisherAdminServiceStub); + cleanup(eventReceiverAdminServiceStub); + cleanup(eventReceiverAdminServiceStub); + cleanup(eventStreamAdminServiceStub); + } + } + + /** + * Returns device specific data for the give period of time. + */ + @GET + @Path("/{type}/{deviceId}") + @Override + public Response getData(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, + @QueryParam("to") long to, @PathParam("type") String deviceType, @QueryParam("offset") + int offset, @QueryParam("limit") int limit) { + if (from == 0 || to == 0) { + String errorMessage = "Invalid values for from/to"; + return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); + } + String fromDate = String.valueOf(from); + String toDate = String.valueOf(to); + String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId + + " AND _timestamp : [" + fromDate + " TO " + toDate + "]"; + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain)); + try { + if (deviceType == null || + !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { + String errorMessage = "Invalid device type"; + log.error(errorMessage); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( + new DeviceIdentifier(deviceId, deviceType))) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + List sortByFields = new ArrayList<>(); + SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC); + sortByFields.add(sortByField); + EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, offset, limit); + return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build(); + } catch (AnalyticsException e) { + String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; + log.error(errorMsg); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } catch (DeviceManagementException e) { + String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; + log.error(errorMsg); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); + } + } + + /** + * Returns the last know data point of the device type. + */ + @GET + @Path("/last-known/{type}/{deviceId}") + @Override + public Response getLastKnownData(@PathParam("deviceId") String deviceId, @PathParam("type") String deviceType) { + String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId; + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain)); + try { + if (deviceType == null || + !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { + String errorMessage = "Invalid device type"; + log.error(errorMessage); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( + new DeviceIdentifier(deviceId, deviceType))) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + List sortByFields = new ArrayList<>(); + SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC); + sortByFields.add(sortByField); + EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, 1); + return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build(); + } catch (AnalyticsException e) { + String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; + log.error(errorMsg); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } catch (DeviceManagementException e) { + String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; + log.error(errorMsg); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); + } + } + + private void publishEventReceivers(String streamNameWithVersion, TransportType transportType + , String requestedTenantDomain, String deviceType) + throws RemoteException, UserStoreException, JWTClientException { + EventReceiverAdminServiceStub receiverAdminServiceStub = DeviceMgtAPIUtils.getEventReceiverAdminServiceStub(); + 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); + } + + String adapterType = OAUTH_MQTT_ADAPTER_TYPE; + BasicInputAdapterPropertyDto basicInputAdapterPropertyDtos[]; + if (transportType == TransportType.MQTT) { + basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[3]; + basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("topic", requestedTenantDomain + + "/" + deviceType + "/+/events"); + basicInputAdapterPropertyDtos[1] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_TRANSFORMER_TYPE + , MQTT_CONTENT_TRANSFORMER); + basicInputAdapterPropertyDtos[2] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_VALIDATOR_TYPE + , MQTT_CONTENT_VALIDATOR); + } else { + adapterType = THRIFT_ADAPTER_TYPE; + basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[1]; + basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("events.duplicated.in.cluster", "false"); + } + String eventRecieverName = getReceiverName(deviceType, requestedTenantDomain, transportType); + if (receiverAdminServiceStub.getActiveEventReceiverConfiguration(eventRecieverName) == null) { + if (transportType == TransportType.MQTT) { + receiverAdminServiceStub.deployJsonEventReceiverConfiguration(eventRecieverName, streamNameWithVersion + , adapterType, null, basicInputAdapterPropertyDtos, false); + } else { + receiverAdminServiceStub.deployWso2EventReceiverConfiguration(eventRecieverName, streamNameWithVersion + , adapterType, null, null, null, basicInputAdapterPropertyDtos, false, null); + } + } + } finally { + cleanup(receiverAdminServiceStub); + } + } + + private void publishStreamDefinitons(String streamName, String version, String deviceType + , EventAttributeList eventAttributes) + throws RemoteException, UserStoreException, JWTClientException { + EventStreamAdminServiceStub eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub(); + 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; + for (Attribute attribute : eventAttributes.getList()) { + EventStreamAttributeDto eventStreamAttributeDto = new EventStreamAttributeDto(); + eventStreamAttributeDto.setAttributeName(attribute.getName()); + eventStreamAttributeDto.setAttributeType(attribute.getType().toString()); + eventStreamAttributeDtos[i] = eventStreamAttributeDto; + i++; + } + + 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); + } else { + eventStreamAdminServiceStub.addEventStreamDefinitionAsDto(eventStreamDefinitionDto); + } + } finally { + cleanup(eventStreamAdminServiceStub); + } + } + + 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 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); + } + } finally { + cleanup(eventPublisherAdminServiceStub); + } + } + + private BasicInputAdapterPropertyDto getBasicInputAdapterPropertyDto(String key, String value) { + BasicInputAdapterPropertyDto basicInputAdapterPropertyDto = new BasicInputAdapterPropertyDto(); + basicInputAdapterPropertyDto.setKey(key); + basicInputAdapterPropertyDto.setValue(value); + return basicInputAdapterPropertyDto; + } + + private String getTableName(String streamName) { + return streamName.toUpperCase().replace('.', '_'); + } + + private String getReceiverName(String deviceType, String tenantDomain, TransportType transportType) { + return deviceType.replace(" ", "_").trim() + "-" + tenantDomain + "-" + transportType.toString() + "-receiver"; + } + + private static AnalyticsDataAPI getAnalyticsDataAPI() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + AnalyticsDataAPI analyticsDataAPI = + (AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null); + if (analyticsDataAPI == null) { + String msg = "Analytics api service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return analyticsDataAPI; + } + + private static EventRecords getAllEventsForDevice(String tableName, String query, List sortByFields + , int offset, int limit) throws AnalyticsException { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI(); + EventRecords eventRecords = new EventRecords(); + int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query); + if (eventCount == 0) { + eventRecords.setCount(0); + } + List resultEntries = analyticsDataAPI.search(tenantId, tableName, query, offset, limit, + sortByFields); + List recordIds = getRecordIds(resultEntries); + AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds); + eventRecords.setCount(eventCount); + eventRecords.setList(AnalyticsDataAPIUtil.listRecords(analyticsDataAPI, response)); + return eventRecords; + } + + private static List getRecordIds(List searchResults) { + List ids = new ArrayList<>(); + for (SearchResultEntry searchResult : searchResults) { + ids.add(searchResult.getId()); + } + return ids; + } + + private void cleanup(Stub stub) { + if (stub != null) { + try { + stub.cleanup(); + } catch (AxisFault axisFault) { + log.warn("Failed to clean the stub " + stub.getClass()); + } + } + } + +} 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 b201bfd80c..a269a67c21 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 @@ -18,17 +18,19 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.impl; -import io.swagger.annotations.ApiParam; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.common.InvalidConfigurationException; +import org.wso2.carbon.device.mgt.common.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.app.mgt.Application; @@ -36,6 +38,7 @@ import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; 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.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; @@ -45,6 +48,8 @@ import org.wso2.carbon.device.mgt.common.search.SearchContext; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; +import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; +import org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation; import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; @@ -52,6 +57,7 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceCompliance; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList; +import org.wso2.carbon.device.mgt.jaxrs.beans.OperationRequest; import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; @@ -59,6 +65,8 @@ import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; +import javax.security.auth.login.Configuration; +import javax.validation.Valid; import javax.validation.constraints.Size; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -84,6 +92,27 @@ import java.util.List; public class DeviceManagementServiceImpl implements DeviceManagementService { private static final Log log = LogFactory.getLog(DeviceManagementServiceImpl.class); + public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss"; + + @GET + @Path("/{type}/{id}/status") + @Override + public Response isEnrolled(@PathParam("type") String type, @PathParam("id") String id) { + boolean result; + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, type); + try { + result = DeviceMgtAPIUtils.getDeviceManagementService().isEnrolled(deviceIdentifier); + if (result) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NO_CONTENT).build(); + } + } catch (DeviceManagementException e) { + String msg = "Error occurred while checking enrollment status of the device."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } @GET @Override @@ -91,12 +120,14 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @QueryParam("name") String name, @QueryParam("type") String type, @QueryParam("user") String user, + @QueryParam("userPattern") String userPattern, @QueryParam("role") String role, @QueryParam("ownership") String ownership, @QueryParam("status") String status, @QueryParam("groupId") int groupId, @QueryParam("since") String since, @HeaderParam("If-Modified-Since") String ifModifiedSince, + @QueryParam("requireDeviceInfo") boolean requireDeviceInfo, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { try { @@ -126,9 +157,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { if (type != null && !type.isEmpty()) { request.setDeviceType(type); } - if (user != null && !user.isEmpty()) { - request.setOwner(user); - } if (ownership != null && !ownership.isEmpty()) { RequestValidationUtil.validateOwnershipType(ownership); request.setOwnership(ownership); @@ -151,6 +179,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { if (deviceAccessAuthorizationService.isDeviceAdminUser()) { if (user != null && !user.isEmpty()) { request.setOwner(MultitenantUtils.getTenantAwareUsername(user)); + } else if (userPattern != null && !userPattern.isEmpty()) { + request.setOwnerPattern(userPattern); } } else { if (user != null && !user.isEmpty()) { @@ -180,7 +210,12 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { "string is provided in 'If-Modified-Since' header").build()).build(); } request.setSince(sinceDate); - result = dms.getAllDevices(request); + if (requireDeviceInfo) { + result = dms.getAllDevices(request); + } else { + result = dms.getAllDevices(request, false); + } + if (result == null || result.getData() == null || result.getData().size() <= 0) { return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " + "after the timestamp provided in 'If-Modified-Since' header").build(); @@ -196,14 +231,22 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { "string is provided in 'since' filter").build()).build(); } request.setSince(sinceDate); - result = dms.getAllDevices(request); + if (requireDeviceInfo) { + result = dms.getAllDevices(request); + } else { + result = dms.getAllDevices(request, false); + } if (result == null || result.getData() == null || result.getData().size() <= 0) { devices.setList(new ArrayList()); devices.setCount(0); return Response.status(Response.Status.OK).entity(devices).build(); } } else { - result = dms.getAllDevices(request); + if (requireDeviceInfo) { + result = dms.getAllDevices(request); + } else { + result = dms.getAllDevices(request, false); + } int resultCount = result.getRecordsTotal(); if (resultCount == 0) { Response.status(Response.Status.OK).entity(devices).build(); @@ -229,7 +272,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @GET @Override @Path("/user-devices") - public Response getDeviceByUser(@QueryParam("offset") int offset, + public Response getDeviceByUser(@QueryParam("requireDeviceInfo") boolean requireDeviceInfo, + @QueryParam("offset") int offset, @QueryParam("limit") int limit) { RequestValidationUtil.validatePaginationParameters(offset, limit); @@ -241,7 +285,11 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { request.setOwner(currentUser); try { - result = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(request); + if (requireDeviceInfo) { + result = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(request); + } else { + result = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(request, false); + } devices.setList((List) result.getData()); devices.setCount(result.getRecordsTotal()); return Response.status(Response.Status.OK).entity(devices).build(); @@ -261,7 +309,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { DeviceMgtAPIUtils.getDeviceManagementService(); try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); - Device persistedDevice = deviceManagementProviderService.getDevice(deviceIdentifier); + Device persistedDevice = deviceManagementProviderService.getDevice(deviceIdentifier, true); if (persistedDevice == null) { return Response.status(Response.Status.NOT_FOUND).build(); } @@ -287,7 +335,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); try { Device persistedDevice = deviceManagementProviderService.getDevice(new DeviceIdentifier - (deviceId, deviceType)); + (deviceId, deviceType), true); persistedDevice.setName(device.getName()); boolean response = deviceManagementProviderService.modifyEnrollment(persistedDevice); return Response.status(Response.Status.CREATED).entity(response).build(); @@ -534,7 +582,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { RequestValidationUtil.validateDeviceIdentifier(type, id); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); Policy policy; - NonComplianceData complianceData = null; + NonComplianceData complianceData; DeviceCompliance deviceCompliance = new DeviceCompliance(); try { @@ -586,7 +634,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { DeviceMgtAPIUtils.getDeviceManagementService(); try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, type); - Device persistedDevice = deviceManagementProviderService.getDevice(deviceIdentifier); + Device persistedDevice = deviceManagementProviderService.getDevice(deviceIdentifier, false); if (persistedDevice == null) { return Response.status(Response.Status.NOT_FOUND).build(); } @@ -600,4 +648,78 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } + + @POST + @Path("/{type}/operations") + public Response addOperation(@PathParam("type") String type, @Valid OperationRequest operationRequest) { + try { + if (operationRequest == null || operationRequest.getDeviceIdentifiers() == null + || operationRequest.getOperation() == null) { + String errorMessage = "Operation cannot be empty"; + log.error(errorMessage); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + if (!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(type)) { + String errorMessage = "Device Type is invalid"; + log.error(errorMessage); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + Operation.Type operationType = operationRequest.getOperation().getType(); + if (operationType == Operation.Type.COMMAND || operationType == Operation.Type.CONFIG) { + DeviceIdentifier deviceIdentifier; + List deviceIdentifiers = new ArrayList<>(); + for (String deviceId : operationRequest.getDeviceIdentifiers()) { + deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(type); + deviceIdentifiers.add(deviceIdentifier); + } + Operation operation; + if (operationType == Operation.Type.COMMAND) { + Operation commandOperation = operationRequest.getOperation(); + operation = new CommandOperation(); + operation.setType(Operation.Type.COMMAND); + operation.setCode(commandOperation.getCode()); + operation.setEnabled(commandOperation.isEnabled()); + operation.setStatus(commandOperation.getStatus()); + + } else { + Operation configOperation = operationRequest.getOperation(); + operation = new ConfigOperation(); + operation.setType(Operation.Type.CONFIG); + operation.setCode(configOperation.getCode()); + operation.setEnabled(configOperation.isEnabled()); + operation.setPayLoad(configOperation.getPayLoad()); + operation.setStatus(configOperation.getStatus()); + } + String date = new SimpleDateFormat(DATE_FORMAT_NOW).format(new Date()); + operation.setCreatedTimeStamp(date); + Activity activity = DeviceMgtAPIUtils.getDeviceManagementService().addOperation(type, operation, + deviceIdentifiers); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } else { + String message = "Only Command and Config operation is supported through this api"; + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(message).build(); + } + + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); + } catch (DeviceManagementException e) { + String errorMessage = "Issue in retrieving deivce management service instance"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); + } catch (InvalidConfigurationException e) { + log.error("failed to add operation", e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementServiceImpl.java index 3bd43681e9..5fdc06a501 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementServiceImpl.java @@ -23,6 +23,9 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; +import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; +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.DeviceTypeList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; @@ -35,7 +38,9 @@ import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; +import java.util.ArrayList; import java.util.List; @Path("/device-types") @@ -86,4 +91,62 @@ public class DeviceTypeManagementServiceImpl implements DeviceTypeManagementServ return Response.status(Response.Status.OK).entity(features).build(); } + @Override + @GET + @Path("/config") + public Response getDeviceTypes() { + try { + List deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceTypes(); + List filteredDeviceTypes = new ArrayList<>(); + for (DeviceType deviceType : deviceTypes) { + filteredDeviceTypes.add(clearMetaEntryInfo(deviceType)); + } + return Response.status(Response.Status.OK).entity(filteredDeviceTypes).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred at server side while fetching device type."; + log.error(msg, e); + return Response.serverError().entity(msg).build(); + } + } + + @Override + @GET + @Path("/config/{type}") + public Response getDeviceTypeByName(@PathParam("type") String type) { + if (type != null && type.length() > 0) { + try { + DeviceType deviceType = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceType(type); + if (deviceType == null) { + String msg = "Device type does not exist, " + type; + return Response.status(Response.Status.NO_CONTENT).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(deviceType).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred at server side while fetching device type."; + log.error(msg, e); + return Response.serverError().entity(msg).build(); + } + } else { + return Response.status(Response.Status.BAD_REQUEST).build(); + } + } + + /** + * This cleans up the configs that should not be exposed to iot users. + * @param deviceType + * @return + */ + private DeviceType clearMetaEntryInfo(DeviceType deviceType) { + DeviceTypeMetaDefinition metaDefinition = deviceType.getDeviceTypeMetaDefinition(); + if (metaDefinition != null) { + metaDefinition.setInitialOperationConfig(null); + if (metaDefinition.getPushNotificationConfig() != null) { + metaDefinition.setPushNotificationConfig(new PushNotificationConfig(metaDefinition. + getPushNotificationConfig().getType(), false, null)); + } + deviceType.setDeviceTypeMetaDefinition(metaDefinition); + } + return deviceType; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java new file mode 100644 index 0000000000..04bfeff0d7 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java @@ -0,0 +1,379 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.jaxrs.service.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.analytics.api.AnalyticsDataAPI; +import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil; +import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse; +import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry; +import org.wso2.carbon.analytics.dataservice.commons.SortByField; +import org.wso2.carbon.analytics.dataservice.commons.SortType; +import org.wso2.carbon.analytics.datasource.commons.Record; +import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; +import org.wso2.carbon.device.mgt.common.geo.service.Alert; +import org.wso2.carbon.device.mgt.common.geo.service.Event; +import org.wso2.carbon.device.mgt.common.geo.service.GeoFence; +import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService; +import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; +import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; +import org.wso2.carbon.device.mgt.jaxrs.service.api.GeoLocationBasedService; +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * The api for + */ +public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { + + private static Log log = LogFactory.getLog(GeoLocationBasedServiceImpl.class); + + @Path("stats/{deviceType}/{deviceId}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Response getGeoDeviceStats(@PathParam("deviceId") String deviceId, + @PathParam("deviceType") String deviceType, + @QueryParam("from") long from, @QueryParam("to") long to) { + //First, check whether the Geo Location service has been enabled in the cdmf-config.xml file + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance() + .getDeviceManagementConfig(); + if (deviceManagementConfig != null) { + if(!deviceManagementConfig.getGeoLocationConfiguration().getPublishLocationOperationResponse()){ + return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build(); + } + } + String tableName = "IOT_PER_DEVICE_STREAM_GEO_FUSEDSPATIALEVENT"; + String fromDate = String.valueOf(from); + String toDate = String.valueOf(to); + String query = "id:" + deviceId + " AND type:" + deviceType; + if (from != 0 || to != 0) { + query += " AND timeStamp : [" + fromDate + " TO " + toDate + "]"; + } + try { + if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( + new DeviceIdentifier(deviceId, deviceType), + DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + List sortByFields = new ArrayList<>(); + SortByField sortByField = new SortByField("timeStamp", SortType.ASC); + sortByFields.add(sortByField); + + // this is the user who initiates the request + String authorizedUser = MultitenantUtils.getTenantAwareUsername( + CarbonContext.getThreadLocalCarbonContext().getUsername()); + + try { + String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser); + int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain); + AnalyticsDataAPI analyticsDataAPI = DeviceMgtAPIUtils.getAnalyticsDataAPI(); + List searchResults = analyticsDataAPI.search(tenantId, tableName, query, + 0, + 100, + sortByFields); + List events = getEventBeans(analyticsDataAPI, tenantId, tableName, new ArrayList(), + searchResults); + return Response.ok().entity(events).build(); + } catch (AnalyticsException | UserStoreException e) { + log.error("Failed to perform search on table: " + tableName + " : " + e.getMessage(), e); + throw DeviceMgtUtil.buildBadRequestException( + Constants.ErrorMessages.STATUS_BAD_REQUEST_MESSAGE_DEFAULT); + } + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage()); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } + } + + @Path("alerts/{alertType}/{deviceType}/{deviceId}") + @POST + @Consumes("application/json") + @Produces("application/json") + public Response createGeoAlerts(Alert alert, @PathParam("deviceId") String deviceId, + @PathParam("deviceType") String deviceType, + @PathParam("alertType") String alertType) { + try { + if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( + new DeviceIdentifier(deviceId, deviceType), + DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + + // this is the user who initiates the request + String authorizedUser = MultitenantUtils.getTenantAwareUsername( + CarbonContext.getThreadLocalCarbonContext().getUsername() + ); + + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setId(deviceId); + identifier.setType(deviceType); + + GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); + geoService.createGeoAlert(alert, identifier, alertType); + return Response.ok().build(); + } catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) { + String error = "Error occurred while creating the geo alert for " + deviceType + " with id: " + deviceId; + log.error(error, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } + } + + @Path("alerts/{alertType}/{deviceType}/{deviceId}") + @PUT + @Consumes("application/json") + @Produces("application/json") + public Response updateGeoAlerts(Alert alert, @PathParam("deviceId") String deviceId, + @PathParam("deviceType") String deviceType, + @PathParam("alertType") String alertType) { + try { + if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( + new DeviceIdentifier(deviceId, deviceType), + DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + + // this is the user who initiates the request + String authorizedUser = MultitenantUtils.getTenantAwareUsername( + CarbonContext.getThreadLocalCarbonContext().getUsername() + ); + + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setId(deviceId); + identifier.setType(deviceType); + + GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); + geoService.updateGeoAlert(alert, identifier, alertType); + return Response.ok().build(); + } catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) { + String error = "Error occurred while creating the geo alert for " + deviceType + " with id: " + deviceId; + log.error(error, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } + } + + @Path("alerts/{alertType}/{deviceType}/{deviceId}") + @DELETE + @Consumes("application/json") + @Produces("application/json") + public Response removeGeoAlerts(@PathParam("deviceId") String deviceId, + @PathParam("deviceType") String deviceType, + @PathParam("alertType") String alertType, + @QueryParam("queryName") String queryName) { + try { + if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( + new DeviceIdentifier(deviceId, deviceType), + DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + + // this is the user who initiates the request + String authorizedUser = MultitenantUtils.getTenantAwareUsername( + CarbonContext.getThreadLocalCarbonContext().getUsername() + ); + + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setId(deviceId); + identifier.setType(deviceType); + + GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); + geoService.removeGeoAlert(alertType, identifier, queryName); + return Response.ok().build(); + } catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) { + String error = "Error occurred while removing the geo alert for " + deviceType + " with id: " + deviceId; + log.error(error, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } + } + + @Path("alerts/{alertType}/{deviceType}/{deviceId}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Response getGeoAlerts(@PathParam("deviceId") String deviceId, + @PathParam("deviceType") String deviceType, + @PathParam("alertType") String alertType) { + try { + if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( + new DeviceIdentifier(deviceId, deviceType), + DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + + // this is the user who initiates the request + String authorizedUser = MultitenantUtils.getTenantAwareUsername( + CarbonContext.getThreadLocalCarbonContext().getUsername() + ); + + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setId(deviceId); + identifier.setType(deviceType); + + GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); + + if (GeoServices.ALERT_TYPE_WITHIN.equals(alertType)) { + List alerts = geoService.getWithinAlerts(identifier); + return Response.ok().entity(alerts).build(); + } else if (GeoServices.ALERT_TYPE_EXIT.equals(alertType)) { + List alerts = geoService.getExitAlerts(identifier); + return Response.ok().entity(alerts).build(); + } else if (GeoServices.ALERT_TYPE_SPEED.equals(alertType)) { + String result = geoService.getSpeedAlerts(identifier); + return Response.ok().entity(result).build(); + } else if (GeoServices.ALERT_TYPE_PROXIMITY.equals(alertType)) { + String result = geoService.getProximityAlerts(identifier); + return Response.ok().entity(result).build(); + } else if (GeoServices.ALERT_TYPE_STATIONARY.equals(alertType)) { + List alerts = geoService.getStationaryAlerts(identifier); + return Response.ok().entity(alerts).build(); + } else if (GeoServices.ALERT_TYPE_TRAFFIC.equals(alertType)) { + List alerts = geoService.getTrafficAlerts(identifier); + return Response.ok().entity(alerts).build(); + } + return null; + } catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) { + String error = "Error occurred while getting the geo alerts for " + deviceType + " with id: " + deviceId; + log.error(error, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } + } + + @Path("alerts/history/{deviceType}/{deviceId}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Response getGeoAlertsHistory(@PathParam("deviceId") String deviceId, + @PathParam("deviceType") String deviceType, + @QueryParam("from") long from, @QueryParam("to") long to) { + String tableName = "IOT_PER_DEVICE_STREAM_GEO_ALERTNOTIFICATIONS"; + String fromDate = String.valueOf(from); + String toDate = String.valueOf(to); + String query = "id:" + deviceId + " AND type:" + deviceType; + if (from != 0 || to != 0) { + query += " AND timeStamp : [" + fromDate + " TO " + toDate + "]"; + } + try { + if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( + new DeviceIdentifier(deviceId, deviceType), + DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + List sortByFields = new ArrayList<>(); + SortByField sortByField = new SortByField("timeStamp", SortType.ASC); + sortByFields.add(sortByField); + + // this is the user who initiates the request + String authorizedUser = MultitenantUtils.getTenantAwareUsername( + CarbonContext.getThreadLocalCarbonContext().getUsername()); + + try { + String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser); + int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain); + AnalyticsDataAPI analyticsDataAPI = DeviceMgtAPIUtils.getAnalyticsDataAPI(); + List searchResults = analyticsDataAPI.search(tenantId, tableName, query, + 0, + 100, + sortByFields); + List events = getEventBeans(analyticsDataAPI, tenantId, tableName, new ArrayList(), + searchResults); + return Response.ok().entity(events).build(); + } catch (AnalyticsException | UserStoreException e) { + log.error("Failed to perform search on table: " + tableName + " : " + e.getMessage(), e); + throw DeviceMgtUtil.buildBadRequestException( + Constants.ErrorMessages.STATUS_BAD_REQUEST_MESSAGE_DEFAULT); + } + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage()); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } + } + + private List getEventBeans(AnalyticsDataAPI analyticsDataAPI, int tenantId, String tableName, + List columns, + List searchResults) throws AnalyticsException { + List ids = getIds(searchResults); + List requiredColumns = (columns == null || columns.isEmpty()) ? null : columns; + AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, requiredColumns, ids); + List records = AnalyticsDataAPIUtil.listRecords(analyticsDataAPI, response); + Map eventBeanMap = getEventBeanKeyedWithIds(records); + return getSortedEventBeans(eventBeanMap, searchResults); + } + + private List getSortedEventBeans(Map eventBeanMap, + List searchResults) { + List sortedRecords = new ArrayList<>(); + for (SearchResultEntry entry : searchResults) { + sortedRecords.add(eventBeanMap.get(entry.getId())); + } + return sortedRecords; + } + + private Map getEventBeanKeyedWithIds(List records) { + Map eventBeanMap = new HashMap<>(); + for (Record record : records) { + Event event = getEventBean(record); + eventBeanMap.put(event.getId(), event); + } + return eventBeanMap; + } + + private List getIds(List searchResults) { + List ids = new ArrayList<>(); + if (searchResults != null) { + for (SearchResultEntry resultEntry : searchResults) { + ids.add(resultEntry.getId()); + } + } + return ids; + } + + private static Event getEventBean(Record record) { + Event eventBean = new Event(); + eventBean.setId(record.getId()); + eventBean.setTableName(record.getTableName()); + eventBean.setTimestamp(record.getTimestamp()); + eventBean.setValues(record.getValues()); + return eventBean; + } +} 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 cc5fa3ddac..8bab08463b 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 @@ -173,7 +173,10 @@ public class GroupManagementServiceImpl implements GroupManagementService { .manageGroupSharing(groupId, userRoles); return Response.status(Response.Status.OK).build(); } catch (GroupManagementException e) { - String msg = "Error occurred while managing group share."; + String msg = "Error occurred while managing group share. "; + if (e.getErrorMessage() != null){ + msg += e.getErrorMessage(); + } log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (RoleDoesNotExistException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java index 7c1fe8e407..01dd4880c1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java @@ -128,7 +128,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { List deviceIdentifiers = policyWrapper.getDeviceIdentifiers(); if (deviceIdentifiers != null) { for (DeviceIdentifier id : deviceIdentifiers) { - devices.add(DeviceMgtAPIUtils.getDeviceManagementService().getDevice(id)); + devices.add(DeviceMgtAPIUtils.getDeviceManagementService().getDevice(id, false)); } } policy.setDevices(devices); @@ -345,11 +345,11 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { public Response updatePolicyPriorities(List priorityUpdatedPolicies) { PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); List policiesToUpdate = new ArrayList<>(priorityUpdatedPolicies.size()); - int i; - for (i = 0; i < priorityUpdatedPolicies.size(); i++) { + + for (PriorityUpdatedPolicyWrapper priorityUpdatedPolicy : priorityUpdatedPolicies) { Policy policyObj = new Policy(); - policyObj.setId(priorityUpdatedPolicies.get(i).getId()); - policyObj.setPriorityId(priorityUpdatedPolicies.get(i).getPriority()); + policyObj.setId(priorityUpdatedPolicy.getId()); + policyObj.setPriorityId(priorityUpdatedPolicy.getPriority()); policiesToUpdate.add(policyObj); } boolean policiesUpdated; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java index e947c258c0..d396237df4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java @@ -22,6 +22,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.RegistryType; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleInfo; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList; @@ -30,6 +32,9 @@ import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; +import org.wso2.carbon.registry.api.Registry; +import org.wso2.carbon.registry.core.session.UserRegistry; +import org.wso2.carbon.registry.resource.services.utils.ChangeRolePermissionsUtil; import org.wso2.carbon.user.api.*; import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import org.wso2.carbon.user.mgt.UserRealmProxy; @@ -296,6 +301,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { } } userStoreManager.addRole(roleInfo.getRoleName(), roleInfo.getUsers(), permissions); + authorizeRoleForAppmgt(roleInfo.getRoleName(), roleInfo.getPermissions()); //TODO fix what's returned in the entity return Response.created(new URI(API_BASE_PATH + "/" + URLEncoder.encode(roleInfo.getRoleName(), "UTF-8"))). @@ -450,6 +456,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { authorizationManager.authorizeRole(roleName, permission, CarbonConstants.UI_PERMISSION_ACTION); } } + authorizeRoleForAppmgt(roleName, roleInfo.getPermissions()); } //TODO: Need to send the updated role information in the entity back to the client return Response.status(Response.Status.OK).entity("Role '" + roleInfo.getRoleName() + "' has " + @@ -467,6 +474,59 @@ public class RoleManagementServiceImpl implements RoleManagementService { } } + /** + * When presented with role and a set of permissions, if given role has permission to + * perform mobile app management, said role will be given rights mobile app collection in the + * governance registry. + * + * @param role + * @param permissions + * @return state of role update Operation + */ + private boolean authorizeRoleForAppmgt(String role, String[] permissions) { + String permissionString = + "ra^true:rd^false:wa^true:wd^false:da^true:dd^false:aa^true:ad^false"; + String resourcePath = "/_system/governance/mobileapps/"; + boolean appmPermAvailable = false; + + if (permissions != null) { + for (int i = 0; i < permissions.length; i++) + switch (permissions[i]) { + case "/permission/admin/manage/mobileapp": + appmPermAvailable = true; + break; + case "/permission/admin/manage/mobileapp/create": + appmPermAvailable = true; + break; + case "/permission/admin/manage/mobileapp/publish": + appmPermAvailable = true; + break; + } + } + + if (appmPermAvailable) { + try { + Registry registry = CarbonContext.getThreadLocalCarbonContext(). + getRegistry(RegistryType.SYSTEM_GOVERNANCE); + ChangeRolePermissionsUtil.changeRolePermissions((UserRegistry) registry, + resourcePath, role + ":" + permissionString); + + return true; + } catch (Exception e) { + String msg = "Error while retrieving user registry in order to update permissions " + + "for resource : " + resourcePath; + log.error(msg, e); + return false; + } + } else { + if (log.isDebugEnabled()) { + log.debug("Mobile App Management permissions not selected, therefore role : " + + role + " not given permission for registry collection : " + resourcePath); + } + return false; + } + } + @DELETE @Path("/{roleName}") @Override diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index a90b51d409..e134a40a17 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -22,7 +22,9 @@ import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.wst.common.uriresolver.internal.util.URIEncoder; +import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; @@ -41,6 +43,7 @@ import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.identity.user.store.count.UserStoreCountRetriever; import org.wso2.carbon.identity.user.store.count.exception.UserStoreCounterException; import org.wso2.carbon.user.api.Permission; +import org.wso2.carbon.user.api.RealmConfiguration; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.utils.CarbonUtils; @@ -304,13 +307,16 @@ public class UserManagementServiceImpl implements UserManagementService { new ErrorResponse.ErrorResponseBuilder().setMessage("User '" + username + "' does not exist for removal.").build()).build(); } + // Un-enroll all devices for the user + DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); + deviceManagementService.setStatus(username, EnrolmentInfo.Status.REMOVED); userStoreManager.deleteUser(username); if (log.isDebugEnabled()) { log.debug("User '" + username + "' was successfully removed."); } return Response.status(Response.Status.OK).build(); - } catch (UserStoreException e) { + } catch (DeviceManagementException | UserStoreException e) { String msg = "Exception in trying to remove user by username: " + username; log.error(msg, e); return Response.serverError().entity( @@ -412,6 +418,15 @@ public class UserManagementServiceImpl implements UserManagementService { public Response getUserCount() { try { UserStoreCountRetriever userStoreCountRetrieverService = DeviceMgtAPIUtils.getUserStoreCountRetrieverService(); + RealmConfiguration secondaryRealmConfiguration = CarbonContext.getThreadLocalCarbonContext().getUserRealm(). + getRealmConfiguration().getSecondaryRealmConfig(); + + if (secondaryRealmConfiguration != null) { + if (!secondaryRealmConfiguration.isPrimary() && !Constants.JDBC_USERSTOREMANAGER. + equals(secondaryRealmConfiguration.getUserStoreClass().getClass())) { + return getUserCountViaUserStoreManager(); + } + } if (userStoreCountRetrieverService != null) { long count = userStoreCountRetrieverService.countUsers(""); if (count != -1) { @@ -424,6 +439,10 @@ public class UserManagementServiceImpl implements UserManagementService { String msg = "Error occurred while retrieving the count of users that exist within the current tenant"; log.error(msg, e); + } catch (UserStoreException e) { + String msg = + "Error occurred while retrieving user stores."; + log.error(msg, e); } return getUserCountViaUserStoreManager(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceAccessAuthorizationAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceAccessAuthorizationAdminServiceImpl.java index fc3fe169ba..035caa3a18 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceAccessAuthorizationAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceAccessAuthorizationAdminServiceImpl.java @@ -36,6 +36,8 @@ import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; @Path("/admin/authorization") @Produces(MediaType.APPLICATION_JSON) @@ -43,6 +45,7 @@ import javax.ws.rs.core.Response; public class DeviceAccessAuthorizationAdminServiceImpl implements DeviceAccessAuthorizationAdminService { private static final Log log = LogFactory.getLog(DeviceAccessAuthorizationAdminServiceImpl.class); + private static final String DEFAULT_STAT_PERMISSION = "/permission/admin/device-mgt/device/realtime_analytics"; @POST @Override @@ -90,4 +93,14 @@ public class DeviceAccessAuthorizationAdminServiceImpl implements DeviceAccessAu } } + @POST + @Path("/stat") + @Override + public Response isAuthorizedForStat(AuthorizationRequest authorizationRequest) { + List permissions = new ArrayList<>(); + permissions.add(DEFAULT_STAT_PERMISSION); + authorizationRequest.setPermissions(permissions); + return isAuthorized(authorizationRequest); + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypePublisherAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceAnalyticsArtifactUploaderAdminServiceImpl.java similarity index 98% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypePublisherAdminServiceImpl.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceAnalyticsArtifactUploaderAdminServiceImpl.java index 9fbd5043e2..c6325a4ec7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypePublisherAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceAnalyticsArtifactUploaderAdminServiceImpl.java @@ -37,13 +37,10 @@ import org.wso2.carbon.application.mgt.stub.upload.types.carbon.UploadedFileItem import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.Utils; -import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceTypePublisherAdminService; +import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceAnalyticsArtifactUploaderAdminService; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.identity.jwt.client.extension.JWTClient; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.Resource; -import org.wso2.carbon.registry.core.ResourceImpl; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.CarbonUtils; @@ -55,7 +52,6 @@ import javax.activation.DataHandler; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; -import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; @@ -72,8 +68,8 @@ import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; -@Path("/admin/devicetype") -public class DeviceTypePublisherAdminServiceImpl implements DeviceTypePublisherAdminService { +@Path("/admin/publish-artifact") +public class DeviceAnalyticsArtifactUploaderAdminServiceImpl implements DeviceAnalyticsArtifactUploaderAdminService { /** * required soap header for authorization @@ -110,7 +106,7 @@ public class DeviceTypePublisherAdminServiceImpl implements DeviceTypePublisherA private String tenantDomain; - private static final Log log = LogFactory.getLog(DeviceTypePublisherAdminServiceImpl.class); + private static final Log log = LogFactory.getLog(DeviceAnalyticsArtifactUploaderAdminServiceImpl.class); private static final String DEFAULT_RESOURCE_LOCATION = "/resources/devicetypes"; private static final String CAR_FILE_LOCATION = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "devicetypes"; @@ -178,6 +174,9 @@ public class DeviceTypePublisherAdminServiceImpl implements DeviceTypePublisherA publishDynamicEventReceivers(type, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, receiverFileList); } } + if (streamFileList != null) { + publishDynamicEventStream(type, tenantDomain, streamFileList); + } if (deployAnalyticsCapp(type, list)){ return Response.status(Response.Status.BAD_REQUEST) .entity("\"Error, Artifact does not exist.\"").build(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java index cb4b1bb37c..a6d98fc73c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java @@ -25,6 +25,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.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.PaginationRequest; 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.service.api.admin.DeviceManagementAdminService; @@ -53,19 +54,22 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe @QueryParam("offset") int offset, @QueryParam("limit") int limit) { RequestValidationUtil.validatePaginationParameters(offset, limit); + int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) { + return Response.status(Response.Status.UNAUTHORIZED).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage( + "Current logged in user is not authorized to perform this operation").build()).build(); + } try { - int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) { - return Response.status(Response.Status.UNAUTHORIZED).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage( - "Current logged in user is not authorized to perform this operation").build()).build(); - } PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(DeviceMgtAPIUtils.getTenantId(tenantDomain)); + PaginationRequest request = new PaginationRequest(offset, limit); + request.setDeviceType(type); + request.setDeviceName(name); List devices = DeviceMgtAPIUtils.getDeviceManagementService(). - getDevicesByNameAndType(name, type, offset, limit); + getDevicesByNameAndType(request, false); // setting up paginated result DeviceList deviceList = new DeviceList(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java new file mode 100644 index 0000000000..3cc9401449 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2016, 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. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.service.impl.admin; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.InvalidConfigurationException; +import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; +import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceTypeManagementAdminService; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Path("/admin/device-types") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class DeviceTypeManagementAdminServiceImpl implements DeviceTypeManagementAdminService { + + private static final Log log = LogFactory.getLog(DeviceTypeManagementAdminServiceImpl.class); + private static final String DEVICETYPE_REGEX_PATTERN = "^[^ /]+$"; + private static final Pattern patternMatcher = Pattern.compile(DEVICETYPE_REGEX_PATTERN); + + @GET + @Override + public Response getDeviceTypes() { + try { + List deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceTypes(); + return Response.status(Response.Status.OK).entity(deviceTypes).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the list of device types."; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + } + + @Override + @POST + public Response addDeviceType(DeviceType deviceType) { + if (deviceType != null && deviceType.getDeviceTypeMetaDefinition() != null) { + try { + if (DeviceMgtAPIUtils.getDeviceManagementService().getDeviceType(deviceType.getName()) != null) { + String msg = "Device type already available, " + deviceType.getName(); + return Response.status(Response.Status.CONFLICT).entity(msg).build(); + } + Matcher matcher = patternMatcher.matcher(deviceType.getName()); + if(matcher.find()) { + DeviceManagementService httpDeviceTypeManagerService = + DeviceMgtAPIUtils.getDeviceTypeGeneratorService() + .populateDeviceManagementService(deviceType.getName(), + deviceType.getDeviceTypeMetaDefinition()); + DeviceMgtAPIUtils.getDeviceManagementService().registerDeviceType(httpDeviceTypeManagerService); + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.BAD_REQUEST).entity("Device type name does not match the pattern " + + DEVICETYPE_REGEX_PATTERN).build(); + } + } catch (DeviceManagementException e) { + String msg = "Error occurred at server side while adding a device type."; + log.error(msg, e); + return Response.serverError().entity(msg).build(); + } catch (InvalidConfigurationException e) { + return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); + } + } else { + return Response.status(Response.Status.BAD_REQUEST).build(); + } + } + + @Override + @PUT + public Response updateDeviceType(DeviceType deviceType) { + if (deviceType != null && deviceType.getDeviceTypeMetaDefinition() != null) { + try { + if (DeviceMgtAPIUtils.getDeviceManagementService().getDeviceType(deviceType.getName()) == null) { + String msg = "Device type does not exist, " + deviceType.getName(); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + DeviceManagementService httpDeviceTypeManagerService = DeviceMgtAPIUtils.getDeviceTypeGeneratorService() + .populateDeviceManagementService(deviceType.getName(), deviceType.getDeviceTypeMetaDefinition()); + DeviceMgtAPIUtils.getDeviceManagementService().registerDeviceType(httpDeviceTypeManagerService); + return Response.status(Response.Status.OK).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred at server side while updating the device type."; + log.error(msg, e); + return Response.serverError().entity(msg).build(); + } catch (InvalidConfigurationException e) { + return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); + } + } else { + return Response.status(Response.Status.BAD_REQUEST).build(); + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java index c5fa21ae89..55dd398e18 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java @@ -27,7 +27,10 @@ public class Constants { public static final String USER_CLAIM_FIRST_NAME = "http://wso2.org/claims/givenname"; public static final String USER_CLAIM_LAST_NAME = "http://wso2.org/claims/lastname"; public static final String PRIMARY_USER_STORE = "PRIMARY"; + public static final String DEFAULT_STREAM_VERSION = "1.0.0"; public static final String SCOPE = "scope"; + public static final String JDBC_USERSTOREMANAGER = "org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager"; + public final class ErrorMessages { private ErrorMessages () { throw new AssertionError(); } 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 888b1c42ee..8b12b4a285 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 @@ -18,24 +18,48 @@ package org.wso2.carbon.device.mgt.jaxrs.util; +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.Options; +import org.apache.axis2.java.security.SSLProtocolSocketFactory; +import org.apache.axis2.transport.http.HTTPConstants; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.protocol.Protocol; +import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub; +import org.wso2.carbon.base.ServerConfiguration; +import org.wso2.carbon.analytics.api.AnalyticsDataAPI; 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.analytics.dashboard.GadgetDataService; +import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; +import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; +import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +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.event.publisher.stub.EventPublisherAdminServiceStub; +import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub; +import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; +import org.wso2.carbon.identity.jwt.client.extension.JWTClient; +import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.identity.user.store.count.AbstractCountRetrieverFactory; import org.wso2.carbon.identity.user.store.count.UserStoreCountRetriever; @@ -54,7 +78,22 @@ import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager; import org.wso2.carbon.user.core.service.RealmService; +import javax.cache.Cache; +import javax.cache.Caching; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; import javax.ws.rs.core.MediaType; +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.cert.CertificateException; +import java.util.ArrayList; import java.util.List; /** @@ -64,7 +103,51 @@ public class DeviceMgtAPIUtils { public static final MediaType DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_JSON_TYPE; private static final String NOTIFIER_FREQUENCY = "notifierFrequency"; + private static final String STREAM_DEFINITION_PREFIX = "iot.per.device.stream."; + private static final String DEFAULT_HTTP_PROTOCOL = "https"; + private static final String EVENT_RECIEVER_CONTEXT = "EventReceiverAdminService/"; + private static final String EVENT_PUBLISHER_CONTEXT = "EventPublisherAdminService/"; + private static final String EVENT_STREAM_CONTEXT = "EventStreamAdminService/"; + private static final String EVENT_PERSISTENCE_CONTEXT = "EventStreamPersistenceAdminService/"; + private static final String AUTHORIZATION_HEADER = "Authorization"; + private static final String AUTHORIZATION_HEADER_VALUE = "Bearer"; + public static final String DAS_PORT = "${iot.analytics.https.port}"; + public static final String DAS_HOST_NAME = "${iot.analytics.host}"; + private static final String KEY_STORE_TYPE = "JKS"; + private static final String TRUST_STORE_TYPE = "JKS"; + private static final String KEY_MANAGER_TYPE = "SunX509"; //Default Key Manager Type + private static final String TRUST_MANAGER_TYPE = "SunX509"; //Default Trust Manager Type + private static final String SSLV3 = "SSLv3"; + private static final String EVENT_CACHE_MANAGER_NAME = "mqttAuthorizationCacheManager"; + private static final String EVENT_CACHE_NAME = "mqttAuthorizationCache"; + public static final String DAS_ADMIN_SERVICE_EP = "https://" + DAS_HOST_NAME + ":" + DAS_PORT + "/services/"; + private static SSLContext sslContext; + private static Log log = LogFactory.getLog(DeviceMgtAPIUtils.class); + private static KeyStore keyStore; + private static KeyStore trustStore; + private static char[] keyStorePassword; + + static { + String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password"); + String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty( + "Security.TrustStore.Password"); + String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location"); + String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty( + "Security.TrustStore.Location"); + + //Call to load the keystore. + try { + loadKeyStore(keyStoreLocation, keyStorePassword); + //Call to load the TrustStore. + loadTrustStore(trustStoreLocation, trustStorePassword); + //Create the SSL context with the loaded TrustStore/keystore. + initSSLConnection(); + } catch (KeyStoreException | IOException | CertificateException | NoSuchAlgorithmException + | UnrecoverableKeyException | KeyManagementException e) { + log.error("publishing dynamic event receiver is failed due to " + e.getMessage(), e); + } + } public static int getNotifierFrequency(PlatformConfiguration tenantConfiguration) { List configEntryList = tenantConfiguration.getConfiguration(); @@ -113,6 +196,30 @@ public class DeviceMgtAPIUtils { return deviceManagementProviderService; } + public static DeviceTypeGeneratorService getDeviceTypeGeneratorService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + DeviceTypeGeneratorService deviceTypeGeneratorService = + (DeviceTypeGeneratorService) ctx.getOSGiService(DeviceTypeGeneratorService.class, null); + if (deviceTypeGeneratorService == null) { + String msg = "DeviceTypeGeneratorService service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return deviceTypeGeneratorService; + } + + public static boolean isValidDeviceIdentifier(DeviceIdentifier deviceIdentifier) throws DeviceManagementException { + Device device = getDeviceManagementService().getDevice(deviceIdentifier); + if (device == null || device.getDeviceIdentifier() == null || + device.getDeviceIdentifier().isEmpty() || device.getEnrolmentInfo() == null) { + return false; + } else if (EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus())) { + return false; + } + return true; + } + + public static UserStoreCountRetriever getUserStoreCountRetrieverService() throws UserStoreCounterException { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); @@ -320,6 +427,28 @@ public class DeviceMgtAPIUtils { return gadgetDataService; } + public static GeoLocationProviderService getGeoService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + GeoLocationProviderService + geoService = (GeoLocationProviderService) ctx.getOSGiService(GeoLocationProviderService.class, null); + if (geoService == null) { + throw new IllegalStateException("Geo Service has not been initialized."); + } + return geoService; + } + + public static AnalyticsDataAPI getAnalyticsDataAPI() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + AnalyticsDataAPI analyticsDataAPI = + (AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null); + if (analyticsDataAPI == null) { + String msg = "Analytics api service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return analyticsDataAPI; + } + public static int getTenantId(String tenantDomain) throws DeviceManagementException { RealmService realmService = (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null); @@ -344,4 +473,212 @@ public class DeviceMgtAPIUtils { return username; } + public static EventsPublisherService getEventPublisherService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + EventsPublisherService eventsPublisherService = + (EventsPublisherService) ctx.getOSGiService(EventsPublisherService.class, null); + if (eventsPublisherService == null) { + String msg = "Event Publisher service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return eventsPublisherService; + } + + 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( + Utils.replaceSystemProperty(DAS_ADMIN_SERVICE_EP + EVENT_STREAM_CONTEXT)); + Options streamOptions = eventStreamAdminServiceStub._getServiceClient().getOptions(); + if (streamOptions == null) { + streamOptions = new Options(); + } + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminUserName() + "@" + tenantDomain; + JWTClient jwtClient = DeviceMgtAPIUtils.getJWTClientManagerService().getJWTClient(); + + String authValue = AUTHORIZATION_HEADER_VALUE + " " + new String(Base64.encodeBase64( + jwtClient.getJwtToken(username).getBytes())); + + List
list = new ArrayList<>(); + Header httpHeader = new Header(); + httpHeader.setName(AUTHORIZATION_HEADER); + httpHeader.setValue(authValue); + list.add(httpHeader);//"https" + streamOptions.setProperty(HTTPConstants.HTTP_HEADERS, list); + streamOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER + , new Protocol(DEFAULT_HTTP_PROTOCOL + , (ProtocolSocketFactory) new SSLProtocolSocketFactory(sslContext) + , Integer.parseInt(Utils.replaceSystemProperty(DAS_PORT)))); + eventStreamAdminServiceStub._getServiceClient().setOptions(streamOptions); + return eventStreamAdminServiceStub; + } + + public static EventReceiverAdminServiceStub getEventReceiverAdminServiceStub() + throws AxisFault, UserStoreException, JWTClientException { + EventReceiverAdminServiceStub receiverAdminServiceStub = new EventReceiverAdminServiceStub( + Utils.replaceSystemProperty(DAS_ADMIN_SERVICE_EP + EVENT_RECIEVER_CONTEXT)); + Options eventReciverOptions = receiverAdminServiceStub._getServiceClient().getOptions(); + if (eventReciverOptions == null) { + eventReciverOptions = new Options(); + } + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminUserName() + "@" + tenantDomain; + JWTClient jwtClient = DeviceMgtAPIUtils.getJWTClientManagerService().getJWTClient(); + + String authValue = AUTHORIZATION_HEADER_VALUE + " " + new String(Base64.encodeBase64( + jwtClient.getJwtToken(username).getBytes())); + + List
list = new ArrayList<>(); + Header httpHeader = new Header(); + httpHeader.setName(AUTHORIZATION_HEADER); + httpHeader.setValue(authValue); + list.add(httpHeader); + + eventReciverOptions.setProperty(HTTPConstants.HTTP_HEADERS, list); + eventReciverOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER + , new Protocol(DEFAULT_HTTP_PROTOCOL + , (ProtocolSocketFactory) new SSLProtocolSocketFactory(sslContext) + , Integer.parseInt(Utils.replaceSystemProperty(DAS_PORT)))); + + receiverAdminServiceStub._getServiceClient().setOptions(eventReciverOptions); + return receiverAdminServiceStub; + } + + public static EventPublisherAdminServiceStub getEventPublisherAdminServiceStub() + throws AxisFault, UserStoreException, JWTClientException { + EventPublisherAdminServiceStub eventPublisherAdminServiceStub = new EventPublisherAdminServiceStub( + Utils.replaceSystemProperty(DAS_ADMIN_SERVICE_EP + EVENT_PUBLISHER_CONTEXT)); + Options eventReciverOptions = eventPublisherAdminServiceStub._getServiceClient().getOptions(); + if (eventReciverOptions == null) { + eventReciverOptions = new Options(); + } + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminUserName() + "@" + tenantDomain; + JWTClient jwtClient = DeviceMgtAPIUtils.getJWTClientManagerService().getJWTClient(); + + String authValue = AUTHORIZATION_HEADER_VALUE + " " + new String(Base64.encodeBase64( + jwtClient.getJwtToken(username).getBytes())); + + List
list = new ArrayList<>(); + Header httpHeader = new Header(); + httpHeader.setName(AUTHORIZATION_HEADER); + httpHeader.setValue(authValue); + list.add(httpHeader); + + eventReciverOptions.setProperty(HTTPConstants.HTTP_HEADERS, list); + eventReciverOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER + , new Protocol(DEFAULT_HTTP_PROTOCOL + , (ProtocolSocketFactory) new SSLProtocolSocketFactory(sslContext) + , Integer.parseInt(Utils.replaceSystemProperty(DAS_PORT)))); + eventPublisherAdminServiceStub._getServiceClient().setOptions(eventReciverOptions); + return eventPublisherAdminServiceStub; + } + + public static EventStreamPersistenceAdminServiceStub getEventStreamPersistenceAdminServiceStub() + throws AxisFault, UserStoreException, JWTClientException { + EventStreamPersistenceAdminServiceStub eventStreamPersistenceAdminServiceStub + = new EventStreamPersistenceAdminServiceStub( + Utils.replaceSystemProperty(DAS_ADMIN_SERVICE_EP + EVENT_PERSISTENCE_CONTEXT)); + Options eventReciverOptions = eventStreamPersistenceAdminServiceStub._getServiceClient().getOptions(); + if (eventReciverOptions == null) { + eventReciverOptions = new Options(); + } + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminUserName() + "@" + tenantDomain; + JWTClient jwtClient = DeviceMgtAPIUtils.getJWTClientManagerService().getJWTClient(); + + String authValue = AUTHORIZATION_HEADER_VALUE + " " + new String(Base64.encodeBase64( + jwtClient.getJwtToken(username).getBytes())); + + List
list = new ArrayList<>(); + Header httpHeader = new Header(); + httpHeader.setName(AUTHORIZATION_HEADER); + httpHeader.setValue(authValue); + list.add(httpHeader); + + eventReciverOptions.setProperty(HTTPConstants.HTTP_HEADERS, list); + eventReciverOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER + , new Protocol(DEFAULT_HTTP_PROTOCOL + , (ProtocolSocketFactory) new SSLProtocolSocketFactory(sslContext) + , Integer.parseInt(Utils.replaceSystemProperty(DAS_PORT)))); + + eventStreamPersistenceAdminServiceStub._getServiceClient().setOptions(eventReciverOptions); + return eventStreamPersistenceAdminServiceStub; + } + + /** + * This method is used to create the Cache that holds the event definition of the device type.. + * @return Cachemanager + */ + public static synchronized Cache getDynamicEventCache() { + return Caching.getCacheManagerFactory().getCacheManager(EVENT_CACHE_MANAGER_NAME).getCache(EVENT_CACHE_NAME); + } + + /** + * Loads the keystore. + * + * @param keyStorePath - the path of the keystore + * @param ksPassword - the keystore password + */ + private static void loadKeyStore(String keyStorePath, String ksPassword) + throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { + InputStream fis = null; + try { + keyStorePassword = ksPassword.toCharArray(); + keyStore = KeyStore.getInstance(KEY_STORE_TYPE); + fis = new FileInputStream(keyStorePath); + keyStore.load(fis, keyStorePassword); + } finally { + if (fis != null) { + fis.close(); + } + } + } + + /** + * Loads the trustore + * + * @param trustStorePath - the trustore path in the filesystem. + * @param tsPassword - the truststore password + */ + private static void loadTrustStore(String trustStorePath, String tsPassword) + throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { + + InputStream fis = null; + try { + trustStore = KeyStore.getInstance(TRUST_STORE_TYPE); + fis = new FileInputStream(trustStorePath); + trustStore.load(fis, tsPassword.toCharArray()); + } finally { + if (fis != null) { + fis.close(); + } + } + } + + /** + * Initializes the SSL Context + */ + private static void initSSLConnection() throws NoSuchAlgorithmException, UnrecoverableKeyException, + KeyStoreException, KeyManagementException { + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE); + keyManagerFactory.init(keyStore, keyStorePassword); + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE); + trustManagerFactory.init(trustStore); + + // Create and initialize SSLContext for HTTPS communication + sslContext = SSLContext.getInstance(SSLV3); + sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); + SSLContext.setDefault(sslContext); + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml index fd6c5e0309..572b64922b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -29,6 +29,7 @@ + @@ -36,11 +37,13 @@ + - - + + + @@ -69,21 +72,24 @@ - + + + - + - - + + + 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 07645e529a..7b4723d838 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 - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml @@ -50,6 +50,7 @@ javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}", com.fasterxml.jackson.annotation;version="${jackson-annotations.version}", + org.wso2.carbon.analytics.datasource.commons;version="${carbon.analytics.version.range}", io.swagger.annotations; version="${swagger.annotations.version}"; resolution:=optional @@ -68,6 +69,14 @@ org.wso2.orbit.com.fasterxml.jackson.core jackson-annotations + + org.wso2.carbon.analytics + org.wso2.carbon.analytics.api + + + org.wso2.carbon.analytics + org.wso2.carbon.analytics.datasource.commons + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java index 04df8c7dcd..d492ce22e1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java @@ -30,7 +30,7 @@ public class Device implements Serializable { private static final long serialVersionUID = 1998101711L; - @ApiModelProperty(name = "id", value = "ID of the device in the WSO2 EMM device information database.", + @ApiModelProperty(name = "id", value = "ID of the device in the device information database.", required = true) private int id; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceIdentifier.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceIdentifier.java index 5b0e234218..04504ccdc9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceIdentifier.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceIdentifier.java @@ -56,7 +56,7 @@ public class DeviceIdentifier implements Serializable{ } public void setType(String type) { - this.type = type.toLowerCase(); + this.type = type.trim(); } public String getId() { return id; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManagementConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManagementConstants.java index ba0d3d59ed..3aa85254f8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManagementConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManagementConstants.java @@ -61,6 +61,7 @@ public final class DeviceManagementConstants { private LicenseProperties() { throw new AssertionError(); } + public static final String PROVIDER = "overview_provider"; public static final String NAME = "overview_name"; public static final String LANGUAGE = "overview_language"; @@ -76,6 +77,7 @@ public final class DeviceManagementConstants { private NotificationProperties() { throw new AssertionError(); } + public static final String NOTIFICATION_CONFIG_FILE = "notification-messages.xml"; } @@ -83,6 +85,7 @@ public final class DeviceManagementConstants { 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"; @@ -91,4 +94,32 @@ public final class DeviceManagementConstants { public static final String DB_TYPE_POSTGRESQL = "PostgreSQL"; } + public static final class GeoServices { + private GeoServices() { + throw new AssertionError(); + } + + public static final String ALERT_TYPE_SPEED = "Speed"; + public static final String ALERT_TYPE_WITHIN = "Within"; + public static final String ALERT_TYPE_EXIT = "Exit"; + public static final String ALERT_TYPE_PROXIMITY = "Proximity"; + public static final String ALERT_TYPE_STATIONARY = "Stationery"; + public static final String ALERT_TYPE_TRAFFIC = "Traffic"; + public static final String REGISTRY_PATH_FOR_ALERTS = "/_system/governance/geo/alerts/"; + public static final String PROXIMITY_DISTANCE = "proximityDistance"; + public static final String PROXIMITY_TIME = "proximityTime"; + public static final String STATIONARY_NAME = "stationeryName"; + public static final String STATIONARY_TIME = "stationeryTime"; + public static final String FLUCTUATION_RADIUS = "fluctuationRadius"; + public static final String QUERY_NAME = "queryName"; + public static final String AREA_NAME = "areaName"; + + public static final String GEO_FENCE_GEO_JSON = "geoFenceGeoJSON"; + public static final String SPEED_ALERT_VALUE = "speedAlertValue"; + + public static final String DAS_PORT = "${iot.analytics.https.port}"; + public static final String DAS_HOST_NAME = "${iot.analytics.host}"; + public static final String DEFAULT_HTTP_PROTOCOL = "https"; + public static final String DAS_URL = DEFAULT_HTTP_PROTOCOL + "://" + DAS_HOST_NAME + ":" + DAS_PORT; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManager.java index 060865c726..31b1aea61e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManager.java @@ -37,8 +37,9 @@ public interface DeviceManager { /** * Method to save platform specific Configuration. - * + * @param configuration - A Platform configuration object which needs to save * @return Returns the status of the operation + * @throws DeviceManagementException If something goes wrong while saving the configuration. */ boolean saveConfiguration(PlatformConfiguration configuration) throws DeviceManagementException; @@ -46,6 +47,7 @@ public interface DeviceManager { * Method to get platform specific Configuration. * * @return Returns the platform specific tenant configurations + * @throws DeviceManagementException If something goes wrong while fetching the configuration. */ PlatformConfiguration getConfiguration() throws DeviceManagementException; @@ -53,6 +55,7 @@ public interface DeviceManager { * Method to enrolling a particular device of type mobile, IoT, etc within CDM. * * @param device Metadata corresponding to the device being enrolled + * @return A boolean indicating the status of the operation. * @throws DeviceManagementException If some unusual behaviour is observed while enrolling a device */ boolean enrollDevice(Device device) throws DeviceManagementException; @@ -61,6 +64,7 @@ public interface DeviceManager { * Method to modify the metadata corresponding to device enrollment. * * @param device Modified device enrollment related metadata + * @return A boolean indicating the status of the operation. * @throws DeviceManagementException If some unusual behaviour is observed while modify the enrollment of a * device */ @@ -70,6 +74,7 @@ public interface DeviceManager { * Method to disenroll a particular device from CDM. * * @param deviceId Fully qualified device identifier + * @return A boolean indicating the status of the operation. * @throws DeviceManagementException If some unusual behaviour is observed while disenrolling a device */ boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException; @@ -100,6 +105,7 @@ public interface DeviceManager { * * @param deviceId Fully qualified device identifier * @param status Indicates whether the device is active + * @return A boolean indicating the status of the operation. * @throws DeviceManagementException If some unusual behaviour is observed while updating the active status * of the device */ @@ -127,6 +133,7 @@ public interface DeviceManager { * * @param deviceIdentifier identifier to identify the device * @param device Updated device information related data + * @return A boolean indicating the status of the operation. * @throws DeviceManagementException If some unusual behaviour is observed while updating the device info */ boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException; @@ -136,6 +143,7 @@ public interface DeviceManager { * * @param deviceId Fully qualified device identifier * @param ownershipType Type of ownership + * @return A boolean indicating the status of the operation. * @throws DeviceManagementException If some unusual behaviour is observed while setting the ownership * of the device */ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceStatusTaskPluginConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceStatusTaskPluginConfig.java new file mode 100644 index 0000000000..9a4a4e36dd --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceStatusTaskPluginConfig.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.common; + +/** + * This class holds plugin specific configurations for Device Status Monitoring Task. + */ +public class DeviceStatusTaskPluginConfig { + + private boolean requireStatusMonitoring; + private int frequency; + private int idleTimeToMarkInactive; + private int idleTimeToMarkUnreachable; + + public int getFrequency() { + return frequency; + } + + public void setFrequency(int frequency) { + this.frequency = frequency; + } + + public int getIdleTimeToMarkInactive() { + return idleTimeToMarkInactive; + } + + public void setIdleTimeToMarkInactive(int idleTimeToMarkInactive) { + this.idleTimeToMarkInactive = idleTimeToMarkInactive; + } + + public int getIdleTimeToMarkUnreachable() { + return idleTimeToMarkUnreachable; + } + + public void setIdleTimeToMarkUnreachable(int idleTimeToMarkUnreachable) { + this.idleTimeToMarkUnreachable = idleTimeToMarkUnreachable; + } + + public boolean isRequireStatusMonitoring() { + return requireStatusMonitoring; + } + + public void setRequireStatusMonitoring(boolean requireStatusMonitoring) { + this.requireStatusMonitoring = requireStatusMonitoring; + } +} \ No newline at end of file diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/xmpp/InvalidConfigurationException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/InvalidConfigurationException.java similarity index 88% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/xmpp/InvalidConfigurationException.java rename to components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/InvalidConfigurationException.java index d0de9a178f..e6b291b605 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/xmpp/InvalidConfigurationException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/InvalidConfigurationException.java @@ -16,10 +16,10 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp; +package org.wso2.carbon.device.mgt.common; /** - * This exception is thrown whether the xmpp configured with invalid configuration. + * This exception is thrown when configured with invalid configuration. */ public class InvalidConfigurationException extends RuntimeException { 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 151e86b6ad..3799b397ba 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 @@ -29,6 +29,7 @@ public class PaginationRequest { private int rowCount; private int groupId; private String owner; + private String ownerPattern; private String status; private String deviceType; private String deviceName; @@ -120,4 +121,12 @@ public class PaginationRequest { public void setOwnerRole(String ownerRole) { this.ownerRole = ownerRole; } + + public String getOwnerPattern() { + return ownerPattern; + } + + public void setOwnerPattern(String ownerPattern) { + this.ownerPattern = ownerPattern; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/ApplicationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/ApplicationManager.java index e9da177cdd..36224b08d4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/ApplicationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/ApplicationManager.java @@ -39,7 +39,7 @@ public interface ApplicationManager { * @param pageNumber Page number of the list. * @param size Number of items in one page. * @return The list of applications belongs to a domain. - * @throws ApplicationManagementException + * @throws ApplicationManagementException If something goes wrong */ Application[] getApplications(String domain, int pageNumber, int size) @@ -52,6 +52,7 @@ public interface ApplicationManager { * @param deviceId Device id of the device that the status belongs to. * @param application Application details of the app being updated. * @param status Installed/Uninstalled + * @throws ApplicationManagementException If something goes wrong */ void updateApplicationStatus(DeviceIdentifier deviceId, Application application, String status) throws ApplicationManagementException; @@ -62,6 +63,7 @@ public interface ApplicationManager { * @param deviceId Device id of the device that the status belongs to. * @param application Application details of the app being searched. * @return Status of the application on the device. + * @throws ApplicationManagementException If something goes wrong */ String getApplicationStatus(DeviceIdentifier deviceId, Application application) throws ApplicationManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAccessAuthorizationService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAccessAuthorizationService.java index 18706fe7de..9ff3eb119b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAccessAuthorizationService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAccessAuthorizationService.java @@ -55,8 +55,8 @@ public interface DeviceAccessAuthorizationService { * DeviceIdentifier list. * * @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization. - * @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized - * devices. + * @return DeviceAuthorizationResult - Authorization result object including the list of authorized devices and + * unauthorized devices. * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. */ DeviceAuthorizationResult isUserAuthorized(List deviceIdentifiers) throws @@ -68,8 +68,8 @@ public interface DeviceAccessAuthorizationService { * * @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization. * @param groupPermissions - Group Permissions - * @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized - * devices. + * @return DeviceAuthorizationResult - Authorization result object including the list of authorized devices and + * unauthorized devices. * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. */ DeviceAuthorizationResult isUserAuthorized(List deviceIdentifiers, String[] groupPermissions) @@ -95,8 +95,8 @@ public interface DeviceAccessAuthorizationService { * @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization. * @param username - User name * @param groupPermissions - Group Permissions - * @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized - * devices. + * @return DeviceAuthorizationResult - Authorization result object including the list of authorized devices and + * unauthorized devices. * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. */ DeviceAuthorizationResult isUserAuthorized(List deviceIdentifiers, String username, @@ -129,8 +129,8 @@ public interface DeviceAccessAuthorizationService { * * @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization. * @param username - Username of the user to be checked for authorization. - * @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized - * devices. + * @return DeviceAuthorizationResult - Authorization result object including the list of authorized devices and + * unauthorized devices. * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. */ DeviceAuthorizationResult isUserAuthorized(List deviceIdentifiers, String username) throws diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/PlatformConfigurationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/PlatformConfigurationManagementService.java index 39484a378f..758c1fc495 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/PlatformConfigurationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/PlatformConfigurationManagementService.java @@ -28,6 +28,7 @@ public interface PlatformConfigurationManagementService { * * @param platformConfiguration Operation to be added. * @param resourcePath Registry resource path. + * @return A boolean indicating the status of the operation. * @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while adding the * configuration. */ @@ -38,6 +39,7 @@ public interface PlatformConfigurationManagementService { * Method to retrieve the list of general tenant configurations. * * @param resourcePath Registry resource path. + * @return Platform Configuration object. * @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while fetching the * operation list. */ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/Alert.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/Alert.java new file mode 100644 index 0000000000..f43c319567 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/Alert.java @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.common.geo.service; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * The Class Alert Bean. + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "alert") +public class Alert { + + /** + * The parse data. + */ + @XmlElement(required = true, name = "parseData") + private String parseData; + + /** + * The execution plan name. + */ + @XmlElement(required = true, name = "executionPlan") + private String executionPlan; + + /** + * The custom name. + */ + @XmlElement(required = false, nillable = true, name = "customName") + private String customName; + + /** + * The query name. + */ + @XmlElementWrapper(required = true, name = "queryName") + private String queryName; + + /** + * The CEP action. + */ + @XmlElementWrapper(required = true, name = "cepAction") + private String cepAction; + + /** + * The device id. + */ + @XmlElementWrapper(required = true, name = "deviceId") + private String deviceId; + + /** + * The stationery time. + */ + @XmlElementWrapper(required = false, nillable = true, name = "stationeryTime") + private String stationeryTime; + + /** + * The fluctuation radius. + */ + @XmlElementWrapper(required = false, nillable = true, name = "fluctuationRadius") + private String fluctuationRadius; + + /** + * The proximity distance. + */ + @XmlElementWrapper(required = false, nillable = true, name = "proximityDistance") + private String proximityDistance; + + /** + * The proximity time. + */ + @XmlElementWrapper(required = false, nillable = true, name = "proximityTime") + private String proximityTime; + + public String getParseData() { + return parseData; + } + + public void setParseData(String parseData) { + this.parseData = parseData; + } + + public String getExecutionPlan() { + return executionPlan; + } + + public void setExecutionPlan(String executionPlan) { + this.executionPlan = executionPlan; + } + + public String getCustomName() { + return customName; + } + + public void setCustomName(String customName) { + this.customName = customName; + } + + public String getQueryName() { + return queryName; + } + + public void setQueryName(String queryName) { + this.queryName = queryName; + } + + public String getCepAction() { + return cepAction; + } + + public void setCepAction(String cepAction) { + this.cepAction = cepAction; + } + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public String getStationeryTime() { + return stationeryTime; + } + + public void setStationeryTime(String stationeryTime) { + this.stationeryTime = stationeryTime; + } + + public String getFluctuationRadius() { + return fluctuationRadius; + } + + public void setFluctuationRadius(String fluctuationRadius) { + this.fluctuationRadius = fluctuationRadius; + } + + public String getProximityDistance() { + return proximityDistance; + } + + public void setProximityDistance(String proximityDistance) { + this.proximityDistance = proximityDistance; + } + + public String getProximityTime() { + return proximityTime; + } + + public void setProximityTime(String proximityTime) { + this.proximityTime = proximityTime; + } + + @Override + public String toString() { + return String.format( + "{\"queryName\" : %s,\"customName\" : %s,\"cepAction\" : %s,\"deviceId\" : %s }", + queryName, customName, cepAction, deviceId); + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/Event.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/Event.java new file mode 100644 index 0000000000..8c79475a37 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/Event.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.common.geo.service; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * The Class RecordBean. + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "event") +public class Event { + + /** The id. */ + @XmlElement(required = false, name = "id") + private String id; + + /** The table name. */ + @XmlElement(required = false, name = "tableName") + private String tableName; + + /** The timestamp. */ + @XmlElement(required = false, nillable = true, name = "timestamp") + private long timestamp; + + /** The values. */ + @XmlElementWrapper(required = true, name = "values") + private Map values; + + /** + * Sets the table name. + * @param tableName the new table name + */ + public void setTableName(String tableName) { + this.tableName = tableName; + } + + /** + * Sets the values. + * @param values the values + */ + public void setValues(Map values) { + this.values = values; + } + + /** + * Sets the timestamp. + * @param timestamp the new timestamp + */ + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + /** + * Sets the id. + * @param id the new id + */ + public void setId(String id) { + this.id = id; + } + + /** + * Gets the id. + * @return the id + */ + public String getId() { + return id; + } + /** + * Gets the table name. + * @return the table name + */ + public String getTableName() { + return tableName; + } + + /** + * Gets the values. + * @return the values + */ + public Map getValues() { + return values; + } + + /** + * Gets the value. + * @param name + * the name + * @return the value + */ + public Object getValue(String name) { + return this.values.get(name); + } + + /** + * Gets the timestamp. + * @return the timestamp + */ + public long getTimestamp() { + return timestamp; + } + + @Override + public String toString(){ + List valueList = new ArrayList<>(); + for (Map.Entry entry : values.entrySet()) { + valueList.add(entry.getKey() + ":" + entry.getValue()); + } + return valueList.toString(); + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoFence.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoFence.java new file mode 100644 index 0000000000..359264dadb --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoFence.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.common.geo.service; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * The Class GeoFence. + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "fence") +public class GeoFence { + + /** The geoJson. */ + @XmlElement(required = false, name = "geoJson") + private String geoJson; + + /** The queryName. */ + @XmlElement(required = false, name = "queryName") + private String queryName; + + /** The areaName. */ + @XmlElement(required = false, name = "areaName") + private String areaName; + + /** The createdTime. */ + @XmlElement(required = false, nillable = true, name = "createdTime") + private long createdTime; + + /** The stationaryTime. */ + @XmlElement(required = false, name = "stationaryTime") + private String stationaryTime; + + /** The fluctuationRadius. */ + @XmlElement(required = false, name = "fluctuationRadius") + private String fluctuationRadius; + + public String getGeoJson() { + return geoJson; + } + + public void setGeoJson(String geoJson) { + this.geoJson = geoJson; + } + + public String getQueryName() { + return queryName; + } + + public void setQueryName(String queryName) { + this.queryName = queryName; + } + + public String getAreaName() { + return areaName; + } + + public void setAreaName(String areaName) { + this.areaName = areaName; + } + + public long getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(long createdTime) { + this.createdTime = createdTime; + } + + public void setStationaryTime(String stationaryTime) { + this.stationaryTime = stationaryTime; + } + + public String getStationaryTime() { + return stationaryTime; + } + + public void setFluctuationRadius(String fluctuationRadius) { + this.fluctuationRadius = fluctuationRadius; + } + + public String getFluctuationRadius() { + return fluctuationRadius; + } + + @Override + public String toString() { + return "{\"geoJson\": " + geoJson + + ",\"queryName\": " + queryName + + ",\"areaName\":" + areaName + + ",\"createdTime\":" + createdTime + + "}"; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoLocationBasedServiceException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoLocationBasedServiceException.java new file mode 100644 index 0000000000..e9eb31f329 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoLocationBasedServiceException.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2017, 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. + */ +package org.wso2.carbon.device.mgt.common.geo.service; + +/** + * Custom exception class of Geo Service related operations. + */ +public class GeoLocationBasedServiceException extends Exception { + + private static final long serialVersionUID = -7151990041029070298L; + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public GeoLocationBasedServiceException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public GeoLocationBasedServiceException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public GeoLocationBasedServiceException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public GeoLocationBasedServiceException() { + super(); + } + + public GeoLocationBasedServiceException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoLocationProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoLocationProviderService.java new file mode 100644 index 0000000000..d8375ab583 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoLocationProviderService.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2015, 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. + */ + +package org.wso2.carbon.device.mgt.common.geo.service; + +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; + +import java.util.List; + +/** + * This represents the Geo service functionality which should be implemented by + * required GeoServiceManagers. + */ +public interface GeoLocationProviderService { + + List getWithinAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException; + + List getExitAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException; + + boolean createGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType) + throws GeoLocationBasedServiceException; + + boolean updateGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType) + throws GeoLocationBasedServiceException; + + boolean removeGeoAlert(String alertType, DeviceIdentifier identifier, String queryName) + throws GeoLocationBasedServiceException; + + String getSpeedAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException; + + String getProximityAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException; + + List getStationaryAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException; + + List getTrafficAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java index cbf26cc4cf..d2a0cfcf6d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java @@ -32,6 +32,7 @@ public interface NotificationManagementService { /** * Method to add a notification to the database. * + * @param deviceId - DeviceIdentifier of the device * @param notification - Notification to be added to database. * @return boolean status of the operation. * @throws NotificationManagementException @@ -66,7 +67,7 @@ public interface NotificationManagementService { * Method to fetch all the notifications in the database. * * @return List of all Notifications in the database. - * @throws NotificationManagementException + * @throws NotificationManagementException if something goes wrong while fetching the Notifications. * */ List getAllNotifications() throws NotificationManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java index ce548628b9..8de9f3199e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java @@ -17,11 +17,14 @@ */ package org.wso2.carbon.device.mgt.common.operation.mgt; -import org.wso2.carbon.device.mgt.common.*; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.InvalidDeviceException; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; import java.util.List; -import java.util.Map; /** * This represents the Device Operation management functionality which should be implemented by @@ -34,8 +37,9 @@ public interface OperationManager { * * @param operation Operation to be added * @param devices List of DeviceIdentifiers to execute the operation + * @return Activity object corresponds to the added operation. * @throws OperationManagementException If some unusual behaviour is observed while adding the operation - * InvalidDeviceException If addOperation request contains Invalid DeviceIdentifiers. + * @throws InvalidDeviceException If addOperation request contains Invalid DeviceIdentifiers. */ Activity addOperation(Operation operation, List devices) throws OperationManagementException, InvalidDeviceException; @@ -43,7 +47,8 @@ public interface OperationManager { /** * Method to retrieve the list of all operations to a device. * - * @param deviceId + * @param deviceId - Device Identifier of the device + * @return A List of operations applied to the given device-id. * @throws OperationManagementException If some unusual behaviour is observed while fetching the * operation list. */ @@ -64,6 +69,7 @@ public interface OperationManager { * Method to retrieve the list of available operations to a device. * * @param deviceId DeviceIdentifier of the device + * @return A List of pending operations. * @throws OperationManagementException If some unusual behaviour is observed while fetching the * operation list. */ @@ -87,6 +93,8 @@ public interface OperationManager { Activity getOperationByActivityId(String activity) throws OperationManagementException; + Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) throws OperationManagementException; + List getOperationUpdatedAfter(long timestamp) throws OperationManagementException; List getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java index 5a31013663..68b81a9de4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java @@ -27,19 +27,20 @@ import java.util.Properties; public interface PermissionManagerService { /** + * Adds a permission. * * @param permission - Permission to be added - * @throws PermissionManagementException If some unusual behaviour is observed while adding the - * permission. + * @return A boolean indicating the status of the operation. + * @throws PermissionManagementException If some unusual behaviour is observed while adding the permission. */ boolean addPermission(Permission permission) throws PermissionManagementException; /** + * Fetches a given permission. * * @param properties - Properties of the permission to be fetched. * @return The matched Permission object. - * @throws PermissionManagementException If some unusual behaviour is observed while fetching the - * permission. + * @throws PermissionManagementException If some unusual behaviour is observed while fetching the permission. */ Permission getPermission(Properties properties) throws PermissionManagementException; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/InvalidConfigurationException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/pull/notification/PullNotificationExecutionFailedException.java similarity index 55% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/InvalidConfigurationException.java rename to components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/pull/notification/PullNotificationExecutionFailedException.java index e6f186f431..ecd3a84ab1 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/InvalidConfigurationException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/pull/notification/PullNotificationExecutionFailedException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017, 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 @@ -16,30 +16,29 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt; +package org.wso2.carbon.device.mgt.common.pull.notification; -/** - * This exception is thrown whether the mqtt configured with invalid configuration. - */ -public class InvalidConfigurationException extends RuntimeException { +public class PullNotificationExecutionFailedException extends Exception { + + private static final long serialVersionUID = -3151279311923070297L; - public InvalidConfigurationException(String msg, Exception nestedEx) { + public PullNotificationExecutionFailedException(String msg, Exception nestedEx) { super(msg, nestedEx); } - public InvalidConfigurationException(String message, Throwable cause) { + public PullNotificationExecutionFailedException(String message, Throwable cause) { super(message, cause); } - public InvalidConfigurationException(String msg) { + public PullNotificationExecutionFailedException(String msg) { super(msg); } - public InvalidConfigurationException() { + public PullNotificationExecutionFailedException() { super(); } - public InvalidConfigurationException(Throwable cause) { + public PullNotificationExecutionFailedException(Throwable cause) { super(cause); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/pull/notification/PullNotificationSubscriber.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/pull/notification/PullNotificationSubscriber.java new file mode 100644 index 0000000000..8d59500ee0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/pull/notification/PullNotificationSubscriber.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.common.pull.notification; + + +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; + +import java.util.Map; + +/** + * This will handle the execution flow when a device sends a payload to IoT Server. + */ +public interface PullNotificationSubscriber { + + void init(Map properties); + + void execute(DeviceIdentifier deviceIdentifier, Operation operation) throws PullNotificationExecutionFailedException; + + void clean(); +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/push/notification/NotificationStrategy.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/push/notification/NotificationStrategy.java index c1f7e37da7..f18a5f5e7c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/push/notification/NotificationStrategy.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/push/notification/NotificationStrategy.java @@ -32,8 +32,8 @@ public interface NotificationStrategy { void undeploy(); /** - * Provides push notification configuration - * + * Provides push notification configuration. + * @return PushNotificationConfig for this NotificationStrategy */ PushNotificationConfig getConfig(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java index 7e6f730337..8cbe049245 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java @@ -21,6 +21,7 @@ package org.wso2.carbon.device.mgt.common.spi; import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; +import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; /** @@ -47,6 +48,8 @@ public interface DeviceManagementService { InitialOperationConfig getInitialOperationConfig(); + PullNotificationSubscriber getPullNotificationSubscriber(); + DeviceStatusTaskPluginConfig getDeviceStatusTaskPluginConfig(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceTypeGeneratorService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceTypeGeneratorService.java new file mode 100644 index 0000000000..f9c98e0f3a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceTypeGeneratorService.java @@ -0,0 +1,13 @@ +package org.wso2.carbon.device.mgt.common.spi; + +import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; + +/** + * This implementation populates device management service. + */ +public interface DeviceTypeGeneratorService { + + DeviceManagementService populateDeviceManagementService(String deviceTypeName + , DeviceTypeMetaDefinition deviceTypeMetaDefinition); + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeDefinitionProvider.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeDefinitionProvider.java new file mode 100644 index 0000000000..fab714fd5b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeDefinitionProvider.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2016, 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. + * + */ +package org.wso2.carbon.device.mgt.common.type.mgt; + +public interface DeviceTypeDefinitionProvider { + + DeviceTypeMetaDefinition getDeviceTypeMetaDefinition(); + +} 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 new file mode 100644 index 0000000000..98b6c36e32 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java @@ -0,0 +1,86 @@ +package org.wso2.carbon.device.mgt.common.type.mgt; + +import org.wso2.carbon.device.mgt.common.Feature; +import org.wso2.carbon.device.mgt.common.InitialOperationConfig; +import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; +import org.wso2.carbon.device.mgt.common.license.mgt.License; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; + +import java.util.List; + +public class DeviceTypeMetaDefinition { + + private List properties; + private List features; + private boolean claimable; + private PushNotificationConfig pushNotificationConfig; + private boolean policyMonitoringEnabled; + private InitialOperationConfig initialOperationConfig; + private License license; + private String description; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + public List getFeatures() { + return features; + } + + public void setFeatures(List features) { + this.features = features; + } + + public boolean isClaimable() { + return claimable; + } + + public void setClaimable(boolean isClaimable) { + this.claimable = isClaimable; + } + + public PushNotificationConfig getPushNotificationConfig() { + return pushNotificationConfig; + } + + public void setPushNotificationConfig( + PushNotificationConfig pushNotificationConfig) { + this.pushNotificationConfig = pushNotificationConfig; + } + + public boolean isPolicyMonitoringEnabled() { + return policyMonitoringEnabled; + } + + public void setPolicyMonitoringEnabled(boolean policyMonitoringEnabled) { + this.policyMonitoringEnabled = policyMonitoringEnabled; + } + + public InitialOperationConfig getInitialOperationConfig() { + return initialOperationConfig; + } + + public void setInitialOperationConfig(InitialOperationConfig initialOperationConfig) { + this.initialOperationConfig = initialOperationConfig; + } + + public License getLicense() { + return license; + } + + public void setLicense(License license) { + this.license = license; + } +} 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 ea73b9e5a4..81a1d150a7 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 - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml @@ -66,6 +66,7 @@ org.wso2.carbon.core, org.wso2.carbon.utils.*, org.wso2.carbon.device.mgt.common.*, + org.wso2.carbon.device.mgt.analytics.data.publisher.service, org.wso2.carbon.user.api, org.wso2.carbon.user.core.*, org.wso2.carbon.registry.core.service, @@ -81,12 +82,15 @@ org.wso2.carbon.ntask.common, org.apache.catalina, org.apache.catalina.core, - org.apache.commons.collections, + org.apache.commons.collections;version="${commons-collections.version.range}", org.wso2.carbon.email.sender.*, io.swagger.annotations.*;resolution:=optional, org.wso2.carbon, org.wso2.carbon.base, - org.scannotation.* + org.scannotation.*, + org.wso2.carbon.event.processor.stub, + org.wso2.carbon.identity.jwt.client.extension.service, + org.apache.commons.codec.binary !org.wso2.carbon.device.mgt.core.internal, @@ -133,6 +137,29 @@ org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.common + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.analytics.data.publisher + provided + + + org.slf4j + slf4j-api + + + javax.servlet + servlet-api + + + org.wso2.carbon.registry + org.wso2.carbon.registry.indexing + + + org.wso2.carbon.identity.framework + org.wso2.carbon.user.mgt + + + org.wso2.carbon org.wso2.carbon.logging @@ -262,6 +289,20 @@ org.wso2.carbon.devicemgt org.wso2.carbon.apimgt.annotations + + org.wso2.carbon.event-processing + org.wso2.carbon.event.processor.stub + + + org.wso2.carbon.devicemgt + org.wso2.carbon.identity.jwt.client.extension + provided + + + commons-codec.wso2 + commons-codec + provided + javax.ws.rs 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 15df1e4435..af07800f3d 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 @@ -22,6 +22,9 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation; public final class DeviceManagementConstants { + public static final String DM_CACHE_MANAGER = "DM_CACHE_MANAGER"; + public static final String DEVICE_CACHE = "DEVICE_CACHE"; + public static final class Common { private Common() { throw new AssertionError(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java index ca32fa037b..7a3b487121 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java @@ -17,24 +17,36 @@ */ package org.wso2.carbon.device.mgt.core; +import com.google.gson.Gson; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.DeviceTypeIdentifier; +import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber; +import org.wso2.carbon.device.mgt.core.dto.DeviceManagementServiceHolder; +import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.ProvisioningConfig; +import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationProvider; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; +import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeDefinitionProvider; +import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; +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.dto.DeviceType; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; import org.wso2.carbon.device.mgt.core.internal.DeviceManagerStartupListener; import org.wso2.carbon.device.mgt.core.internal.DeviceMonitoringOperationDataHolder; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerRepository; +import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskException; +import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskManagerService; +import org.wso2.carbon.device.mgt.core.status.task.impl.DeviceStatusTaskManagerServiceImpl; import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; @@ -45,71 +57,101 @@ import java.util.Map; public class DeviceManagementPluginRepository implements DeviceManagerStartupListener { - private Map providers; - private boolean isInited; + private Map providers; + private boolean isInitiated; private static final Log log = LogFactory.getLog(DeviceManagementPluginRepository.class); private OperationManagerRepository operationManagerRepository; + private static final long DEFAULT_UPDATE_TIMESTAMP = 900000L; public DeviceManagementPluginRepository() { this.operationManagerRepository = new OperationManagerRepository(); - providers = Collections.synchronizedMap(new HashMap()); + providers = Collections.synchronizedMap(new HashMap()); DeviceManagementServiceComponent.registerStartupListener(this); } public void addDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { - String deviceType = provider.getType().toLowerCase(); - + String deviceType = provider.getType(); ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); String tenantDomain = provisioningConfig.getProviderTenantDomain(); + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); boolean isSharedWithAllTenants = provisioningConfig.isSharedWithAllTenants(); int tenantId = DeviceManagerUtil.getTenantId(tenantDomain); if (tenantId == -1) { throw new DeviceManagementException("No tenant available for tenant domain " + tenantDomain); } synchronized (providers) { - try { - if (isInited) { - /* Initializing Device Management Service Provider */ - provider.init(); - DeviceManagerUtil.registerDeviceType(deviceType, tenantId, isSharedWithAllTenants); - DeviceManagementDataHolder.getInstance().setRequireDeviceAuthorization(deviceType, - provider.getDeviceManager() - .requireDeviceAuthorization()); - registerPushNotificationStrategy(provider); - registerMonitoringTask(provider); + if (isInitiated) { + /* Initializing Device Management Service Provider */ + provider.init(); + DeviceTypeMetaDefinition deviceTypeDefinition = null; + if (provider instanceof DeviceTypeDefinitionProvider) { + DeviceTypeServiceIdentifier deviceTypeIdentifier = new DeviceTypeServiceIdentifier( + provider.getType()); + DeviceManagementServiceHolder existingProvider = providers.get(deviceTypeIdentifier); + deviceTypeDefinition = ((DeviceTypeDefinitionProvider) provider).getDeviceTypeMetaDefinition(); + if (existingProvider != null && !(existingProvider.getDeviceManagementService() + instanceof DeviceTypeDefinitionProvider)) { + throw new DeviceManagementException("Definition of device type " + provider.getType() + + " is already available through sharing."); + } + + deviceTypeIdentifier = new DeviceTypeServiceIdentifier(provider.getType(), tenantId); + existingProvider = providers.get(deviceTypeIdentifier); + if (existingProvider != null) { + removeDeviceManagementProvider(provider); + } + } + + DeviceManagerUtil.registerDeviceType(deviceType, tenantId, isSharedWithAllTenants, deviceTypeDefinition); + DeviceManagementDataHolder.getInstance().setRequireDeviceAuthorization(deviceType, + provider.getDeviceManager() + .requireDeviceAuthorization()); + registerPushNotificationStrategy(provider); + registerMonitoringTask(provider); + if (deviceManagementConfig != null && deviceManagementConfig.getDeviceStatusTaskConfig().isEnabled()) { + DeviceType deviceTypeObj = DeviceManagerUtil.getDeviceType(deviceType, tenantId); + registerDeviceStatusMonitoringTask(deviceTypeObj, provider); } - } catch (DeviceManagementException e) { - throw new DeviceManagementException("Error occurred while adding device management provider '" + - deviceType + "'", e); } + DeviceManagementServiceHolder deviceManagementServiceHolder = new DeviceManagementServiceHolder(provider); if (isSharedWithAllTenants) { - DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType); - providers.put(deviceTypeIdentifier, provider); + DeviceTypeServiceIdentifier deviceTypeIdentifier = new DeviceTypeServiceIdentifier(deviceType); + providers.put(deviceTypeIdentifier, deviceManagementServiceHolder); } else { - DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType, tenantId); - providers.put(deviceTypeIdentifier, provider); + DeviceTypeServiceIdentifier deviceTypeIdentifier = new DeviceTypeServiceIdentifier(deviceType, tenantId); + providers.put(deviceTypeIdentifier, deviceManagementServiceHolder); } } } public void removeDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { - String deviceTypeName = provider.getType().toLowerCase(); - DeviceTypeIdentifier deviceTypeIdentifier; - ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); - if (provisioningConfig.isSharedWithAllTenants()) { - deviceTypeIdentifier = new DeviceTypeIdentifier(deviceTypeName); - providers.remove(deviceTypeIdentifier); - } else { - int providerTenantId = DeviceManagerUtil.getTenantId(provisioningConfig.getProviderTenantDomain()); - deviceTypeIdentifier = new DeviceTypeIdentifier(deviceTypeName, providerTenantId); - providers.remove(deviceTypeIdentifier); - } - unregisterPushNotificationStrategy(deviceTypeIdentifier); - unregisterMonitoringTask(provider); + String deviceTypeName = provider.getType(); + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance() + .getDeviceManagementConfig(); + DeviceTypeServiceIdentifier deviceTypeIdentifier; + ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); + if (provisioningConfig.isSharedWithAllTenants()) { + deviceTypeIdentifier = new DeviceTypeServiceIdentifier(deviceTypeName); + } else { + int providerTenantId = DeviceManagerUtil.getTenantId(provisioningConfig.getProviderTenantDomain()); + deviceTypeIdentifier = new DeviceTypeServiceIdentifier(deviceTypeName, providerTenantId); + } + PullNotificationSubscriber pullNotificationSubscriber = provider.getPullNotificationSubscriber(); + if (pullNotificationSubscriber != null) { + pullNotificationSubscriber.clean(); + } + providers.remove(deviceTypeIdentifier); + unregisterPushNotificationStrategy(deviceTypeIdentifier); + unregisterMonitoringTask(provider); + if (deviceManagementConfig != null && deviceManagementConfig.getDeviceStatusTaskConfig().isEnabled()) { + DeviceType deviceTypeObj = DeviceManagerUtil.getDeviceType(deviceTypeIdentifier.getDeviceType(), + deviceTypeIdentifier.getTenantId()); + unregisterDeviceStatusMonitoringTask(deviceTypeObj, provider); + } } - private void unregisterPushNotificationStrategy(DeviceTypeIdentifier deviceTypeIdentifier) { + private void unregisterPushNotificationStrategy(DeviceTypeServiceIdentifier deviceTypeIdentifier) { OperationManager operationManager = operationManagerRepository.getOperationManager( deviceTypeIdentifier); if (operationManager != null) { @@ -123,20 +165,82 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis public DeviceManagementService getDeviceManagementService(String type, int tenantId) { //Priority need to be given to the tenant before public. - DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(type.toLowerCase(), tenantId); - DeviceManagementService provider = providers.get(deviceTypeIdentifier); + DeviceTypeServiceIdentifier deviceTypeIdentifier = new DeviceTypeServiceIdentifier(type, tenantId); + DeviceManagementServiceHolder provider = providers.get(deviceTypeIdentifier); if (provider == null) { - deviceTypeIdentifier = new DeviceTypeIdentifier(type.toLowerCase()); + deviceTypeIdentifier = new DeviceTypeServiceIdentifier(type); provider = providers.get(deviceTypeIdentifier); + if (provider == null) { + try { + DeviceType deviceType = DeviceManagerUtil.getDeviceType(type, tenantId); + if (deviceType == null) { + return null; + } + DeviceTypeMetaDefinition deviceTypeMetaDefinition = deviceType.getDeviceTypeMetaDefinition(); + if (deviceTypeMetaDefinition != null) { + DeviceManagementService deviceTypeManagerService = DeviceManagementDataHolder.getInstance() + .getDeviceTypeGeneratorService().populateDeviceManagementService(type, deviceTypeMetaDefinition); + if (deviceTypeManagerService == null) { + log.error("Failing to retrieve the device type service for " + type); + return null; + } + addDeviceManagementProvider(deviceTypeManagerService); + deviceTypeIdentifier = new DeviceTypeServiceIdentifier(type, tenantId); + provider = providers.get(deviceTypeIdentifier); + } + } catch (DeviceManagementException e) { + log.error("Failing to retrieve the device type service for " + type, e); + return null; + } + } + if (provider == null) { + log.error("Device Type Definition not found for " + type); + return null; + } + } else { + // retrieves per tenant device type management service + if (provider.getDeviceManagementService() instanceof DeviceTypeDefinitionProvider) { + //handle updates. + long updatedTimestamp = provider.getTimestamp(); + if (System.currentTimeMillis() - updatedTimestamp > DEFAULT_UPDATE_TIMESTAMP) { + try { + DeviceType deviceType = DeviceManagerUtil.getDeviceType(type,tenantId); + DeviceTypeMetaDefinition deviceTypeMetaDefinition = deviceType.getDeviceTypeMetaDefinition(); + if (deviceTypeMetaDefinition != null) { + Gson gson = new Gson(); + String dbStoredDefinition = gson.toJson(deviceTypeMetaDefinition); + deviceTypeMetaDefinition = ((DeviceTypeDefinitionProvider) + provider.getDeviceManagementService()).getDeviceTypeMetaDefinition(); + String cachedDefinition = gson.toJson(deviceTypeMetaDefinition); + if (!cachedDefinition.equals(dbStoredDefinition)) { + DeviceManagementService deviceTypeManagerService = DeviceManagementDataHolder.getInstance() + .getDeviceTypeGeneratorService().populateDeviceManagementService(type, deviceTypeMetaDefinition); + if (deviceTypeManagerService == null) { + log.error("Failing to retrieve the device type service for " + type); + return null; + } + addDeviceManagementProvider(deviceTypeManagerService); + deviceTypeIdentifier = new DeviceTypeServiceIdentifier(type, tenantId); + provider = providers.get(deviceTypeIdentifier); + } else { + provider.setTimestamp(System.currentTimeMillis()); + } + } + } catch (DeviceManagementException e) { + log.error("Failing to retrieve the device type service for " + type, e); + return null; + } + } + } } - return provider; + return provider.getDeviceManagementService(); } - public Map getAllDeviceManagementServices(int tenantId) { - Map tenantProviders = new HashMap<>(); - for (DeviceTypeIdentifier identifier : providers.keySet()) { + public Map getAllDeviceManagementServices(int tenantId) { + Map tenantProviders = new HashMap<>(); + for (DeviceTypeServiceIdentifier identifier : providers.keySet()) { if (identifier.getTenantId() == tenantId || identifier.isSharedWithAllTenant()) { - tenantProviders.put(identifier, providers.get(identifier)); + tenantProviders.put(identifier, providers.get(identifier).getDeviceManagementService()); } } return tenantProviders; @@ -149,30 +253,30 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( deviceManagementService.getProvisioningConfig().getProviderTenantDomain(), true); try { - boolean isSharedWithAllTenants = deviceManagementService.getProvisioningConfig().isSharedWithAllTenants(); - DeviceTypeIdentifier deviceTypeIdentifier; - if (isSharedWithAllTenants) { - deviceTypeIdentifier = new DeviceTypeIdentifier(deviceManagementService.getType()); - } else { - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - deviceTypeIdentifier = new DeviceTypeIdentifier(deviceManagementService.getType(), tenantId); - } + boolean isSharedWithAllTenants = deviceManagementService.getProvisioningConfig().isSharedWithAllTenants(); + DeviceTypeServiceIdentifier deviceTypeIdentifier; + if (isSharedWithAllTenants) { + deviceTypeIdentifier = new DeviceTypeServiceIdentifier(deviceManagementService.getType()); + } else { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + deviceTypeIdentifier = new DeviceTypeServiceIdentifier(deviceManagementService.getType(), tenantId); + } - if (pushNoteConfig != null) { - PushNotificationProvider provider = DeviceManagementDataHolder.getInstance() - .getPushNotificationProviderRepository().getProvider(pushNoteConfig.getType()); - if (provider == null) { - throw new DeviceManagementException( - "No registered push notification provider found for the type: '" + - pushNoteConfig.getType() + "'."); + if (pushNoteConfig != null) { + PushNotificationProvider provider = DeviceManagementDataHolder.getInstance() + .getPushNotificationProviderRepository().getProvider(pushNoteConfig.getType()); + if (provider == null) { + throw new DeviceManagementException( + "No registered push notification provider found for the type: '" + + pushNoteConfig.getType() + "'."); + } + NotificationStrategy notificationStrategy = provider.getNotificationStrategy(pushNoteConfig); + operationManagerRepository.addOperationManager(deviceTypeIdentifier, + new OperationManagerImpl(deviceTypeIdentifier.getDeviceType(), notificationStrategy)); + } else { + operationManagerRepository.addOperationManager(deviceTypeIdentifier, + new OperationManagerImpl(deviceTypeIdentifier.getDeviceType())); } - NotificationStrategy notificationStrategy = provider.getNotificationStrategy(pushNoteConfig); - operationManagerRepository.addOperationManager(deviceTypeIdentifier, - new OperationManagerImpl(deviceTypeIdentifier.getDeviceType(), notificationStrategy)); - } else { - operationManagerRepository.addOperationManager(deviceTypeIdentifier, - new OperationManagerImpl(deviceTypeIdentifier.getDeviceType())); - } } finally { PrivilegedCarbonContext.endTenantFlow(); } @@ -181,12 +285,10 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis private void registerMonitoringTask(DeviceManagementService deviceManagementService) throws DeviceManagementException { try { - DeviceTaskManagerService deviceTaskManagerService = DeviceManagementDataHolder.getInstance() - .getDeviceTaskManagerService(); - - OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementService - .getOperationMonitoringConfig(); - + DeviceTaskManagerService deviceTaskManagerService = DeviceManagementDataHolder.getInstance(). + getDeviceTaskManagerService(); + OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementService. + getOperationMonitoringConfig(); if (operationMonitoringTaskConfig != null && operationMonitoringTaskConfig.isEnabled()) { if (deviceTaskManagerService == null) { @@ -206,10 +308,10 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis private void unregisterMonitoringTask(DeviceManagementService deviceManagementService) throws DeviceManagementException { try { - DeviceTaskManagerService deviceTaskManagerService = DeviceManagementDataHolder.getInstance() - .getDeviceTaskManagerService(); - OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementService - .getOperationMonitoringConfig(); + DeviceTaskManagerService deviceTaskManagerService = DeviceManagementDataHolder.getInstance(). + getDeviceTaskManagerService(); + OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementService. + getOperationMonitoringConfig(); if (operationMonitoringTaskConfig != null) { deviceTaskManagerService.stopTask(deviceManagementService.getType(), deviceManagementService.getOperationMonitoringConfig()); @@ -220,12 +322,51 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis } } + private void registerDeviceStatusMonitoringTask(DeviceType deviceType, DeviceManagementService deviceManagementService) throws + DeviceManagementException { + DeviceTaskManagerService deviceTaskManagerService = DeviceManagementDataHolder.getInstance(). + getDeviceTaskManagerService(); + DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig = deviceManagementService.getDeviceStatusTaskPluginConfig(); + if (deviceStatusTaskPluginConfig != null && deviceStatusTaskPluginConfig.isRequireStatusMonitoring()) { + if (deviceTaskManagerService == null) { + DeviceManagementDataHolder.getInstance().addDeviceStatusTaskPluginConfig(deviceType, + deviceStatusTaskPluginConfig); + } else { + try { + new DeviceStatusTaskManagerServiceImpl().startTask(deviceType, deviceStatusTaskPluginConfig); + } catch (DeviceStatusTaskException e) { + throw new DeviceManagementException("Error occurred while adding Device Status task service for '" + + deviceManagementService.getType() + "'", e); + } + } + } + } + + private void unregisterDeviceStatusMonitoringTask(DeviceType deviceType, DeviceManagementService deviceManagementService) throws + DeviceManagementException { + DeviceStatusTaskManagerService deviceStatusTaskManagerService = DeviceManagementDataHolder.getInstance(). + getDeviceStatusTaskManagerService(); + DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig = deviceManagementService.getDeviceStatusTaskPluginConfig(); + if (deviceStatusTaskPluginConfig != null && deviceStatusTaskPluginConfig.isRequireStatusMonitoring()) { + try { + DeviceManagementDataHolder.getInstance().removeDeviceStatusTaskPluginConfig(deviceType); + deviceStatusTaskManagerService.stopTask(deviceType, deviceStatusTaskPluginConfig); + } catch (DeviceStatusTaskException e) { + throw new DeviceManagementException("Error occurred while stopping Device Status task service for '" + + deviceManagementService.getType() + "'", e); + } + } + } + public OperationManager getOperationManager(String deviceType, int tenantId) { //Priority need to be given to the tenant before public. - DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType.toLowerCase(), tenantId); + DeviceTypeServiceIdentifier deviceTypeIdentifier = new DeviceTypeServiceIdentifier(deviceType, tenantId); + if (getDeviceManagementService(deviceType, tenantId) == null) { + return null; + } OperationManager operationManager = operationManagerRepository.getOperationManager(deviceTypeIdentifier); if (operationManager == null) { - deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType.toLowerCase()); + deviceTypeIdentifier = new DeviceTypeServiceIdentifier(deviceType); operationManager = operationManagerRepository.getOperationManager(deviceTypeIdentifier); } return operationManager; @@ -235,32 +376,45 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis public void notifyObserver() { String deviceTypeName; synchronized (providers) { - for (DeviceManagementService provider : providers.values()) { + for (DeviceManagementServiceHolder deviceManagementServiceHolder : providers.values()) { + DeviceManagementService provider= deviceManagementServiceHolder.getDeviceManagementService(); try { provider.init(); - deviceTypeName = provider.getType().toLowerCase(); + deviceTypeName = provider.getType(); ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); int tenantId = DeviceManagerUtil.getTenantId(provisioningConfig.getProviderTenantDomain()); - DeviceManagerUtil.registerDeviceType(deviceTypeName, tenantId, - provisioningConfig.isSharedWithAllTenants()); + DeviceTypeMetaDefinition deviceTypeDefinition = null; + if (provider instanceof DeviceTypeDefinitionProvider) { + deviceTypeDefinition = ((DeviceTypeDefinitionProvider) provider).getDeviceTypeMetaDefinition(); + + DeviceTypeServiceIdentifier deviceTypeIdentifier = new DeviceTypeServiceIdentifier( + provider.getType(), tenantId); + DeviceManagementServiceHolder existingProvider = providers.get(deviceTypeIdentifier); + if (existingProvider != null) { + removeDeviceManagementProvider(provider); + } + } + DeviceManagerUtil.registerDeviceType(deviceTypeName, tenantId + , provisioningConfig.isSharedWithAllTenants(), deviceTypeDefinition); registerPushNotificationStrategy(provider); registerMonitoringTask(provider); + //TODO: //This is a temporory fix. //windows and IOS cannot resolve user info by extracting certs //until fix that, use following variable to enable and disable of checking user authorization. DeviceManagementDataHolder.getInstance().setRequireDeviceAuthorization(provider.getType(), - provider.getDeviceManager() - .requireDeviceAuthorization()); + provider.getDeviceManager() + .requireDeviceAuthorization()); } catch (Throwable e) { /* Throwable is caught intentionally as failure of one plugin - due to invalid start up parameters, etc - should not block the initialization of other device management providers */ log.error("Error occurred while initializing device management provider '" + - provider.getType() + "'", e); + provider.getType() + "'", e); } } - this.isInited = true; + this.isInitiated = true; } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java index 0bc04e6e61..bf078a7b56 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java @@ -21,14 +21,22 @@ package org.wso2.carbon.device.mgt.core.app.mgt; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.device.mgt.common.*; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.InvalidDeviceException; +import org.wso2.carbon.device.mgt.common.TransactionManagementException; 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.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig; -import org.wso2.carbon.device.mgt.core.dao.*; +import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO; +import org.wso2.carbon.device.mgt.core.dao.ApplicationMappingDAO; +import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import java.sql.SQLException; @@ -114,7 +122,7 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem for (String user : userNameList) { userName = user; deviceList = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevicesOfUser - (user); + (user, false); for (Device device : deviceList) { deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(Integer.toString(device.getId())); @@ -156,7 +164,7 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem for (String role : userRoleList) { userRole = role; deviceList = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider() - .getAllDevicesOfRole(userRole); + .getAllDevicesOfRole(userRole, false); for (Device device : deviceList) { deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(Integer.toString(device.getId())); @@ -190,10 +198,9 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem List applications) throws ApplicationManagementException { List installedAppList = getApplicationListForDevice(deviceIdentifier); try { + Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier, + false); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - DeviceManagementDAOFactory.beginTransaction(); - Device device = deviceDAO.getDevice(deviceIdentifier, tenantId); - if (log.isDebugEnabled()) { log.debug("Device:" + device.getId() + ":identifier:" + deviceIdentifier.getId()); } @@ -212,6 +219,7 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem appIdsToRemove.add(installedApp.getId()); } } + DeviceManagementDAOFactory.beginTransaction(); applicationMappingDAO.removeApplicationMapping(device.getId(), appIdsToRemove, tenantId); Application installedApp; List applicationIds = new ArrayList<>(); @@ -247,6 +255,8 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem throw new ApplicationManagementException("Error occurred saving application list to the device", e); } catch (TransactionManagementException e) { throw new ApplicationManagementException("Error occurred while initializing transaction", e); + } catch (DeviceManagementException e) { + throw new ApplicationManagementException("Error occurred obtaining the device object.", e); } finally { DeviceManagementDAOFactory.closeConnection(); } @@ -255,27 +265,31 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem @Override public List getApplicationListForDevice( DeviceIdentifier deviceId) throws ApplicationManagementException { - Device device; + Device device = null; try { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - DeviceManagementDAOFactory.openConnection(); - device = deviceDAO.getDevice(deviceId, tenantId); - if (device == null) { - if (log.isDebugEnabled()) { - log.debug("No device is found upon the device identifier '" + deviceId.getId() + - "' and type '" + deviceId.getType() + "'. Therefore returning null"); - } - return null; + device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId, + false); + } catch (DeviceManagementException e) { + throw new ApplicationManagementException("Error occurred while fetching the device of '" + + deviceId.getType() + "' carrying the identifier'" + deviceId.getId(), e); + } + if (device == null) { + if (log.isDebugEnabled()) { + log.debug("No device is found upon the device identifier '" + deviceId.getId() + + "' and type '" + deviceId.getType() + "'. Therefore returning null"); } + return null; + } + try { + DeviceManagementDAOFactory.openConnection(); return applicationDAO.getInstalledApplications(device.getId()); } catch (DeviceManagementDAOException e) { throw new ApplicationManagementException("Error occurred while fetching the Application List of '" + deviceId.getType() + "' device carrying the identifier'" + deviceId.getId(), e); } catch (SQLException e) { throw new ApplicationManagementException("Error occurred while opening a connection to the data source", e); - } finally { + } finally { DeviceManagementDAOFactory.closeConnection(); } } - -} +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/DeviceCacheKey.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/DeviceCacheKey.java new file mode 100644 index 0000000000..79f3d7507c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/DeviceCacheKey.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.cache; + +import java.util.Objects; + +/** + * This represents a Key object used in DeviceCache. + */ +public class DeviceCacheKey { + + private String deviceId; + private String deviceType; + private int tenantId; + private volatile int hashCode; + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public String getDeviceType() { + return deviceType; + } + + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; + } + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!DeviceCacheKey.class.isAssignableFrom(obj.getClass())) { + return false; + } + final DeviceCacheKey other = (DeviceCacheKey) obj; + String thisId = this.deviceId + "-" + this.deviceType + "_" + this.tenantId; + String otherId = other.deviceId + "-" + other.deviceType + "_" + other.tenantId; + if (!thisId.equals(otherId)) { + return false; + } + return true; + } + + @Override + public int hashCode() { + if (hashCode == 0) { + hashCode = Objects.hash(deviceId, deviceType, tenantId); + } + return hashCode; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/DeviceCacheManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/DeviceCacheManager.java new file mode 100644 index 0000000000..9a3d3ee3f4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/DeviceCacheManager.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.cache; + +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.Device; + +import java.util.List; + +/** + * This defines the contract to be implemented by DeviceCacheManager which holds the necessary functionalities to + * manage a cache of Device objects. + */ +public interface DeviceCacheManager { + + /** + * Adds a given device object to the device-cache. + * @param deviceIdentifier - DeviceIdentifier of the device to be added. + * @param device - Device object to be added. + * @param tenantId - Owning tenant of the device. + * + */ + void addDeviceToCache(DeviceIdentifier deviceIdentifier, Device device, int tenantId); + + /** + * Removes a device object from device-cache. + * @param deviceIdentifier - DeviceIdentifier of the device to be removed. + * @param tenantId - Owning tenant of the device. + * + */ + void removeDeviceFromCache(DeviceIdentifier deviceIdentifier, int tenantId); + + /** + * Removes a list of devices from device-cache. + * @param deviceList - List of Cache-Keys of the device objects to be removed. + * + */ + void removeDevicesFromCache(List deviceList); + + /** + * Updates a given device object in the device-cache. + * @param deviceIdentifier - DeviceIdentifier of the device to be updated. + * @param device - Device object to be updated. + * @param tenantId - Owning tenant of the device. + * + */ + void updateDeviceInCache(DeviceIdentifier deviceIdentifier, Device device, int tenantId); + + /** + * Fetches a device object from device-cache. + * @param deviceIdentifier - DeviceIdentifier of the device to be fetched. + * @param tenantId - Owning tenant of the device. + * @return Device object + * + */ + Device getDeviceFromCache(DeviceIdentifier deviceIdentifier, int tenantId); +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/impl/DeviceCacheManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/impl/DeviceCacheManagerImpl.java new file mode 100644 index 0000000000..2bcd5e2797 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/impl/DeviceCacheManagerImpl.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.cache.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey; +import org.wso2.carbon.device.mgt.core.cache.DeviceCacheManager; +import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; + +import javax.cache.Cache; +import java.util.List; + +/** + * Implementation of DeviceCacheManager. + */ +public class DeviceCacheManagerImpl implements DeviceCacheManager { + + private static final Log log = LogFactory.getLog(DeviceCacheManagerImpl.class); + + private static DeviceCacheManagerImpl deviceCacheManager; + + private DeviceCacheManagerImpl() { + } + + public static DeviceCacheManagerImpl getInstance() { + if (deviceCacheManager == null) { + synchronized (DeviceCacheManagerImpl.class) { + if (deviceCacheManager == null) { + deviceCacheManager = new DeviceCacheManagerImpl(); + } + } + } + return deviceCacheManager; + } + + @Override + public void addDeviceToCache(DeviceIdentifier deviceIdentifier, Device device, int tenantId) { + Cache lCache = DeviceManagerUtil.getDeviceCache(); + if (lCache != null) { + DeviceCacheKey cacheKey = getCacheKey(deviceIdentifier, tenantId); + if (lCache.containsKey(cacheKey)) { + this.updateDeviceInCache(deviceIdentifier, device, tenantId); + } else { + lCache.put(cacheKey, device); + } + } + } + + @Override + public void removeDeviceFromCache(DeviceIdentifier deviceIdentifier, int tenantId) { + Cache lCache = DeviceManagerUtil.getDeviceCache(); + if (lCache != null) { + DeviceCacheKey cacheKey = getCacheKey(deviceIdentifier, tenantId); + if (lCache.containsKey(cacheKey)) { + lCache.remove(cacheKey); + } + } + } + + @Override + public void removeDevicesFromCache(List deviceList) { + Cache lCache = DeviceManagerUtil.getDeviceCache(); + if (lCache != null) { + for (DeviceCacheKey cacheKey : deviceList) { + if (lCache.containsKey(cacheKey)) { + lCache.remove(cacheKey); + } + } + } + } + + @Override + public void updateDeviceInCache(DeviceIdentifier deviceIdentifier, Device device, int tenantId) { + Cache lCache = DeviceManagerUtil.getDeviceCache(); + if (lCache != null) { + DeviceCacheKey cacheKey = getCacheKey(deviceIdentifier, tenantId); + if (lCache.containsKey(cacheKey)) { + lCache.replace(cacheKey, device); + } + } + } + + @Override + public Device getDeviceFromCache(DeviceIdentifier deviceIdentifier, int tenantId) { + Cache lCache = DeviceManagerUtil.getDeviceCache(); + if (lCache != null) { + return lCache.get(getCacheKey(deviceIdentifier, tenantId)); + } + return null; + } + + + private DeviceCacheKey getCacheKey(DeviceIdentifier deviceIdentifier, int tenantId) { + DeviceCacheKey deviceCacheKey = new DeviceCacheKey(); + deviceCacheKey.setDeviceId(deviceIdentifier.getId()); + deviceCacheKey.setDeviceType(deviceIdentifier.getType()); + deviceCacheKey.setTenantId(tenantId); + return deviceCacheKey; + } +} \ No newline at end of file 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 cc9a6256a6..5d757f4f0b 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 @@ -17,16 +17,18 @@ */ package org.wso2.carbon.device.mgt.core.config; +import org.wso2.carbon.device.mgt.core.config.geo.location.GeoLocationConfiguration; +import org.wso2.carbon.device.mgt.core.config.cache.DeviceCacheConfiguration; import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations; import org.wso2.carbon.device.mgt.core.config.pagination.PaginationConfiguration; import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; +import org.wso2.carbon.device.mgt.core.config.pull.notification.PullNotificationConfiguration; import org.wso2.carbon.device.mgt.core.config.push.notification.PushNotificationConfiguration; +import org.wso2.carbon.device.mgt.core.config.status.task.DeviceStatusTaskConfig; import org.wso2.carbon.device.mgt.core.config.task.TaskConfiguration; import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; /** * Represents Device Mgt configuration. @@ -41,7 +43,11 @@ public final class DeviceManagementConfig { private PolicyConfiguration policyConfiguration; private PaginationConfiguration paginationConfiguration; private PushNotificationConfiguration pushNotificationConfiguration; - + private PullNotificationConfiguration pullNotificationConfiguration; + private DeviceStatusTaskConfig deviceStatusTaskConfig; + private DeviceCacheConfiguration deviceCacheConfiguration; + private GeoLocationConfiguration geoLocationConfiguration; + private String defaultGroupsConfiguration; @XmlElement(name = "ManagementRepository", required = true) public DeviceManagementConfigRepository getDeviceManagementConfigRepository() { @@ -97,5 +103,50 @@ public final class DeviceManagementConfig { public void setPushNotificationConfiguration(PushNotificationConfiguration pushNotificationConfiguration) { this.pushNotificationConfiguration = pushNotificationConfiguration; } + + @XmlElement(name = "PullNotificationConfiguration", required = true) + public PullNotificationConfiguration getPullNotificationConfiguration() { + return pullNotificationConfiguration; + } + + public void setPullNotificationConfiguration(PullNotificationConfiguration pullNotificationConfiguration) { + this.pullNotificationConfiguration = pullNotificationConfiguration; + } + + @XmlElement(name = "DeviceStatusTaskConfig", required = true) + public DeviceStatusTaskConfig getDeviceStatusTaskConfig() { + return deviceStatusTaskConfig; + } + + public void setDeviceStatusTaskConfig(DeviceStatusTaskConfig deviceStatusTaskConfig) { + this.deviceStatusTaskConfig = deviceStatusTaskConfig; + } + + @XmlElement(name = "DeviceCacheConfiguration", required = true) + public DeviceCacheConfiguration getDeviceCacheConfiguration() { + return deviceCacheConfiguration; + } + + public void setDeviceCacheConfiguration(DeviceCacheConfiguration deviceCacheConfiguration) { + this.deviceCacheConfiguration = deviceCacheConfiguration; + } + + @XmlElement(name = "GeoLocationConfiguration", required = true) + public GeoLocationConfiguration getGeoLocationConfiguration() { + return geoLocationConfiguration; + } + + public void setGeoLocationConfiguration(GeoLocationConfiguration geoLocationConfiguration) { + this.geoLocationConfiguration = geoLocationConfiguration; + } + + @XmlElement(name = "DefaultGroupsConfiguration", required = true) + public String getDefaultGroupsConfiguration() { + return defaultGroupsConfiguration; + } + + public void setDefaultGroupsConfiguration(String defaultGroupsConfiguration) { + this.defaultGroupsConfiguration = defaultGroupsConfiguration; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/cache/DeviceCacheConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/cache/DeviceCacheConfiguration.java new file mode 100644 index 0000000000..34a813fbcf --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/cache/DeviceCacheConfiguration.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.config.cache; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "DeviceCacheConfiguration") +public class DeviceCacheConfiguration { + + private boolean isEnabled; + private int expiryTime; + + @XmlElement(name = "Enable", required = true) + public boolean isEnabled() { + return isEnabled; + } + + public void setEnabled(boolean enabled) { + isEnabled = enabled; + } + + @XmlElement(name = "ExpiryTime", required = true) + public int getExpiryTime() { + return expiryTime; + } + + public void setExpiryTime(int expiryTime) { + this.expiryTime = expiryTime; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/geo/location/GeoLocationConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/geo/location/GeoLocationConfiguration.java new file mode 100644 index 0000000000..e1aeb1a45c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/geo/location/GeoLocationConfiguration.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.config.geo.location; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * This class represents the information related to Geo Location configuration. + */ +@XmlRootElement(name = "GeoLocationConfiguration") +public class GeoLocationConfiguration { + + private boolean publishLocationOperationResponse; + private boolean isEnabled; + + public boolean getPublishLocationOperationResponse() { + return publishLocationOperationResponse; + } + + @XmlElement(name = "PublishLocationOperationResponse", required = true) + public void setPublishLocationOperationResponse(boolean publishLocationOperationResponse) { + this.publishLocationOperationResponse = publishLocationOperationResponse; + } + + public boolean getIsEnabled() { + return isEnabled; + } + + @XmlElement(name = "isEnabled", required = true) + public void setEnabled(boolean enabled) { + isEnabled = enabled; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pull/notification/PullNotificationConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pull/notification/PullNotificationConfiguration.java new file mode 100644 index 0000000000..4298987df7 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pull/notification/PullNotificationConfiguration.java @@ -0,0 +1,40 @@ +/* +* Copyright (c) 2017, 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. +*/ +package org.wso2.carbon.device.mgt.core.config.pull.notification; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * This class is for Pull notification related Configurations + */ +@XmlRootElement(name = "PullNotificationConfiguration") +public class PullNotificationConfiguration { + + private boolean enabled; + + @XmlElement(name = "Enabled", required = true) + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/status/task/DeviceStatusTaskConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/status/task/DeviceStatusTaskConfig.java new file mode 100644 index 0000000000..03cf0643a1 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/status/task/DeviceStatusTaskConfig.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.config.status.task; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "DeviceStatusTaskConfig") +public class DeviceStatusTaskConfig { + + private boolean enabled; + + @XmlElement(name = "Enable", required = true) + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index 1eb39fc502..f6a0a363b4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -158,7 +158,7 @@ public interface DeviceDAO { HashMap getDevice(DeviceIdentifier deviceIdentifier) throws DeviceManagementDAOException; /** - * This method is used to retrieve a device of a given id. + * This method is used to retrieve a device of a given tenant id. * * @param deviceId device id. * @param tenantId tenant id. @@ -420,5 +420,7 @@ public interface DeviceDAO { */ List getEnrolmentsByStatus(List deviceIds, Status status, int tenantId) throws DeviceManagementDAOException; + + List getDeviceEnrolledTenants() throws DeviceManagementDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceTypeDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceTypeDAO.java index 0e34fc1ab0..337a5af133 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceTypeDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceTypeDAO.java @@ -55,7 +55,7 @@ public interface DeviceTypeDAO { * @return return only the device types that are associated with the provider tenant. * @throws DeviceManagementDAOException */ - List getDeviceTypesByProvider(int tenantId) throws DeviceManagementDAOException; + List getDeviceTypesByProvider(int tenantId) throws DeviceManagementDAOException; /** * @return sharedWithAllDeviceTypes This returns public shared device types. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java index d59d5733f4..21cc243abe 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java @@ -32,11 +32,17 @@ public interface EnrollmentDAO { int updateEnrollment(EnrolmentInfo enrolmentInfo) throws DeviceManagementDAOException; + boolean updateEnrollmentStatus(List enrolmentInfos) throws DeviceManagementDAOException; + int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException; boolean setStatus(int enrolmentId, String currentOwner, Status status, int tenantId) throws DeviceManagementDAOException; + boolean setStatus(String currentOwner, Status status, int tenantId) throws DeviceManagementDAOException; + + boolean setStatus(int enrolmentId, Status status, int tenantId) throws DeviceManagementDAOException; + Status getStatus(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException; EnrolmentInfo getEnrollment(int deviceId, String currentUser, int tenantId) throws DeviceManagementDAOException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/GroupManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/GroupManagementDAOFactory.java index 3626c34b19..a962f91773 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/GroupManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/GroupManagementDAOFactory.java @@ -20,11 +20,16 @@ package org.wso2.carbon.device.mgt.core.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException; import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.device.mgt.common.UnsupportedDatabaseEngineException; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; -import org.wso2.carbon.device.mgt.core.dao.impl.GroupDAOImpl; +import org.wso2.carbon.device.mgt.core.dao.impl.group.GenericGroupDAOImpl; +import org.wso2.carbon.device.mgt.core.dao.impl.group.OracleGroupDAOImpl; +import org.wso2.carbon.device.mgt.core.dao.impl.group.PostgreSQLGroupDAOImpl; +import org.wso2.carbon.device.mgt.core.dao.impl.group.SQLServerGroupDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.GroupManagementDAOUtil; import javax.sql.DataSource; @@ -40,6 +45,7 @@ public class GroupManagementDAOFactory { private static final Log log = LogFactory.getLog(GroupManagementDAOFactory.class); private static DataSource dataSource; + private static String databaseEngine; private static ThreadLocal currentConnection = new ThreadLocal<>(); /** @@ -48,25 +54,40 @@ public class GroupManagementDAOFactory { * @return instance of GroupDAO implementation */ public static GroupDAO getGroupDAO() { - return new GroupDAOImpl(); + if (databaseEngine != null) { + switch (databaseEngine) { + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE: + return new OracleGroupDAOImpl(); + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL: + return new SQLServerGroupDAOImpl(); + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new PostgreSQLGroupDAOImpl(); + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL: + return new GenericGroupDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); } - /** - * Initialize factory with datasource configs - * - * @param config data source configuration - */ 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); + } } - /** - * Initialize factory with existing datasource - * - * @param dtSource an existing datasource - */ 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); + } } /** @@ -129,8 +150,8 @@ public class GroupManagementDAOFactory { 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"); + "This might have ideally been caused by not properly initiating " + + "the transaction via 'beginTransaction'/'openConnection' methods"); } try { conn.commit(); @@ -146,8 +167,8 @@ public class GroupManagementDAOFactory { 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"); + "This might have ideally been caused by not properly initiating " + + "the transaction via 'beginTransaction'/'openConnection' methods"); } try { conn.rollback(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 085b3f35d6..3bab9aceed 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -121,7 +121,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + - "t.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + + "t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + "AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceIdentifier.getType()); @@ -154,8 +154,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_DETAIL dt " + - "WHERE t.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " + - "AND dt.UPDATE_TIMESTAMP > ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?" ; + "WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " + + "AND dt.UPDATE_TIMESTAMP > ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC" ; stmt = conn.prepareStatement(sql); int paramIdx = 1; stmt.setString(paramIdx++, deviceIdentifier.getType()); @@ -189,8 +189,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + - "t.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + - "AND TENANT_ID = ? AND e.STATUS = ?"; + "t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + + "AND TENANT_ID = ? AND e.STATUS = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceIdentifier.getType()); stmt.setString(2, deviceIdentifier.getId()); @@ -223,7 +223,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + - "t.NAME = ? AND d.DEVICE_IDENTIFICATION = ? ) d1 WHERE d1.ID = e.DEVICE_ID ORDER BY e.DATE_OF_LAST_UPDATE DESC"; + "t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? ) d1 WHERE d1.ID = e.DEVICE_ID ORDER BY e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceIdentifier.getType()); stmt.setString(2, deviceIdentifier.getId()); @@ -253,7 +253,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + - "d.ID = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + + "d.ID = ? AND t.ID = d.DEVICE_TYPE_ID AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + "AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); stmt.setInt(1, deviceId); @@ -285,7 +285,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, " + "d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " + - "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; + "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setInt(2, tenantId); @@ -317,7 +317,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + - "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; + "AND t.ID = d.DEVICE_TYPE_ID AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?" + + " ORDER BY e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); stmt.setString(1, type); stmt.setInt(2, tenantId); @@ -350,7 +351,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + - "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "e.TENANT_ID = ? AND LOWER(e.OWNER) = LOWER(?) ORDER BY e.DATE_OF_LAST_UPDATE DESC) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + "AND t.ID = d.DEVICE_TYPE_ID"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -383,7 +384,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + - "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "e.TENANT_ID = ? AND LOWER(e.OWNER) = LOWER(?) ORDER BY e.DATE_OF_LAST_UPDATE DESC) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + "AND t.ID = d.DEVICE_TYPE_ID AND t.NAME= ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -424,7 +425,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { conn = this.getConnection(); String sql = "SELECT COUNT(d1.DEVICE_ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID FROM " + "DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 WHERE " + - "d1.DEVICE_ID = e.DEVICE_ID AND e.OWNER = ? AND TENANT_ID = ?"; + "d1.DEVICE_ID = e.DEVICE_ID AND LOWER(e.OWNER) = LOWER(?) AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, username); @@ -485,6 +486,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { boolean isDeviceNameProvided = false; String owner = request.getOwner(); boolean isOwnerProvided = false; + String ownerPattern = request.getOwnerPattern(); + boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; String status = request.getStatus(); @@ -523,9 +526,13 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { isOwnershipProvided = true; } + //Add the query for owner if (owner != null && !owner.isEmpty()) { - sql = sql + " AND e.OWNER LIKE ?"; + sql = sql + " AND e.OWNER = ?"; isOwnerProvided = true; + } else if (ownerPattern != null && !ownerPattern.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerPatternProvided = true; } if (status != null && !status.isEmpty()) { @@ -551,7 +558,9 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { stmt.setString(paramIdx++, request.getOwnership()); } if (isOwnerProvided) { - stmt.setString(paramIdx++, request.getOwner() + "%"); + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); } if (isStatusProvided) { stmt.setString(paramIdx++, request.getStatus()); @@ -604,7 +613,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT COUNT(e1.DEVICE_ID) AS DEVICE_COUNT FROM DM_DEVICE d, (SELECT e.DEVICE_ID " + - "FROM DM_ENROLMENT e WHERE e.TENANT_ID = ? AND e.OWNER = ?) " + + "FROM DM_ENROLMENT e WHERE e.TENANT_ID = ? AND LOWER(e.OWNER) = LOWER(?)) " + "e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID AND t.ID = d.DEVICE_TYPE_ID"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -1063,4 +1072,27 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { return devices; } + + public List getDeviceEnrolledTenants() throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List tenants = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT distinct(TENANT_ID) FROM DM_DEVICE"; + stmt = conn.prepareStatement(sql); + rs = stmt.executeQuery(); + while (rs.next()) { + tenants.add(rs.getInt("TENANT_ID")); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving tenants which have " + + "device registered.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return tenants; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java similarity index 76% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GroupDAOImpl.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java index 7d9947a421..bd672aabd7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java @@ -18,13 +18,11 @@ package org.wso2.carbon.device.mgt.core.dao.impl; -import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.core.dao.GroupDAO; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; -import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.GroupManagementDAOUtil; import java.sql.Connection; @@ -37,7 +35,7 @@ import java.util.List; /** * This class represents implementation of GroupDAO */ -public class GroupDAOImpl implements GroupDAO { +public abstract class AbstractGroupDAOImpl implements GroupDAO { @Override public int addGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException { @@ -47,7 +45,7 @@ public class GroupDAOImpl implements GroupDAO { try { Connection conn = GroupManagementDAOFactory.getConnection(); String sql = "INSERT INTO DM_GROUP(DESCRIPTION, GROUP_NAME, OWNER, TENANT_ID) VALUES (?, ?, ?, ?)"; - stmt = conn.prepareStatement(sql, new String[]{"ID"}); + stmt = conn.prepareStatement(sql, new String[]{"id"}); stmt.setString(1, deviceGroup.getDescription()); stmt.setString(2, deviceGroup.getName()); stmt.setString(3, deviceGroup.getOwner()); @@ -60,7 +58,7 @@ public class GroupDAOImpl implements GroupDAO { return groupId; } catch (SQLException e) { throw new GroupManagementDAOException("Error occurred while adding deviceGroup '" + - deviceGroup.getName() + "'", e); + deviceGroup.getName() + "'", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, null); } @@ -83,7 +81,7 @@ public class GroupDAOImpl implements GroupDAO { stmt.executeUpdate(); } catch (SQLException e) { throw new GroupManagementDAOException("Error occurred while updating deviceGroup '" + - deviceGroup.getName() + "'", e); + deviceGroup.getName() + "'", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, null); } @@ -148,7 +146,7 @@ public class GroupDAOImpl implements GroupDAO { } } catch (SQLException e) { throw new GroupManagementDAOException("Error occurred while obtaining information of Device Group '" + - groupId + "'", e); + groupId + "'", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, resultSet); } @@ -179,126 +177,6 @@ public class GroupDAOImpl implements GroupDAO { return deviceGroupBuilders; } - @Override - public List getGroups(GroupPaginationRequest request, int tenantId) - throws GroupManagementDAOException { - PreparedStatement stmt = null; - ResultSet resultSet = null; - List deviceGroupList = null; - - String groupName = request.getGroupName(); - boolean hasGroupName = false; - String owner = request.getOwner(); - boolean hasOwner = false; - boolean hasLimit = request.getRowCount() != 0; - - try { - Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE TENANT_ID = ?"; - if (groupName != null && !groupName.isEmpty()) { - sql += " AND GROUP_NAME LIKE ?"; - hasGroupName = true; - } - if (owner != null && !owner.isEmpty()) { - sql += " AND OWNER LIKE ?"; - hasOwner = true; - } - if (hasLimit) { - sql += " LIMIT ?, ?"; - } - - int paramIndex = 1; - stmt = conn.prepareStatement(sql); - stmt.setInt(paramIndex++, tenantId); - if (hasGroupName) { - stmt.setString(paramIndex++, groupName + "%"); - } - if (hasOwner) { - stmt.setString(paramIndex++, owner + "%"); - } - if (hasLimit) { - stmt.setInt(paramIndex++, request.getStartIndex()); - stmt.setInt(paramIndex, request.getRowCount()); - } - resultSet = stmt.executeQuery(); - deviceGroupList = new ArrayList<>(); - while (resultSet.next()) { - deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet)); - } - } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e); - } finally { - GroupManagementDAOUtil.cleanupResources(stmt, resultSet); - } - return deviceGroupList; - } - - @Override - public List getGroups(GroupPaginationRequest request, List deviceGroupIds, - int tenantId) throws GroupManagementDAOException { - int deviceGroupIdsCount = deviceGroupIds.size(); - if (deviceGroupIdsCount == 0) { - return new ArrayList<>(); - } - PreparedStatement stmt = null; - ResultSet resultSet = null; - List deviceGroupList = null; - - String groupName = request.getGroupName(); - boolean hasGroupName = false; - String owner = request.getOwner(); - boolean hasOwner = false; - boolean hasLimit = request.getRowCount() != 0; - - try { - Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE TENANT_ID = ?"; - if (groupName != null && !groupName.isEmpty()) { - sql += " AND GROUP_NAME LIKE ?"; - hasGroupName = true; - } - if (owner != null && !owner.isEmpty()) { - sql += " AND OWNER LIKE ?"; - hasOwner = true; - } - sql += " AND ID IN ("; - for (int i = 0; i < deviceGroupIdsCount; i++) { - sql += (deviceGroupIdsCount - 1 != i) ? "?," : "?"; - } - sql += ")"; - if (hasLimit) { - sql += " LIMIT ?, ?"; - } - - int paramIndex = 1; - stmt = conn.prepareStatement(sql); - stmt.setInt(paramIndex++, tenantId); - if (hasGroupName) { - stmt.setString(paramIndex++, groupName + "%"); - } - if (hasOwner) { - stmt.setString(paramIndex++, owner + "%"); - } - for (Integer deviceGroupId : deviceGroupIds) { - stmt.setInt(paramIndex++, deviceGroupId); - } - if (hasLimit) { - stmt.setInt(paramIndex++, request.getStartIndex()); - stmt.setInt(paramIndex, request.getRowCount()); - } - resultSet = stmt.executeQuery(); - deviceGroupList = new ArrayList<>(); - while (resultSet.next()) { - deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet)); - } - } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e); - } finally { - GroupManagementDAOUtil.cleanupResources(stmt, resultSet); - } - return deviceGroupList; - } - @Override public List getGroups(int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; @@ -495,49 +373,6 @@ public class GroupDAOImpl implements GroupDAO { } } - @Override - public List getDevices(int groupId, int startIndex, int rowCount, int tenantId) - throws GroupManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List devices = null; - try { - conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + - "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + - "FROM " + - "(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM" + - " DM_DEVICE d, (" + - "SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 " + - "WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t " + - "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? , ?"; - - stmt = conn.prepareStatement(sql); - stmt.setInt(1, groupId); - stmt.setInt(2, tenantId); - stmt.setInt(3, tenantId); - //noinspection JpaQueryApiInspection - stmt.setInt(4, startIndex); - //noinspection JpaQueryApiInspection - stmt.setInt(5, rowCount); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); - } - } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while retrieving information of all " + - "registered devices", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return devices; - } - @Override public List getRoles(int groupId, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; @@ -728,7 +563,7 @@ public class GroupDAOImpl implements GroupDAO { } } catch (SQLException e) { throw new GroupManagementDAOException("Error occurred while getting own groups of user '" - + username + "'", e); + + username + "'", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, resultSet); } @@ -753,7 +588,7 @@ public class GroupDAOImpl implements GroupDAO { } } catch (SQLException e) { throw new GroupManagementDAOException("Error occurred while getting own groups of user '" - + username + "'", e); + + username + "'", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, resultSet); } @@ -778,7 +613,7 @@ public class GroupDAOImpl implements GroupDAO { } } catch (SQLException e) { throw new GroupManagementDAOException("Error occurred while getting own groups count of user '" - + username + "'", e); + + username + "'", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, resultSet); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java index c7e4952328..a4ecacfd3a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java @@ -17,6 +17,8 @@ */ package org.wso2.carbon.device.mgt.core.dao.impl; +import com.google.gson.Gson; +import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; @@ -27,7 +29,9 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Timestamp; import java.util.ArrayList; +import java.util.Date; import java.util.List; public class DeviceTypeDAOImpl implements DeviceTypeDAO { @@ -40,10 +44,18 @@ public class DeviceTypeDAOImpl implements DeviceTypeDAO { try { conn = this.getConnection(); stmt = conn.prepareStatement( - "INSERT INTO DM_DEVICE_TYPE (NAME,PROVIDER_TENANT_ID,SHARED_WITH_ALL_TENANTS) VALUES (?,?,?)"); + "INSERT INTO DM_DEVICE_TYPE (NAME,PROVIDER_TENANT_ID,SHARED_WITH_ALL_TENANTS,DEVICE_TYPE_META" + + ",LAST_UPDATED_TIMESTAMP) VALUES (?,?,?,?,?)"); stmt.setString(1, deviceType.getName()); stmt.setInt(2, providerTenantId); stmt.setBoolean(3, isSharedWithAllTenants); + String deviceMeta = null; + if (deviceType.getDeviceTypeMetaDefinition() != null) { + Gson gson = new Gson(); + deviceMeta = gson.toJson(deviceType.getDeviceTypeMetaDefinition()); + } + stmt.setString(4, deviceMeta); + stmt.setTimestamp(5, new Timestamp(new Date().getTime())); stmt.execute(); } catch (SQLException e) { throw new DeviceManagementDAOException( @@ -54,8 +66,29 @@ public class DeviceTypeDAOImpl implements DeviceTypeDAO { } @Override - public void updateDeviceType(DeviceType deviceType, int tenantId) - throws DeviceManagementDAOException { + public void updateDeviceType(DeviceType deviceType, int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + stmt = conn.prepareStatement("UPDATE DM_DEVICE_TYPE SET DEVICE_TYPE_META = ?, LAST_UPDATED_TIMESTAMP = ? " + + "WHERE NAME = ? AND PROVIDER_TENANT_ID = ?"); + String deviceMeta = null; + if (deviceType.getDeviceTypeMetaDefinition() != null) { + Gson gson = new Gson(); + deviceMeta = gson.toJson(deviceType.getDeviceTypeMetaDefinition()); + } + stmt.setString(1, deviceMeta); + stmt.setTimestamp(2, new Timestamp(new Date().getTime())); + stmt.setString(3, deviceType.getName()); + stmt.setInt(4, tenantId); + stmt.execute(); + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while updating device type'" + + deviceType.getName() + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } } @Override @@ -67,8 +100,8 @@ public class DeviceTypeDAOImpl implements DeviceTypeDAO { try { conn = this.getConnection(); String sql = - "SELECT ID AS DEVICE_TYPE_ID, NAME AS DEVICE_TYPE FROM DM_DEVICE_TYPE where PROVIDER_TENANT_ID =" + - "? OR SHARED_WITH_ALL_TENANTS = ?"; + "SELECT ID AS DEVICE_TYPE_ID, NAME AS DEVICE_TYPE, DEVICE_TYPE_META,LAST_UPDATED_TIMESTAMP " + + "FROM DM_DEVICE_TYPE where PROVIDER_TENANT_ID =? OR SHARED_WITH_ALL_TENANTS = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setBoolean(2, true); @@ -78,6 +111,12 @@ public class DeviceTypeDAOImpl implements DeviceTypeDAO { DeviceType deviceType = new DeviceType(); deviceType.setId(rs.getInt("DEVICE_TYPE_ID")); deviceType.setName(rs.getString("DEVICE_TYPE")); + String devicetypeMeta = rs.getString("DEVICE_TYPE_META"); + if (devicetypeMeta != null && devicetypeMeta.length() > 0) { + Gson gson = new Gson(); + deviceType.setDeviceTypeMetaDefinition(gson.fromJson(devicetypeMeta + , DeviceTypeMetaDefinition.class)); + } deviceTypes.add(deviceType); } return deviceTypes; @@ -89,21 +128,30 @@ public class DeviceTypeDAOImpl implements DeviceTypeDAO { } @Override - public List getDeviceTypesByProvider(int tenantId) throws DeviceManagementDAOException { + public List getDeviceTypesByProvider(int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; - List deviceTypes = new ArrayList<>(); + List deviceTypes = new ArrayList<>(); try { conn = this.getConnection(); String sql = - "SELECT NAME AS DEVICE_TYPE FROM DM_DEVICE_TYPE where PROVIDER_TENANT_ID =?"; + "SELECT NAME AS DEVICE_TYPE, DEVICE_TYPE_META FROM DM_DEVICE_TYPE where PROVIDER_TENANT_ID =?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); rs = stmt.executeQuery(); while (rs.next()) { - deviceTypes.add(rs.getString("DEVICE_TYPE")); + DeviceType deviceType = new DeviceType(); + deviceType.setName(rs.getString("DEVICE_TYPE")); + String devicetypeMeta = rs.getString("DEVICE_TYPE_META"); + if (devicetypeMeta != null && devicetypeMeta.length() > 0) { + Gson gson = new Gson(); + deviceType.setDeviceTypeMetaDefinition(gson.fromJson(devicetypeMeta + , DeviceTypeMetaDefinition.class)); + } + deviceTypes.add(deviceType); + } return deviceTypes; } catch (SQLException e) { @@ -146,7 +194,7 @@ public class DeviceTypeDAOImpl implements DeviceTypeDAO { ResultSet rs = null; try { conn = this.getConnection(); - String sql = "SELECT ID AS DEVICE_TYPE_ID, NAME AS DEVICE_TYPE FROM DM_DEVICE_TYPE WHERE ID = ?"; + String sql = "SELECT ID AS DEVICE_TYPE_ID, DEVICE_TYPE_META, NAME AS DEVICE_TYPE FROM DM_DEVICE_TYPE WHERE ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); @@ -155,6 +203,13 @@ public class DeviceTypeDAOImpl implements DeviceTypeDAO { deviceType = new DeviceType(); deviceType.setId(rs.getInt("DEVICE_TYPE_ID")); deviceType.setName(rs.getString("DEVICE_TYPE")); + String devicetypeMeta = rs.getString("DEVICE_TYPE_META"); + if (devicetypeMeta != null && devicetypeMeta.length() > 0) { + Gson gson = new Gson(); + deviceType.setDeviceTypeMetaDefinition(gson.fromJson(devicetypeMeta + , DeviceTypeMetaDefinition.class)); + } + } return deviceType; } catch (SQLException e) { @@ -174,7 +229,7 @@ public class DeviceTypeDAOImpl implements DeviceTypeDAO { DeviceType deviceType = null; try { conn = this.getConnection(); - String sql = "SELECT ID AS DEVICE_TYPE_ID FROM DM_DEVICE_TYPE WHERE (PROVIDER_TENANT_ID =? OR " + + String sql = "SELECT ID AS DEVICE_TYPE_ID, DEVICE_TYPE_META FROM DM_DEVICE_TYPE WHERE (PROVIDER_TENANT_ID =? OR " + "SHARED_WITH_ALL_TENANTS = ?) AND NAME =?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -185,6 +240,12 @@ public class DeviceTypeDAOImpl implements DeviceTypeDAO { deviceType = new DeviceType(); deviceType.setId(rs.getInt("DEVICE_TYPE_ID")); deviceType.setName(type); + String devicetypeMeta = rs.getString("DEVICE_TYPE_META"); + if (devicetypeMeta != null && devicetypeMeta.length() > 0) { + Gson gson = new Gson(); + deviceType.setDeviceTypeMetaDefinition(gson.fromJson(devicetypeMeta + , DeviceTypeMetaDefinition.class)); + } } return deviceType; } catch (SQLException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java index 9e8bd4680a..33371e3c9d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java @@ -23,6 +23,7 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping; import java.sql.*; import java.util.ArrayList; @@ -70,7 +71,6 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; - int status = -1; try { conn = this.getConnection(); String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, DATE_OF_LAST_UPDATE = ? WHERE DEVICE_ID = ?" + @@ -83,7 +83,7 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { stmt.setString(5, enrolmentInfo.getOwner()); stmt.setInt(6, tenantId); stmt.setInt(7, enrolmentInfo.getId()); - stmt.executeUpdate(); + int status = stmt.executeUpdate(); return status; } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e); @@ -97,7 +97,6 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; - int status = -1; try { conn = this.getConnection(); String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, DATE_OF_LAST_UPDATE = ? WHERE ID = ?"; @@ -106,7 +105,7 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { stmt.setString(2, enrolmentInfo.getStatus().toString()); stmt.setTimestamp(3, new Timestamp(new Date().getTime())); stmt.setInt(4, enrolmentInfo.getId()); - stmt.executeUpdate(); + int status = stmt.executeUpdate(); return status; } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e); @@ -115,6 +114,42 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { } } + @Override + public boolean updateEnrollmentStatus(List enrolmentInfos) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + boolean status = false; + int updateStatus = -1; + try { + conn = this.getConnection(); + String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE ID = ?"; + stmt = conn.prepareStatement(sql); + if (conn.getMetaData().supportsBatchUpdates()) { + for (EnrolmentInfo enrolmentInfo : enrolmentInfos) { + stmt.setString(1, enrolmentInfo.getStatus().toString()); + stmt.setInt(2, enrolmentInfo.getId()); + stmt.addBatch(); + } + updateStatus = stmt.executeBatch().length; + } else { + for (EnrolmentInfo enrolmentInfo : enrolmentInfos) { + stmt.setString(1, enrolmentInfo.getStatus().toString()); + stmt.setInt(2, enrolmentInfo.getId()); + updateStatus = stmt.executeUpdate(); + } + } + if (updateStatus > 0) { + status = true; + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while updating enrolment status of given device-list.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return status; + } + @Override public int removeEnrollment(int deviceId, String currentOwner, @@ -166,6 +201,47 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { return true; } + @Override + public boolean setStatus(String currentOwner, EnrolmentInfo.Status status, + int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE OWNER = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, status.toString()); + stmt.setString(2, currentOwner); + stmt.setInt(3, tenantId); + stmt.executeUpdate(); + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return true; + } + + @Override + public boolean setStatus(int enrolmentID, EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, status.toString()); + stmt.setInt(2, enrolmentID); + stmt.setInt(3, tenantId); + stmt.executeUpdate(); + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return true; + } + @Override public EnrolmentInfo.Status getStatus(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index b60072be2a..353eaedb38 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -48,6 +48,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isDeviceNameProvided = false; String owner = request.getOwner(); boolean isOwnerProvided = false; + String ownerPattern = request.getOwnerPattern(); + boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; String status = request.getStatus(); @@ -95,8 +97,11 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } //Add the query for owner if (owner != null && !owner.isEmpty()) { - sql = sql + " AND e.OWNER LIKE ?"; + sql = sql + " AND e.OWNER = ?"; isOwnerProvided = true; + } else if (ownerPattern != null && !ownerPattern.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerPatternProvided = true; } //Add the query for status if (status != null && !status.isEmpty()) { @@ -113,21 +118,23 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setLong(paramIdx++, since.getTime()); } if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, request.getDeviceType()); + stmt.setString(paramIdx++, deviceType); } if (isDeviceNameProvided) { - stmt.setString(paramIdx++, request.getDeviceName() + "%"); + stmt.setString(paramIdx++, deviceName + "%"); } stmt.setInt(paramIdx++, tenantId); if (isOwnershipProvided) { - stmt.setString(paramIdx++, request.getOwnership()); + stmt.setString(paramIdx++, ownership); } if (isOwnerProvided) { - stmt.setString(paramIdx++, request.getOwner() + "%"); + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); } if (isStatusProvided) { - stmt.setString(paramIdx++, request.getStatus()); + stmt.setString(paramIdx++, status); } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx, request.getRowCount()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index a1773f505f..2f96e94d00 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -54,6 +54,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isDeviceNameProvided = false; String owner = request.getOwner(); boolean isOwnerProvided = false; + String ownerPattern = request.getOwnerPattern(); + boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; String status = request.getStatus(); @@ -101,8 +103,11 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } //Add the query for owner if (owner != null && !owner.isEmpty()) { - sql = sql + " AND e.OWNER LIKE ?"; + sql = sql + " AND e.OWNER = ?"; isOwnerProvided = true; + } else if (ownerPattern != null && !ownerPattern.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerPatternProvided = true; } //Add the query for status if (status != null && !status.isEmpty()) { @@ -119,20 +124,23 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setLong(paramIdx++, since.getTime()); } if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, request.getDeviceType()); + stmt.setString(paramIdx++, deviceType); } if (isDeviceNameProvided) { - stmt.setString(paramIdx++, request.getDeviceName() + "%"); + stmt.setString(paramIdx++, deviceName + "%"); } + stmt.setInt(paramIdx++, tenantId); if (isOwnershipProvided) { - stmt.setString(paramIdx++, request.getOwnership()); + stmt.setString(paramIdx++, ownership); } if (isOwnerProvided) { - stmt.setString(paramIdx++, request.getOwner() + "%"); + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); } if (isStatusProvided) { - stmt.setString(paramIdx++, request.getStatus()); + stmt.setString(paramIdx++, status); } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx, request.getRowCount()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index 2651916025..8578892885 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -51,6 +51,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isDeviceNameProvided = false; String owner = request.getOwner(); boolean isOwnerProvided = false; + String ownerPattern = request.getOwnerPattern(); + boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; String status = request.getStatus(); @@ -85,8 +87,11 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } //Add the query for owner if (owner != null && !owner.isEmpty()) { - sql = sql + " AND e.OWNER LIKE ?"; + sql = sql + " AND e.OWNER = ?"; isOwnerProvided = true; + } else if (ownerPattern != null && !ownerPattern.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerPatternProvided = true; } //Add the query for status if (status != null && !status.isEmpty()) { @@ -100,20 +105,23 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setInt(1, tenantId); int paramIdx = 2; if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, request.getDeviceType()); + stmt.setString(paramIdx++, deviceType); } if (isDeviceNameProvided) { - stmt.setString(paramIdx++, request.getDeviceName() + "%"); + stmt.setString(paramIdx++, deviceName + "%"); } + stmt.setInt(paramIdx++, tenantId); if (isOwnershipProvided) { - stmt.setString(paramIdx++, request.getOwnership()); + stmt.setString(paramIdx++, ownership); } if (isOwnerProvided) { - stmt.setString(paramIdx++, request.getOwner() + "%"); + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); } if (isStatusProvided) { - stmt.setString(paramIdx++, request.getStatus()); + stmt.setString(paramIdx++, status); } stmt.setInt(paramIdx++, request.getRowCount()); stmt.setInt(paramIdx, request.getStartIndex()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index fe942787f8..c1b4dc0529 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -51,6 +51,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isDeviceNameProvided = false; String owner = request.getOwner(); boolean isOwnerProvided = false; + String ownerPattern = request.getOwnerPattern(); + boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; String status = request.getStatus(); @@ -98,8 +100,11 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } //Add the query for owner if (owner != null && !owner.isEmpty()) { - sql = sql + " AND e.OWNER LIKE ?"; + sql = sql + " AND e.OWNER = ?"; isOwnerProvided = true; + } else if (ownerPattern != null && !ownerPattern.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerPatternProvided = true; } //Add the query for status if (status != null && !status.isEmpty()) { @@ -116,20 +121,23 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setLong(paramIdx++, since.getTime()); } if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, request.getDeviceType()); + stmt.setString(paramIdx++, deviceType); } if (isDeviceNameProvided) { - stmt.setString(paramIdx++, request.getDeviceName() + "%"); + stmt.setString(paramIdx++, deviceName + "%"); } + stmt.setInt(paramIdx++, tenantId); if (isOwnershipProvided) { - stmt.setString(paramIdx++, request.getOwnership()); + stmt.setString(paramIdx++, ownership); } if (isOwnerProvided) { - stmt.setString(paramIdx++, request.getOwner() + "%"); + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); } if (isStatusProvided) { - stmt.setString(paramIdx++, request.getStatus()); + stmt.setString(paramIdx++, status); } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx, request.getRowCount()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/GenericGroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/GenericGroupDAOImpl.java new file mode 100644 index 0000000000..7ad8b9981e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/GenericGroupDAOImpl.java @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.dao.impl.group; + +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOException; +import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.impl.AbstractGroupDAOImpl; +import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.dao.util.GroupManagementDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class represents implementation of GroupDAO + */ +public class GenericGroupDAOImpl extends AbstractGroupDAOImpl { + + @Override + public List getGroups(GroupPaginationRequest request, int tenantId) + throws GroupManagementDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + List deviceGroupList = null; + + String groupName = request.getGroupName(); + boolean hasGroupName = false; + String owner = request.getOwner(); + boolean hasOwner = false; + boolean hasLimit = request.getRowCount() != 0; + + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE TENANT_ID = ?"; + if (groupName != null && !groupName.isEmpty()) { + sql += " AND GROUP_NAME LIKE ?"; + hasGroupName = true; + } + if (owner != null && !owner.isEmpty()) { + sql += " AND OWNER LIKE ?"; + hasOwner = true; + } + if (hasLimit) { + sql += " LIMIT ?, ?"; + } + + int paramIndex = 1; + stmt = conn.prepareStatement(sql); + stmt.setInt(paramIndex++, tenantId); + if (hasGroupName) { + stmt.setString(paramIndex++, groupName + "%"); + } + if (hasOwner) { + stmt.setString(paramIndex++, owner + "%"); + } + if (hasLimit) { + stmt.setInt(paramIndex++, request.getStartIndex()); + stmt.setInt(paramIndex, request.getRowCount()); + } + resultSet = stmt.executeQuery(); + deviceGroupList = new ArrayList<>(); + while (resultSet.next()) { + deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet)); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return deviceGroupList; + } + + @Override + public List getGroups(GroupPaginationRequest request, List deviceGroupIds, + int tenantId) throws GroupManagementDAOException { + int deviceGroupIdsCount = deviceGroupIds.size(); + if (deviceGroupIdsCount == 0) { + return new ArrayList<>(); + } + PreparedStatement stmt = null; + ResultSet resultSet = null; + List deviceGroupList = null; + + String groupName = request.getGroupName(); + boolean hasGroupName = false; + String owner = request.getOwner(); + boolean hasOwner = false; + boolean hasLimit = request.getRowCount() != 0; + + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE TENANT_ID = ?"; + if (groupName != null && !groupName.isEmpty()) { + sql += " AND GROUP_NAME LIKE ?"; + hasGroupName = true; + } + if (owner != null && !owner.isEmpty()) { + sql += " AND OWNER LIKE ?"; + hasOwner = true; + } + sql += " AND ID IN ("; + for (int i = 0; i < deviceGroupIdsCount; i++) { + sql += (deviceGroupIdsCount - 1 != i) ? "?," : "?"; + } + sql += ")"; + if (hasLimit) { + sql += " LIMIT ?, ?"; + } + + int paramIndex = 1; + stmt = conn.prepareStatement(sql); + stmt.setInt(paramIndex++, tenantId); + if (hasGroupName) { + stmt.setString(paramIndex++, groupName + "%"); + } + if (hasOwner) { + stmt.setString(paramIndex++, owner + "%"); + } + for (Integer deviceGroupId : deviceGroupIds) { + stmt.setInt(paramIndex++, deviceGroupId); + } + if (hasLimit) { + stmt.setInt(paramIndex++, request.getStartIndex()); + stmt.setInt(paramIndex, request.getRowCount()); + } + resultSet = stmt.executeQuery(); + deviceGroupList = new ArrayList<>(); + while (resultSet.next()) { + deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet)); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return deviceGroupList; + } + + @Override + public List getDevices(int groupId, int startIndex, int rowCount, int tenantId) + throws GroupManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List devices = null; + try { + conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + + "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + + "FROM " + + "(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM" + + " DM_DEVICE d, (" + + "SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 " + + "WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t " + + "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? , ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + //noinspection JpaQueryApiInspection + stmt.setInt(4, startIndex); + //noinspection JpaQueryApiInspection + stmt.setInt(5, rowCount); + rs = stmt.executeQuery(); + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while retrieving information of all " + + "registered devices", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/OracleGroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/OracleGroupDAOImpl.java new file mode 100644 index 0000000000..ecbe0013b7 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/OracleGroupDAOImpl.java @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.dao.impl.group; + +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOException; +import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.impl.AbstractGroupDAOImpl; +import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.dao.util.GroupManagementDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class represents implementation of GroupDAO + */ +public class OracleGroupDAOImpl extends AbstractGroupDAOImpl { + + @Override + public List getGroups(GroupPaginationRequest request, int tenantId) + throws GroupManagementDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + List deviceGroupList = null; + + String groupName = request.getGroupName(); + boolean hasGroupName = false; + String owner = request.getOwner(); + boolean hasOwner = false; + boolean hasLimit = request.getRowCount() != 0; + + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE TENANT_ID = ?"; + if (groupName != null && !groupName.isEmpty()) { + sql += " AND GROUP_NAME LIKE ?"; + hasGroupName = true; + } + if (owner != null && !owner.isEmpty()) { + sql += " AND OWNER LIKE ?"; + hasOwner = true; + } + if (hasLimit) { + sql += " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + } + + int paramIndex = 1; + stmt = conn.prepareStatement(sql); + stmt.setInt(paramIndex++, tenantId); + if (hasGroupName) { + stmt.setString(paramIndex++, groupName + "%"); + } + if (hasOwner) { + stmt.setString(paramIndex++, owner + "%"); + } + if (hasLimit) { + stmt.setInt(paramIndex++, request.getStartIndex()); + stmt.setInt(paramIndex, request.getRowCount()); + } + resultSet = stmt.executeQuery(); + deviceGroupList = new ArrayList<>(); + while (resultSet.next()) { + deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet)); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return deviceGroupList; + } + + @Override + public List getGroups(GroupPaginationRequest request, List deviceGroupIds, + int tenantId) throws GroupManagementDAOException { + int deviceGroupIdsCount = deviceGroupIds.size(); + if (deviceGroupIdsCount == 0) { + return new ArrayList<>(); + } + PreparedStatement stmt = null; + ResultSet resultSet = null; + List deviceGroupList = null; + + String groupName = request.getGroupName(); + boolean hasGroupName = false; + String owner = request.getOwner(); + boolean hasOwner = false; + boolean hasLimit = request.getRowCount() != 0; + + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE TENANT_ID = ?"; + if (groupName != null && !groupName.isEmpty()) { + sql += " AND GROUP_NAME LIKE ?"; + hasGroupName = true; + } + if (owner != null && !owner.isEmpty()) { + sql += " AND OWNER LIKE ?"; + hasOwner = true; + } + sql += " AND ID IN ("; + for (int i = 0; i < deviceGroupIdsCount; i++) { + sql += (deviceGroupIdsCount - 1 != i) ? "?," : "?"; + } + sql += ")"; + if (hasLimit) { + sql += " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + } + + int paramIndex = 1; + stmt = conn.prepareStatement(sql); + stmt.setInt(paramIndex++, tenantId); + if (hasGroupName) { + stmt.setString(paramIndex++, groupName + "%"); + } + if (hasOwner) { + stmt.setString(paramIndex++, owner + "%"); + } + for (Integer deviceGroupId : deviceGroupIds) { + stmt.setInt(paramIndex++, deviceGroupId); + } + if (hasLimit) { + stmt.setInt(paramIndex++, request.getStartIndex()); + stmt.setInt(paramIndex, request.getRowCount()); + } + resultSet = stmt.executeQuery(); + deviceGroupList = new ArrayList<>(); + while (resultSet.next()) { + deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet)); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return deviceGroupList; + } + + @Override + public List getDevices(int groupId, int startIndex, int rowCount, int tenantId) + throws GroupManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List devices = null; + try { + conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + + "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + + "FROM " + + "(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM" + + " DM_DEVICE d, (" + + "SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 " + + "WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t " + + "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + //noinspection JpaQueryApiInspection + stmt.setInt(4, startIndex); + //noinspection JpaQueryApiInspection + stmt.setInt(5, rowCount); + rs = stmt.executeQuery(); + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while retrieving information of all " + + "registered devices", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/PostgreSQLGroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/PostgreSQLGroupDAOImpl.java new file mode 100644 index 0000000000..c7b0c6b78b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/PostgreSQLGroupDAOImpl.java @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.dao.impl.group; + +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOException; +import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.impl.AbstractGroupDAOImpl; +import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.dao.util.GroupManagementDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class represents implementation of GroupDAO + */ +public class PostgreSQLGroupDAOImpl extends AbstractGroupDAOImpl { + + @Override + public List getGroups(GroupPaginationRequest request, int tenantId) + throws GroupManagementDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + List deviceGroupList = null; + + String groupName = request.getGroupName(); + boolean hasGroupName = false; + String owner = request.getOwner(); + boolean hasOwner = false; + boolean hasLimit = request.getRowCount() != 0; + + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE TENANT_ID = ?"; + if (groupName != null && !groupName.isEmpty()) { + sql += " AND GROUP_NAME LIKE ?"; + hasGroupName = true; + } + if (owner != null && !owner.isEmpty()) { + sql += " AND OWNER LIKE ?"; + hasOwner = true; + } + if (hasLimit) { + sql += " LIMIT ? OFFSET ?"; + } + + int paramIndex = 1; + stmt = conn.prepareStatement(sql); + stmt.setInt(paramIndex++, tenantId); + if (hasGroupName) { + stmt.setString(paramIndex++, groupName + "%"); + } + if (hasOwner) { + stmt.setString(paramIndex++, owner + "%"); + } + if (hasLimit) { + stmt.setInt(paramIndex++, request.getRowCount()); + stmt.setInt(paramIndex, request.getStartIndex()); + } + resultSet = stmt.executeQuery(); + deviceGroupList = new ArrayList<>(); + while (resultSet.next()) { + deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet)); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return deviceGroupList; + } + + @Override + public List getGroups(GroupPaginationRequest request, List deviceGroupIds, + int tenantId) throws GroupManagementDAOException { + int deviceGroupIdsCount = deviceGroupIds.size(); + if (deviceGroupIdsCount == 0) { + return new ArrayList<>(); + } + PreparedStatement stmt = null; + ResultSet resultSet = null; + List deviceGroupList = null; + + String groupName = request.getGroupName(); + boolean hasGroupName = false; + String owner = request.getOwner(); + boolean hasOwner = false; + boolean hasLimit = request.getRowCount() != 0; + + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE TENANT_ID = ?"; + if (groupName != null && !groupName.isEmpty()) { + sql += " AND GROUP_NAME LIKE ?"; + hasGroupName = true; + } + if (owner != null && !owner.isEmpty()) { + sql += " AND OWNER LIKE ?"; + hasOwner = true; + } + sql += " AND ID IN ("; + for (int i = 0; i < deviceGroupIdsCount; i++) { + sql += (deviceGroupIdsCount - 1 != i) ? "?," : "?"; + } + sql += ")"; + if (hasLimit) { + sql += " LIMIT ? OFFSET ?"; + } + + int paramIndex = 1; + stmt = conn.prepareStatement(sql); + stmt.setInt(paramIndex++, tenantId); + if (hasGroupName) { + stmt.setString(paramIndex++, groupName + "%"); + } + if (hasOwner) { + stmt.setString(paramIndex++, owner + "%"); + } + for (Integer deviceGroupId : deviceGroupIds) { + stmt.setInt(paramIndex++, deviceGroupId); + } + if (hasLimit) { + stmt.setInt(paramIndex++, request.getRowCount()); + stmt.setInt(paramIndex, request.getStartIndex()); + } + resultSet = stmt.executeQuery(); + deviceGroupList = new ArrayList<>(); + while (resultSet.next()) { + deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet)); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return deviceGroupList; + } + + @Override + public List getDevices(int groupId, int startIndex, int rowCount, int tenantId) + throws GroupManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List devices = null; + try { + conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + + "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + + "FROM " + + "(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM" + + " DM_DEVICE d, (" + + "SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 " + + "WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t " + + "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + //noinspection JpaQueryApiInspection + stmt.setInt(4, rowCount); + //noinspection JpaQueryApiInspection + stmt.setInt(5, startIndex); + rs = stmt.executeQuery(); + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while retrieving information of all " + + "registered devices", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java new file mode 100644 index 0000000000..34810ae5ab --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.dao.impl.group; + +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOException; +import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.impl.AbstractGroupDAOImpl; +import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.dao.util.GroupManagementDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class represents implementation of GroupDAO + */ +public class SQLServerGroupDAOImpl extends AbstractGroupDAOImpl { + + @Override + public List getGroups(GroupPaginationRequest request, int tenantId) + throws GroupManagementDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + List deviceGroupList = null; + + String groupName = request.getGroupName(); + boolean hasGroupName = false; + String owner = request.getOwner(); + boolean hasOwner = false; + boolean hasLimit = request.getRowCount() != 0; + + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE TENANT_ID = ?"; + if (groupName != null && !groupName.isEmpty()) { + sql += " AND GROUP_NAME LIKE ?"; + hasGroupName = true; + } + if (owner != null && !owner.isEmpty()) { + sql += " AND OWNER LIKE ?"; + hasOwner = true; + } + if (hasLimit) { + sql += " ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + } + + int paramIndex = 1; + stmt = conn.prepareStatement(sql); + stmt.setInt(paramIndex++, tenantId); + if (hasGroupName) { + stmt.setString(paramIndex++, groupName + "%"); + } + if (hasOwner) { + stmt.setString(paramIndex++, owner + "%"); + } + if (hasLimit) { + stmt.setInt(paramIndex++, request.getStartIndex()); + stmt.setInt(paramIndex, request.getRowCount()); + } + resultSet = stmt.executeQuery(); + deviceGroupList = new ArrayList<>(); + while (resultSet.next()) { + deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet)); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return deviceGroupList; + } + + @Override + public List getGroups(GroupPaginationRequest request, List deviceGroupIds, + int tenantId) throws GroupManagementDAOException { + int deviceGroupIdsCount = deviceGroupIds.size(); + if (deviceGroupIdsCount == 0) { + return new ArrayList<>(); + } + PreparedStatement stmt = null; + ResultSet resultSet = null; + List deviceGroupList = null; + + String groupName = request.getGroupName(); + boolean hasGroupName = false; + String owner = request.getOwner(); + boolean hasOwner = false; + boolean hasLimit = request.getRowCount() != 0; + + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE TENANT_ID = ?"; + if (groupName != null && !groupName.isEmpty()) { + sql += " AND GROUP_NAME LIKE ?"; + hasGroupName = true; + } + if (owner != null && !owner.isEmpty()) { + sql += " AND OWNER LIKE ?"; + hasOwner = true; + } + sql += " AND ID IN ("; + for (int i = 0; i < deviceGroupIdsCount; i++) { + sql += (deviceGroupIdsCount - 1 != i) ? "?," : "?"; + } + sql += ")"; + if (hasLimit) { + sql += " ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + } + + int paramIndex = 1; + stmt = conn.prepareStatement(sql); + stmt.setInt(paramIndex++, tenantId); + if (hasGroupName) { + stmt.setString(paramIndex++, groupName + "%"); + } + if (hasOwner) { + stmt.setString(paramIndex++, owner + "%"); + } + for (Integer deviceGroupId : deviceGroupIds) { + stmt.setInt(paramIndex++, deviceGroupId); + } + if (hasLimit) { + stmt.setInt(paramIndex++, request.getStartIndex()); + stmt.setInt(paramIndex, request.getRowCount()); + } + resultSet = stmt.executeQuery(); + deviceGroupList = new ArrayList<>(); + while (resultSet.next()) { + deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet)); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return deviceGroupList; + } + + @Override + public List getDevices(int groupId, int startIndex, int rowCount, int tenantId) + throws GroupManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List devices = null; + try { + conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + + "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + + "FROM " + + "(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM" + + " DM_DEVICE d, (" + + "SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 " + + "WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t " + + "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY d1.DEVICE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + //noinspection JpaQueryApiInspection + stmt.setInt(4, startIndex); + //noinspection JpaQueryApiInspection + stmt.setInt(5, rowCount); + rs = stmt.executeQuery(); + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while retrieving information of all " + + "registered devices", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java index ea998fdec7..251b489d0d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java @@ -200,33 +200,7 @@ public final class DeviceManagementDAOUtil { if (deviceInfoIncluded) { device.setDeviceInfo(loadDeviceInfo(rs)); } - - if (EnrolmentInfo.Status.ACTIVE.equals(device.getEnrolmentInfo().getStatus())) { - return device; - } - deviceMap.put(device.getEnrolmentInfo().getStatus(), device); - while (rs.next()) { - device = loadDevice(rs); - if (deviceInfoIncluded) { - device.setDeviceInfo(loadDeviceInfo(rs)); - } - if (EnrolmentInfo.Status.ACTIVE.equals(device.getEnrolmentInfo().getStatus())) { - return device; - } - if (device.getEnrolmentInfo() != null) { - deviceMap.put(device.getEnrolmentInfo().getStatus(), device); - } - } - if (deviceMap.containsKey(EnrolmentInfo.Status.UNREACHABLE)) { - return deviceMap.get(EnrolmentInfo.Status.UNREACHABLE); - } else if (deviceMap.containsKey(EnrolmentInfo.Status.INACTIVE)) { - return deviceMap.get(EnrolmentInfo.Status.INACTIVE); - } else if (deviceMap.containsKey(EnrolmentInfo.Status.CREATED)) { - return deviceMap.get(EnrolmentInfo.Status.CREATED); - } else if (deviceMap.containsKey(EnrolmentInfo.Status.UNCLAIMED)) { - return deviceMap.get(EnrolmentInfo.Status.UNCLAIMED); - } - return null; + return device; } //This method will retrieve most appropriate device information when there are multiple device enrollments for @@ -237,39 +211,6 @@ public final class DeviceManagementDAOUtil { if (deviceInfoIncluded) { device.setDeviceInfo(loadDeviceInfo(rs)); } - - if (EnrolmentInfo.Status.ACTIVE.equals(device.getEnrolmentInfo().getStatus())) { - return device; - } - while (rs.next()) { - device = loadDevice(rs); - if (deviceInfoIncluded) { - device.setDeviceInfo(loadDeviceInfo(rs)); - } - if (EnrolmentInfo.Status.ACTIVE.equals(device.getEnrolmentInfo().getStatus())) { - return device; - } - if (device.getEnrolmentInfo() != null) { - deviceMap.put(device.getEnrolmentInfo().getStatus(), device); - } - } - if (deviceMap.containsKey(EnrolmentInfo.Status.UNREACHABLE)) { - return deviceMap.get(EnrolmentInfo.Status.UNREACHABLE); - } else if (deviceMap.containsKey(EnrolmentInfo.Status.INACTIVE)) { - return deviceMap.get(EnrolmentInfo.Status.INACTIVE); - } else if (deviceMap.containsKey(EnrolmentInfo.Status.DISENROLLMENT_REQUESTED)) { - return deviceMap.get(EnrolmentInfo.Status.DISENROLLMENT_REQUESTED); - } else if (deviceMap.containsKey(EnrolmentInfo.Status.CREATED)) { - return deviceMap.get(EnrolmentInfo.Status.CREATED); - } else if (deviceMap.containsKey(EnrolmentInfo.Status.REMOVED)) { - return deviceMap.get(EnrolmentInfo.Status.REMOVED); - } else if (deviceMap.containsKey(EnrolmentInfo.Status.UNCLAIMED)) { - return deviceMap.get(EnrolmentInfo.Status.UNCLAIMED); - } else if (deviceMap.containsKey(EnrolmentInfo.Status.SUSPENDED)) { - return deviceMap.get(EnrolmentInfo.Status.SUSPENDED); - } else if (deviceMap.containsKey(EnrolmentInfo.Status.BLOCKED)) { - return deviceMap.get(EnrolmentInfo.Status.BLOCKED); - } return device; } 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 127216f27b..e356802117 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 @@ -22,7 +22,11 @@ package org.wso2.carbon.device.mgt.core.device.details.mgt.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.device.mgt.common.*; +import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.TransactionManagementException; 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.core.dao.DeviceDAO; @@ -33,6 +37,7 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManag import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDAOException; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import java.sql.SQLException; import java.util.ArrayList; @@ -45,6 +50,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { private DeviceDetailsDAO deviceDetailsDAO; private DeviceDAO deviceDAO; private static final Log log = LogFactory.getLog(DeviceInformationManagerImpl.class); + private static final String EVENT_STREAM_DEFINITION = "org.wso2.iot.LocationStream"; public DeviceInformationManagerImpl() { this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); @@ -55,7 +61,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { public void addDeviceInfo(DeviceIdentifier deviceId, DeviceInfo deviceInfo) throws DeviceDetailsMgtException { try { Device device = DeviceManagementDataHolder.getInstance(). - getDeviceManagementProvider().getDevice(deviceId); + getDeviceManagementProvider().getDevice(deviceId, false); DeviceManagementDAOFactory.beginTransaction(); deviceDAO.updateDevice(device, CarbonContext.getThreadLocalCarbonContext().getTenantId()); @@ -87,7 +93,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { Device device; try { device = DeviceManagementDataHolder.getInstance(). - getDeviceManagementProvider().getDevice(deviceId); + getDeviceManagementProvider().getDevice(deviceId, false); if (device == null) { if (log.isDebugEnabled()) { log.debug("No device is found upon the device identifier '" + deviceId.getId() + @@ -123,8 +129,8 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } try { List deviceIds = new ArrayList<>(); - List devices = DeviceManagementDataHolder.getInstance(). - getDeviceManagementProvider().getAllDevices(); + List devices = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider(). + getAllDevices(false); for (Device device : devices) { if (identifierMap.containsKey(device.getDeviceIdentifier()) && device.getType().equals(identifierMap.get(device.getDeviceIdentifier()).getType())) { @@ -154,12 +160,23 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { try { Device device = DeviceManagementDataHolder.getInstance(). - getDeviceManagementProvider().getDevice(deviceLocation.getDeviceIdentifier()); + getDeviceManagementProvider().getDevice(deviceLocation.getDeviceIdentifier(), false); deviceLocation.setDeviceId(device.getId()); DeviceManagementDAOFactory.beginTransaction(); deviceDAO.updateDevice(device, CarbonContext.getThreadLocalCarbonContext().getTenantId()); deviceDetailsDAO.deleteDeviceLocation(deviceLocation.getDeviceId()); deviceDetailsDAO.addDeviceLocation(deviceLocation); + if (DeviceManagerUtil.isPublishLocationOperationResEnabled()) { + Object metaData[] = {device.getDeviceIdentifier(), device.getType()}; + Object payload[] = new Object[]{ + deviceLocation.getUpdatedTime().getTime(), + deviceLocation.getLatitude(), + deviceLocation.getLongitude() + }; + DeviceManagerUtil.getEventPublisherService().publishEvent( + EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload + ); + } DeviceManagementDAOFactory.commitTransaction(); } catch (TransactionManagementException e) { throw new DeviceDetailsMgtException("Transactional error occurred while adding the device location " + @@ -174,6 +191,9 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceDetailsMgtException("Error occurred while updating the last updated timestamp of " + "the device", e); + } catch (DataPublisherConfigurationException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e); } finally { DeviceManagementDAOFactory.closeConnection(); } @@ -183,7 +203,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { public DeviceLocation getDeviceLocation(DeviceIdentifier deviceId) throws DeviceDetailsMgtException { Device device; try { - device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId); + device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId, false); if (device == null) { if (log.isDebugEnabled()) { log.debug("No device is found upon the device identifier '" + deviceId.getId() + @@ -212,7 +232,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { try { List devices = DeviceManagementDataHolder.getInstance(). - getDeviceManagementProvider().getAllDevices(deviceIdentifiers.get(0).getType()); + getDeviceManagementProvider().getAllDevices(deviceIdentifiers.get(0).getType(), false); List deviceLocations = new ArrayList<>(); DeviceManagementDAOFactory.openConnection(); for (Device device : devices) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceManagementServiceHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceManagementServiceHolder.java new file mode 100644 index 0000000000..d849120414 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceManagementServiceHolder.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2017, 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. + */ +package org.wso2.carbon.device.mgt.core.dto; + +import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; + +/** + * This holds the information of the registered device management service against the device type + * definition loaded timestamp. This is used to handle device type update scenario. + */ +public class DeviceManagementServiceHolder { + + private DeviceManagementService deviceManagementService; + private long timestamp; + + public DeviceManagementServiceHolder(DeviceManagementService deviceManagementService) { + this.deviceManagementService = deviceManagementService; + this.timestamp = System.currentTimeMillis(); + } + + public DeviceManagementService getDeviceManagementService() { + return deviceManagementService; + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceType.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceType.java index eb363fff1c..5f04d3d6d1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceType.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceType.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import java.io.Serializable; @@ -33,6 +34,9 @@ public class DeviceType implements Serializable { @ApiModelProperty(name = "name", value = "Device type name", required = true) private String name; + @ApiModelProperty(name = "metaDefinition", value = "Device type definition", required = true) + private DeviceTypeMetaDefinition deviceTypeMetaDefinition; + public DeviceType() { } @@ -56,4 +60,13 @@ public class DeviceType implements Serializable { this.name = name; } + public DeviceTypeMetaDefinition getDeviceTypeMetaDefinition() { + return deviceTypeMetaDefinition; + } + + public void setDeviceTypeMetaDefinition( + DeviceTypeMetaDefinition deviceTypeMetaDefinition) { + this.deviceTypeMetaDefinition = deviceTypeMetaDefinition; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceTypeServiceIdentifier.java similarity index 75% rename from components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceTypeServiceIdentifier.java index 1849a97c0d..d6d48a8497 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceTypeServiceIdentifier.java @@ -15,26 +15,26 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.common; +package org.wso2.carbon.device.mgt.core.dto; import java.io.Serializable; /** * This class holds the information of the device type and its provider tenant. */ -public class DeviceTypeIdentifier implements Serializable { +public class DeviceTypeServiceIdentifier implements Serializable { private String deviceType; private int tenantId; private static final int DEFAULT_SHARE_WITH_ALL_TENANTS_ID = -1; - public DeviceTypeIdentifier(String deviceType, int tenantId) { - this.deviceType = deviceType.toLowerCase(); + public DeviceTypeServiceIdentifier(String deviceType, int tenantId) { + this.deviceType = deviceType; this.tenantId = tenantId; } - public DeviceTypeIdentifier(String deviceType) { - this.deviceType = deviceType.toLowerCase(); + public DeviceTypeServiceIdentifier(String deviceType) { + this.deviceType = deviceType; this.tenantId = DEFAULT_SHARE_WITH_ALL_TENANTS_ID; } @@ -59,8 +59,8 @@ public class DeviceTypeIdentifier implements Serializable { @Override public boolean equals(Object obj) { - return (obj instanceof DeviceTypeIdentifier) && deviceType.equals( - ((DeviceTypeIdentifier) obj).deviceType) && tenantId == ((DeviceTypeIdentifier) obj).tenantId; + return (obj instanceof DeviceTypeServiceIdentifier) && deviceType.equals( + ((DeviceTypeServiceIdentifier) obj).deviceType) && tenantId == ((DeviceTypeServiceIdentifier) obj).tenantId; } public boolean isSharedWithAllTenant() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java new file mode 100644 index 0000000000..36b56e357a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java @@ -0,0 +1,729 @@ +/* + * Copyright (c) 2015, 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. + */ + +package org.wso2.carbon.device.mgt.core.geo.service; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.Stub; +import org.apache.axis2.java.security.SSLProtocolSocketFactory; +import org.apache.axis2.transport.http.HTTPConstants; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.protocol.Protocol; +import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.ServerConfiguration; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.core.util.Utils; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices; +import org.wso2.carbon.device.mgt.common.geo.service.Alert; +import org.wso2.carbon.device.mgt.common.geo.service.GeoFence; +import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService; +import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub; +import org.wso2.carbon.identity.jwt.client.extension.JWTClient; +import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; +import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; +import org.wso2.carbon.registry.api.Registry; +import org.wso2.carbon.registry.api.RegistryException; +import org.wso2.carbon.registry.api.Resource; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import static org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices.DAS_PORT; +import static org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices.DEFAULT_HTTP_PROTOCOL; + +/** + * This class will read events, set alerts, read alerts related to geo-fencing and it will + * use Registry as the persistence storage. + */ +public class GeoLocationProviderServiceImpl implements GeoLocationProviderService { + + private static Log log = LogFactory.getLog(GeoLocationProviderServiceImpl.class); + + /** + * required soap header for authorization + */ + private static final String AUTHORIZATION_HEADER = "Authorization"; + /** + * required soap header value for mutualSSL + */ + private static final String AUTHORIZATION_HEADER_VALUE = "Bearer"; + /** + * Default keystore type of the client + */ + private static final String KEY_STORE_TYPE = "JKS"; + /** + * Default truststore type of the client + */ + private static final String TRUST_STORE_TYPE = "JKS"; + /** + * Default keymanager type of the client + */ + private static final String KEY_MANAGER_TYPE = "SunX509"; //Default Key Manager Type + /** + * Default trustmanager type of the client + */ + private static final String TRUST_MANAGER_TYPE = "SunX509"; //Default Trust Manager Type + + private static final String SSLV3 = "SSLv3"; + + @Override + public List getWithinAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException { + + Registry registry = getGovernanceRegistry(); + String registryPath = GeoServices.REGISTRY_PATH_FOR_ALERTS + + GeoServices.ALERT_TYPE_WITHIN + "/" + identifier.getId() + "/"; + Resource resource; + try { + resource = registry.get(registryPath); + } catch (RegistryException e) { + log.error("Error while reading the registry path: " + registryPath); + return null; + } + + try { + List fences = new ArrayList<>(); + if (resource != null) { + Object contentObj = resource.getContent(); + if (contentObj instanceof String[]) { + String[] content = (String[]) contentObj; + for (String res : content) { + Resource childRes = registry.get(res); + Properties props = childRes.getProperties(); + + GeoFence geoFence = new GeoFence(); + + InputStream inputStream = childRes.getContentStream(); + StringWriter writer = new StringWriter(); + IOUtils.copy(inputStream, writer, "UTF-8"); + geoFence.setGeoJson(writer.toString()); + + List queryNameObj = (List) props.get(GeoServices.QUERY_NAME); + geoFence.setQueryName(queryNameObj != null ? queryNameObj.get(0).toString() : null); + List areaNameObj = (List) props.get(GeoServices.AREA_NAME); + geoFence.setAreaName(areaNameObj != null ? areaNameObj.get(0).toString() : null); + geoFence.setCreatedTime(childRes.getCreatedTime().getTime()); + fences.add(geoFence); + } + } + } + return fences; + } catch (RegistryException | IOException e) { + throw new GeoLocationBasedServiceException( + "Error occurred while getting the geo alerts for " + identifier.getType() + " with id: " + + identifier.getId(), e); + } + } + + @Override + public List getExitAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException { + + Registry registry = getGovernanceRegistry(); + String registryPath = GeoServices.REGISTRY_PATH_FOR_ALERTS + + GeoServices.ALERT_TYPE_EXIT + "/" + identifier.getId() + "/"; + Resource resource; + try { + resource = registry.get(registryPath); + } catch (RegistryException e) { + log.error("Error while reading the registry path: " + registryPath); + return null; + } + + try { + List fences = new ArrayList<>(); + if (resource != null) { + Object contentObj = resource.getContent(); + if (contentObj instanceof String[]) { + String[] content = (String[]) contentObj; + for (String res : content) { + Resource childRes = registry.get(res); + Properties props = childRes.getProperties(); + + GeoFence geoFence = new GeoFence(); + + InputStream inputStream = childRes.getContentStream(); + StringWriter writer = new StringWriter(); + IOUtils.copy(inputStream, writer, "UTF-8"); + geoFence.setGeoJson(writer.toString()); + + List queryNameObj = (List) props.get(GeoServices.QUERY_NAME); + geoFence.setQueryName(queryNameObj != null ? queryNameObj.get(0).toString() : null); + List areaNameObj = (List) props.get(GeoServices.AREA_NAME); + geoFence.setAreaName(areaNameObj != null ? areaNameObj.get(0).toString() : null); + geoFence.setCreatedTime(childRes.getCreatedTime().getTime()); + fences.add(geoFence); + } + } + } + return fences; + } catch (RegistryException | IOException e) { + throw new GeoLocationBasedServiceException( + "Error occurred while getting the geo alerts for " + identifier.getType() + " with id: " + + identifier.getId(), e); + } + } + + @Override + public boolean createGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType) + throws GeoLocationBasedServiceException { + return saveGeoAlert(alert, identifier, alertType, false); + } + + @Override + public boolean updateGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType) + throws GeoLocationBasedServiceException { + return saveGeoAlert(alert, identifier, alertType, true); + } + + public boolean saveGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType, boolean isUpdate) + throws GeoLocationBasedServiceException { + + Type type = new TypeToken>() { + }.getType(); + Gson gson = new Gson(); + Map parseMap = gson.fromJson(alert.getParseData(), type); + + Map options = new HashMap<>(); + Object content = null; + + if (GeoServices.ALERT_TYPE_WITHIN.equals(alertType)) { + options.put(GeoServices.QUERY_NAME, alert.getQueryName()); + options.put(GeoServices.AREA_NAME, alert.getCustomName()); + content = parseMap.get(GeoServices.GEO_FENCE_GEO_JSON); + + } else if (GeoServices.ALERT_TYPE_EXIT.equals(alertType)) { + options.put(GeoServices.QUERY_NAME, alert.getQueryName()); + options.put(GeoServices.AREA_NAME, alert.getCustomName()); + content = parseMap.get(GeoServices.GEO_FENCE_GEO_JSON); + + } else if (GeoServices.ALERT_TYPE_SPEED.equals(alertType)) { + content = parseMap.get(GeoServices.SPEED_ALERT_VALUE); + + } else if (GeoServices.ALERT_TYPE_PROXIMITY.equals(alertType)) { + options.put(GeoServices.PROXIMITY_DISTANCE, alert.getProximityDistance()); + options.put(GeoServices.PROXIMITY_TIME, alert.getProximityTime()); + content = alert.getParseData(); + + } else if (GeoServices.ALERT_TYPE_STATIONARY.equals(alertType)) { + options.put(GeoServices.QUERY_NAME, alert.getQueryName()); + options.put(GeoServices.AREA_NAME, alert.getCustomName()); + options.put(GeoServices.STATIONARY_TIME, alert.getStationeryTime()); + options.put(GeoServices.FLUCTUATION_RADIUS, alert.getFluctuationRadius()); + content = alert.getParseData(); + + } else if (GeoServices.ALERT_TYPE_TRAFFIC.equals(alertType)) { + content = parseMap.get(GeoServices.GEO_FENCE_GEO_JSON); + } else { + throw new GeoLocationBasedServiceException( + "Unrecognized execution plan type: " + alertType + " while creating geo alert"); + } + + //persist alert in registry + updateRegistry(getRegistryPath(alertType, identifier, alert.getQueryName()), identifier, content, + options); + + //deploy alert into event processor + EventProcessorAdminServiceStub eventprocessorStub = null; + String action = (isUpdate ? "updating" : "creating"); + try { + eventprocessorStub = getEventProcessorAdminServiceStub(); + String parsedTemplate = parseTemplate(alertType, parseMap); + String validationResponse = eventprocessorStub.validateExecutionPlan(parsedTemplate); + if (validationResponse.equals("success")) { + if (isUpdate) { + String executionPlanName = getExecutionPlanName(alertType, alert.getQueryName(), + identifier.getId()); + eventprocessorStub.editActiveExecutionPlan(parsedTemplate, executionPlanName); + } else { + eventprocessorStub.deployExecutionPlan(parsedTemplate); + } + } else { + if (validationResponse.startsWith( + "'within' is neither a function extension nor an aggregated attribute extension" + )) { + log.error("GPL Siddhi Geo Extension is not configured. Please execute maven script " + + "`siddhi-geo-extention-deployer.xml` in $IOT_HOME/analytics/scripts"); + } else { + log.error("Execution plan validation failed: " + validationResponse); + } + throw new GeoLocationBasedServiceException( + "Error occurred while " + action + " geo " + alertType + " alert for " + + identifier.getType() + " with id: " + identifier.getId()); + } + return true; + } catch (AxisFault axisFault) { + throw new GeoLocationBasedServiceException( + "Event processor admin service initialization failed while " + action + " geo alert '" + + alertType + "' for " + identifier.getType() + " " + + "device with id: " + identifier.getId(), axisFault + ); + } catch (IOException e) { + throw new GeoLocationBasedServiceException( + "Event processor admin service failed while " + action + " geo alert '" + + alertType + "' for " + identifier.getType() + " " + + "device with id: " + identifier.getId(), e); + } catch (JWTClientException e) { + throw new GeoLocationBasedServiceException( + "JWT token creation failed while " + action + " geo alert '" + alertType + "' for " + + identifier.getType() + " device with id:" + identifier.getId(), e); + } finally { + cleanup(eventprocessorStub); + } + } + + private String getRegistryPath(String alertType, DeviceIdentifier identifier, String queryName) + throws GeoLocationBasedServiceException { + String path = ""; + if (GeoServices.ALERT_TYPE_WITHIN.equals(alertType)) { + path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_WITHIN + + "/" + identifier.getId() + "/" + queryName; + } else if (GeoServices.ALERT_TYPE_EXIT.equals(alertType)) { + path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_EXIT + + "/" + identifier.getId() + "/" + queryName; + } else if (GeoServices.ALERT_TYPE_SPEED.equals(alertType)) { + path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_SPEED + + "/" + identifier.getId(); + } else if (GeoServices.ALERT_TYPE_PROXIMITY.equals(alertType)) { + path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_PROXIMITY + + "/" + identifier.getId() + "/" + queryName; + } else if (GeoServices.ALERT_TYPE_STATIONARY.equals(alertType)) { + path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_STATIONARY + + "/" + identifier.getId() + "/" + queryName; + } else if (GeoServices.ALERT_TYPE_TRAFFIC.equals(alertType)) { + path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_TRAFFIC + + "/" + identifier.getId() + "/" + queryName; + } else { + throw new GeoLocationBasedServiceException( + "Unrecognized execution plan type: " + alertType); + } + return path; + } + + private String getExecutionPlanName(String alertType, String queryName, String deviceId) { + if ("Traffic".equals(alertType)) { + return "Geo-ExecutionPlan-Traffic_" + queryName + "_alert"; + } else { + return "Geo-ExecutionPlan-" + alertType + "_" + queryName + "---_" + deviceId + "_alert"; + } + } + + @Override + public boolean removeGeoAlert(String alertType, DeviceIdentifier identifier, String queryName) + throws GeoLocationBasedServiceException { + removeFromRegistry(alertType, identifier, queryName); + String executionPlanName = getExecutionPlanName(alertType, queryName, identifier.getId()); + EventProcessorAdminServiceStub eventprocessorStub = null; + try { + eventprocessorStub = getEventProcessorAdminServiceStub(); + eventprocessorStub.undeployActiveExecutionPlan(executionPlanName); + return true; + } catch (IOException e) { + throw new GeoLocationBasedServiceException( + "Event processor admin service stub invocation failed while removing geo alert '" + + alertType + + "': " + executionPlanName + " for " + + identifier.getType() + " device with id:" + identifier.getId(), e + ); + } catch (JWTClientException e) { + throw new GeoLocationBasedServiceException( + "JWT token creation failed while removing geo alert '" + alertType + "': " + + executionPlanName + " for " + + identifier.getType() + " device with id:" + identifier.getId(), e + ); + } finally { + cleanup(eventprocessorStub); + } + } + + private void removeFromRegistry(String alertType, DeviceIdentifier identifier, String queryName) + throws GeoLocationBasedServiceException { + String path = "unknown"; + try { + path = getRegistryPath(alertType, identifier, queryName); + getGovernanceRegistry().delete(path); + } catch (RegistryException e) { + throw new GeoLocationBasedServiceException( + "Error occurred while removing " + alertType + " alert for " + identifier.getType() + + " device with id:" + identifier.getId() + " from the path: " + path); + } + } + + private EventProcessorAdminServiceStub getEventProcessorAdminServiceStub() throws JWTClientException { + //send alert to event-processing + String eventProcessorAdminServiceWSUrl = Utils.replaceSystemProperty(GeoServices.DAS_URL) + + "/services/EventProcessorAdminService"; + + //Getting the tenant Domain + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + String tenantAdminUser = username + "@" + tenantDomain; + + try { + //Create the SSL context with the loaded TrustStore/keystore. + SSLContext sslContext = initSSLConnection(tenantAdminUser); + JWTClient jwtClient = getJWTClientManagerService().getJWTClient(); + + String authValue = AUTHORIZATION_HEADER_VALUE + " " + new String(Base64.encodeBase64( + jwtClient.getJwtToken(tenantAdminUser).getBytes())); + + EventProcessorAdminServiceStub eventprocessorStub = new EventProcessorAdminServiceStub( + eventProcessorAdminServiceWSUrl); + + Options eventProcessorOption = eventprocessorStub._getServiceClient().getOptions(); + if (eventProcessorOption == null) { + eventProcessorOption = new Options(); + } + + List
list = new ArrayList<>(); + Header httpHeader = new Header(); + httpHeader.setName(AUTHORIZATION_HEADER); + httpHeader.setValue(authValue); + list.add(httpHeader);//"https" + + eventProcessorOption.setProperty(HTTPConstants.HTTP_HEADERS, list); + eventProcessorOption.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER + , new Protocol(DEFAULT_HTTP_PROTOCOL + , (ProtocolSocketFactory) new SSLProtocolSocketFactory(sslContext) + , Integer.parseInt(Utils.replaceSystemProperty(DAS_PORT)))); + eventprocessorStub._getServiceClient().setOptions(eventProcessorOption); + + return eventprocessorStub; + } catch (CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | + KeyManagementException | IOException e) { + throw new JWTClientException("JWT token creation failed for the Event Processor Stub", e); + } + } + + @Override + public String getSpeedAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException { + try { + Registry registry = getGovernanceRegistry(); + Resource resource = registry.get(GeoServices.REGISTRY_PATH_FOR_ALERTS + + GeoServices.ALERT_TYPE_SPEED + "/" + identifier.getId()); + if (resource == null) { + return "{'content': false}"; + } + InputStream inputStream = resource.getContentStream(); + StringWriter writer = new StringWriter(); + IOUtils.copy(inputStream, writer, "UTF-8"); + return "{'speedLimit':" + writer.toString() + "}"; + } catch (RegistryException | IOException e) { + return "{'content': false}"; + } + } + + @Override + public String getProximityAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException { + try { + Registry registry = getGovernanceRegistry(); + Resource resource = registry.get(GeoServices.REGISTRY_PATH_FOR_ALERTS + + GeoServices.ALERT_TYPE_PROXIMITY + + "/" + identifier.getId()); + if (resource != null) { + Properties props = resource.getProperties(); + + List proxDisObj = (List) props.get(GeoServices.PROXIMITY_DISTANCE); + List proxTimeObj = (List) props.get(GeoServices.PROXIMITY_TIME); + + return String.format("{proximityDistance:\"%s\", proximityTime:\"%s\"}", + proxDisObj != null ? proxDisObj.get(0).toString() : "", + proxTimeObj != null ? proxTimeObj.get(0).toString() : ""); + } else { + return "{'content': false}"; + } + } catch (RegistryException e) { + return "{'content': false}"; + } + } + + @Override + public List getStationaryAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException { + + Registry registry = getGovernanceRegistry(); + String registryPath = GeoServices.REGISTRY_PATH_FOR_ALERTS + + GeoServices.ALERT_TYPE_STATIONARY + "/" + identifier.getId() + "/"; + Resource resource; + try { + resource = registry.get(registryPath); + } catch (RegistryException e) { + log.error("Error while reading the registry path: " + registryPath); + return null; + } + + try { + List fences = new ArrayList<>(); + if (resource != null) { + Object contentObj = resource.getContent(); + + if (contentObj instanceof String[]) { + String[] content = (String[]) contentObj; + for (String res : content) { + Resource childRes = registry.get(res); + Properties props = childRes.getProperties(); + GeoFence geoFence = new GeoFence(); + + InputStream inputStream = childRes.getContentStream(); + StringWriter writer = new StringWriter(); + IOUtils.copy(inputStream, writer, "UTF-8"); + geoFence.setGeoJson(writer.toString()); + + List queryNameObj = (List) props.get(GeoServices.QUERY_NAME); + geoFence.setQueryName(queryNameObj != null ? queryNameObj.get(0).toString() : null); + List areaNameObj = (List) props.get(GeoServices.AREA_NAME); + geoFence.setAreaName(areaNameObj != null ? areaNameObj.get(0).toString() : null); + List sTimeObj = (List) props.get(GeoServices.STATIONARY_TIME); + geoFence.setStationaryTime(sTimeObj != null ? sTimeObj.get(0).toString() : null); + List fluctRadiusObj = (List) props.get(GeoServices.FLUCTUATION_RADIUS); + geoFence.setFluctuationRadius(fluctRadiusObj != null ? fluctRadiusObj.get(0).toString() : null); + geoFence.setCreatedTime(childRes.getCreatedTime().getTime()); + fences.add(geoFence); + } + } + } + return fences; + } catch (RegistryException | IOException e) { + throw new GeoLocationBasedServiceException( + "Error occurred while getting the geo alerts for " + identifier.getType() + " with id: " + + identifier.getId(), e); + } + } + + @Override + public List getTrafficAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException { + Registry registry = getGovernanceRegistry(); + String registryPath = GeoServices.REGISTRY_PATH_FOR_ALERTS + + GeoServices.ALERT_TYPE_STATIONARY + "/" + identifier.getId() + "/"; + Resource resource; + try { + resource = registry.get(registryPath); + } catch (RegistryException e) { + log.error("Error while reading the registry path: " + registryPath); + return null; + } + + try { + List fences = new ArrayList<>(); + if (resource != null) { + Object contentObj = resource.getContent(); + if (contentObj instanceof String[]) { + String[] content = (String[]) contentObj; + for (String res : content) { + Resource childRes = registry.get(res); + Properties props = childRes.getProperties(); + + GeoFence geoFence = new GeoFence(); + + InputStream inputStream = childRes.getContentStream(); + StringWriter writer = new StringWriter(); + IOUtils.copy(inputStream, writer, "UTF-8"); + geoFence.setGeoJson(writer.toString()); + + List queryNameObj = (List) props.get(GeoServices.QUERY_NAME); + geoFence.setQueryName(queryNameObj != null ? queryNameObj.get(0).toString() : null); + List sNameObj = (List) props.get(GeoServices.STATIONARY_NAME); + geoFence.setAreaName(sNameObj != null ? sNameObj.get(0).toString() : null); + geoFence.setCreatedTime(childRes.getCreatedTime().getTime()); + fences.add(geoFence); + } + } + } + return fences; + } catch (RegistryException | IOException e) { + throw new GeoLocationBasedServiceException( + "Error occurred while getting the geo alerts for " + identifier.getType() + " with id: " + + identifier.getId(), e); + } + } + + private Registry getGovernanceRegistry() throws GeoLocationBasedServiceException { + try { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + return DeviceManagementDataHolder.getInstance().getRegistryService() + .getGovernanceSystemRegistry( + tenantId); + } catch (RegistryException e) { + throw new GeoLocationBasedServiceException( + "Error in retrieving governance registry instance: " + + e.getMessage(), e); + } + } + + private String parseTemplate(String alertType, Map parseMap) throws + GeoLocationBasedServiceException { + String templatePath = "alerts/Geo-ExecutionPlan-" + alertType + "_alert.siddhiql"; + InputStream resource = getClass().getClassLoader().getResourceAsStream(templatePath); + if (resource == null) { + throw new GeoLocationBasedServiceException("Could not find template in path : " + templatePath); + } + try { + //Read template + String template = IOUtils.toString(resource, StandardCharsets.UTF_8.toString()); + //Replace variables + for (Map.Entry parseEntry : parseMap.entrySet()) { + String find = "\\$" + parseEntry.getKey(); + template = template.replaceAll(find, parseEntry.getValue()); + } + return template; + } catch (IOException e) { + throw new GeoLocationBasedServiceException( + "Error occurred while populating the template for the Within Alert", e); + } + } + + private void updateRegistry(String path, DeviceIdentifier identifier, Object content, Map options) + throws GeoLocationBasedServiceException { + try { + + Registry registry = getGovernanceRegistry(); + Resource newResource = registry.newResource(); + newResource.setContent(content); + newResource.setMediaType("application/json"); + for (Map.Entry option : options.entrySet()) { + newResource.addProperty(option.getKey(), option.getValue()); + } + registry.put(path, newResource); + } catch (RegistryException e) { + throw new GeoLocationBasedServiceException( + "Error occurred while setting the Within Alert for " + identifier.getType() + " with id: " + + identifier.getId(), e); + } + } + + /** + * Loads the keystore. + * + * @param keyStorePath - the path of the keystore + * @param keyStorePassword - the keystore password + */ + private KeyStore loadKeyStore(String keyStorePath, char[] keyStorePassword) + throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { + InputStream fis = null; + try { + KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE); + fis = new FileInputStream(keyStorePath); + keyStore.load(fis, keyStorePassword); + return keyStore; + } finally { + if (fis != null) { + fis.close(); + } + } + } + + /** + * Loads the trustore + * + * @param trustStorePath - the trustore path in the filesystem. + * @param tsPassword - the truststore password + */ + private KeyStore loadTrustStore(String trustStorePath, char[] tsPassword) + throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { + + InputStream fis = null; + try { + KeyStore trustStore = KeyStore.getInstance(TRUST_STORE_TYPE); + fis = new FileInputStream(trustStorePath); + trustStore.load(fis, tsPassword); + return trustStore; + } finally { + if (fis != null) { + fis.close(); + } + } + } + + /** + * Initializes the SSL Context + */ + private SSLContext initSSLConnection(String tenantAdminUser) + throws NoSuchAlgorithmException, UnrecoverableKeyException, + KeyStoreException, KeyManagementException, IOException, CertificateException { + String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password"); + String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty( + "Security.TrustStore.Password"); + String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location"); + String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty( + "Security.TrustStore.Location"); + + //Call to load the keystore. + KeyStore keyStore = loadKeyStore(keyStoreLocation, keyStorePassword.toCharArray()); + //Call to load the TrustStore. + KeyStore trustStore = loadTrustStore(trustStoreLocation, trustStorePassword.toCharArray()); + + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE); + keyManagerFactory.init(keyStore, keyStorePassword.toCharArray()); + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE); + trustManagerFactory.init(trustStore); + + // Create and initialize SSLContext for HTTPS communication + + SSLContext sslContext = SSLContext.getInstance(SSLV3); + sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); + SSLContext.setDefault(sslContext); + return sslContext; + } + + private void cleanup(Stub stub) { + if (stub != null) { + try { + stub.cleanup(); + } catch (AxisFault axisFault) { + //do nothing + } + } + } + + public static JWTClientManagerService getJWTClientManagerService() { + JWTClientManagerService jwtClientManagerService; + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + jwtClientManagerService = (JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null); + if (jwtClientManagerService == null) { + String msg = "jwtClientManagerServicehas not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return jwtClientManagerService; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java index f7e8e0a177..f6a3a3fc83 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java @@ -18,16 +18,21 @@ package org.wso2.carbon.device.mgt.core.internal; +import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; +import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService; import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig; import org.wso2.carbon.device.mgt.core.config.license.LicenseConfig; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier; import org.wso2.carbon.device.mgt.core.push.notification.mgt.PushNotificationProviderRepository; 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.status.task.DeviceStatusTaskManagerService; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService; import org.wso2.carbon.email.sender.core.service.EmailSenderService; import org.wso2.carbon.ntask.core.service.TaskService; @@ -36,6 +41,7 @@ import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.utils.ConfigurationContextService; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -59,6 +65,10 @@ public class DeviceManagementDataHolder { private EmailSenderService emailSenderService; private PushNotificationProviderRepository pushNotificationProviderRepository; private DeviceTaskManagerService deviceTaskManagerService; + private DeviceStatusTaskManagerService deviceStatusTaskManagerService; + private DeviceTypeGeneratorService deviceTypeGeneratorService; + private Map deviceStatusTaskPluginConfigs = Collections.synchronizedMap( + new HashMap()); private Map map = new HashMap<>(); @@ -191,7 +201,6 @@ public class DeviceManagementDataHolder { this.deviceAccessAuthorizationService = deviceAccessAuthorizationService; } - public TaskService getTaskService() { return taskService; } @@ -224,4 +233,37 @@ public class DeviceManagementDataHolder { public void setDeviceTaskManagerService(DeviceTaskManagerService deviceTaskManagerService) { this.deviceTaskManagerService = deviceTaskManagerService; } -} + + public DeviceStatusTaskManagerService getDeviceStatusTaskManagerService() { + return deviceStatusTaskManagerService; + } + + public void setDeviceStatusTaskManagerService(DeviceStatusTaskManagerService deviceStatusTaskManagerService) { + this.deviceStatusTaskManagerService = deviceStatusTaskManagerService; + } + + public void addDeviceStatusTaskPluginConfig(DeviceType deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig) { + this.deviceStatusTaskPluginConfigs.put(deviceType, deviceStatusTaskPluginConfig); + } + + public DeviceStatusTaskPluginConfig getDeviceStatusTaskPluginConfig(DeviceTypeServiceIdentifier deviceType) { + return this.deviceStatusTaskPluginConfigs.get(deviceType); + } + + public Map getDeviceStatusTaskPluginConfigs() { + return this.deviceStatusTaskPluginConfigs; + } + + public void removeDeviceStatusTaskPluginConfig(DeviceType deviceType) { + this.deviceStatusTaskPluginConfigs.remove(deviceType); + } + + public DeviceTypeGeneratorService getDeviceTypeGeneratorService() { + return deviceTypeGeneratorService; + } + + public void setDeviceTypeGeneratorService( + DeviceTypeGeneratorService deviceTypeGeneratorService) { + this.deviceTypeGeneratorService = deviceTypeGeneratorService; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java index 0c1a62471d..0c45b6ffda 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -25,11 +25,14 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; +import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; +import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagerProviderServiceImpl; @@ -42,6 +45,7 @@ import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.device.mgt.core.config.tenant.PlatformConfigurationManagementServiceImpl; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.geo.service.GeoLocationProviderServiceImpl; import org.wso2.carbon.device.mgt.core.notification.mgt.NotificationManagementServiceImpl; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; @@ -55,6 +59,7 @@ import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService; import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer; +import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.email.sender.core.service.EmailSenderService; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.registry.core.service.RegistryService; @@ -105,6 +110,12 @@ import java.util.concurrent.TimeUnit; * policy="dynamic" * bind="setEmailSenderService" * unbind="unsetEmailSenderService" + * @scr.reference name="device.type.generator.service" + * interface="org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService" + * cardinality="0..1" + * policy="dynamic" + * bind="setDeviceTypeGeneratorService" + * unbind="unsetDeviceTypeGeneratorService" */ public class DeviceManagementServiceComponent { @@ -150,6 +161,8 @@ public class DeviceManagementServiceComponent { GroupManagementDAOFactory.init(dsConfig); NotificationManagementDAOFactory.init(dsConfig); OperationManagementDAOFactory.init(dsConfig); + /*Initialize the device cache*/ + DeviceManagerUtil.initializeDeviceCache(); /* Initialize Operation Manager */ this.initOperationsManager(); @@ -241,6 +254,21 @@ public class DeviceManagementServiceComponent { /* Registering Group Management Service */ GroupManagementProviderService groupManagementProvider = new GroupManagementProviderServiceImpl(); + String defaultGroups = + DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getDefaultGroupsConfiguration(); + List groups = this.parseDefaultGroups(defaultGroups); + for(String group : groups){ + try { + groupManagementProvider.createDefaultGroup(group); + } catch (GroupManagementException e) { + // Error is ignored, because error could be group already exist exception. Therefore it does not require + // to print the error. + if(log.isDebugEnabled()){ + log.error("Error occurred while adding the group"); + } + } + } + DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(groupManagementProvider); bundleContext.registerService(GroupManagementProviderService.class.getName(), groupManagementProvider, null); @@ -260,6 +288,10 @@ public class DeviceManagementServiceComponent { bundleContext.registerService(DeviceAccessAuthorizationService.class.getName(), deviceAccessAuthorizationService, null); + /* Registering Geo Service */ + GeoLocationProviderService geoService = new GeoLocationProviderServiceImpl(); + bundleContext.registerService(GeoLocationProviderService.class.getName(), geoService, null); + /* Registering App Management service */ try { AppManagementConfigurationManager.getInstance().initConfig(); @@ -295,6 +327,19 @@ public class DeviceManagementServiceComponent { } } + private List parseDefaultGroups(String defaultGroups) { + List defaultGroupsList = new ArrayList<>(); + if (defaultGroups != null && !defaultGroups.isEmpty()) { + String gps[] = defaultGroups.split(","); + if (gps.length != 0) { + for(String group : gps){ + defaultGroupsList.add(group.trim()); + } + } + } + return defaultGroupsList; + } + /** * Sets Device Manager service. * @@ -435,6 +480,30 @@ public class DeviceManagementServiceComponent { } DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null); } + + /** + * sets DeviceTypeGeneratorService. + * + * @param deviceTypeGeneratorService An Instance of DeviceTypeGeneratorService + */ + protected void setDeviceTypeGeneratorService(DeviceTypeGeneratorService deviceTypeGeneratorService) { + if (log.isDebugEnabled()) { + log.debug("Un setting Device DeviceTypeGeneratorService"); + } + DeviceManagementDataHolder.getInstance().setDeviceTypeGeneratorService(deviceTypeGeneratorService); + } + + /** + * sets DeviceTypeGeneratorService. + * + * @param deviceTypeGeneratorService An Instance of DeviceTypeGeneratorService + */ + protected void unsetDeviceTypeGeneratorService(DeviceTypeGeneratorService deviceTypeGeneratorService) { + if (log.isDebugEnabled()) { + log.debug("Un setting Device DeviceTypeGeneratorService"); + } + DeviceManagementDataHolder.getInstance().setDeviceTypeGeneratorService(null); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java index 344d567f0f..ae39c83109 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java @@ -22,11 +22,18 @@ package org.wso2.carbon.device.mgt.core.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; +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.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.search.mgt.impl.SearchManagerServiceImpl; +import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskException; +import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskManagerService; +import org.wso2.carbon.device.mgt.core.status.task.impl.DeviceStatusTaskManagerServiceImpl; import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService; import org.wso2.carbon.device.mgt.core.task.impl.DeviceTaskManagerServiceImpl; @@ -47,24 +54,21 @@ import java.util.Map; public class DeviceTaskManagerServiceComponent { - private static Log log = LogFactory.getLog(DeviceManagementServiceComponent.class); - - + private static Log log = LogFactory.getLog(DeviceTaskManagerServiceComponent.class); @SuppressWarnings("unused") protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { - log.debug("Initializing device details retrieving task manager bundle."); + log.debug("Initializing device task manager bundle."); } - // This will start the device details retrieving task. - // DeviceTaskManagerService deviceTaskManagerService = new DeviceTaskManagerServiceImpl(); - // DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService( - // deviceTaskManagerService); - // componentContext.getBundleContext().registerService(DeviceTaskManagerService.class, - // deviceTaskManagerService, null); - getDeviceOperationMonitoringConfig(componentContext); + //Start the DeviceStatusMonitoringTask for registered DeviceTypes + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig(); + if (deviceManagementConfig != null && deviceManagementConfig.getDeviceStatusTaskConfig().isEnabled()) { + startDeviceStatusMonitoringTask(); + } componentContext.getBundleContext().registerService(DeviceInformationManager.class, new DeviceInformationManagerImpl(), null); @@ -72,29 +76,38 @@ public class DeviceTaskManagerServiceComponent { componentContext.getBundleContext().registerService(SearchManagerService.class, new SearchManagerServiceImpl(), null); } catch (Throwable e) { - log.error("Error occurred while initializing device details retrieving task manager service.", e); + log.error("Error occurred while initializing device task manager service.", e); } } private void getDeviceOperationMonitoringConfig(ComponentContext componentContext) throws DeviceMgtTaskException { - DeviceTaskManagerService deviceTaskManagerService = new DeviceTaskManagerServiceImpl(); - DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(deviceTaskManagerService); - componentContext.getBundleContext().registerService(DeviceTaskManagerService.class, deviceTaskManagerService, null); - Map deviceConfigMap = DeviceMonitoringOperationDataHolder .getInstance().getOperationMonitoringConfigFromMap(); - for (String platformType : new ArrayList<>(deviceConfigMap.keySet())) { deviceTaskManagerService.startTask(platformType, deviceConfigMap.get(platformType)); deviceConfigMap.remove(platformType); } } + private void startDeviceStatusMonitoringTask() { + DeviceStatusTaskManagerService deviceStatusTaskManagerService = new DeviceStatusTaskManagerServiceImpl(); + Map deviceStatusTaskPluginConfigs = DeviceManagementDataHolder. + getInstance().getDeviceStatusTaskPluginConfigs(); + for (DeviceType deviceType : new ArrayList<>(deviceStatusTaskPluginConfigs.keySet())) { + try { + deviceStatusTaskManagerService.startTask(deviceType, deviceStatusTaskPluginConfigs.get(deviceType)); + } catch (DeviceStatusTaskException e) { + log.error("Exception occurred while starting the DeviceStatusMonitoring Task for deviceType '" + + deviceType + "'", e); + } + } + } + @SuppressWarnings("unused") protected void deactivate(ComponentContext componentContext) { try { @@ -105,7 +118,6 @@ public class DeviceTaskManagerServiceComponent { } } - protected void setTaskService(TaskService taskService) { if (log.isDebugEnabled()) { log.debug("Setting the task service."); @@ -119,7 +131,4 @@ public class DeviceTaskManagerServiceComponent { } DeviceManagementDataHolder.getInstance().setTaskService(null); } - -} - - +} \ No newline at end of file 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 88883a4e26..90867dbc3d 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 @@ -22,6 +22,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EntityDoesNotExistException; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; @@ -30,8 +31,8 @@ import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationDAO; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; @@ -65,7 +66,7 @@ public class NotificationManagementServiceImpl implements NotificationManagement int notificationId; int tenantId = NotificationDAOUtil.getTenantId(); - Device device = this.getDevice(deviceId, tenantId); + Device device = this.getDevice(deviceId); if (device == null) { throw new EntityDoesNotExistException("No device is found with type '" + deviceId.getType() + "' and id '" + deviceId.getId() + "'"); @@ -87,19 +88,13 @@ public class NotificationManagementServiceImpl implements NotificationManagement return true; } - private Device getDevice(DeviceIdentifier deviceId, int tenantId) throws NotificationManagementException { + private Device getDevice(DeviceIdentifier deviceId) throws NotificationManagementException { Device device; try { - DeviceManagementDAOFactory.openConnection(); - device = deviceDAO.getDevice(deviceId, tenantId); - } catch (SQLException e) { - throw new NotificationManagementException("Error occurred while opening a connection to" + - " the data source", e); - } catch (DeviceManagementDAOException e) { - throw new NotificationManagementException("Error occurred while retriving device data for " + + device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId, false); + } catch (DeviceManagementException e) { + throw new NotificationManagementException("Error occurred while retrieving device data for " + " adding notification", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); } return device; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationEnrolmentMapping.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationEnrolmentMapping.java new file mode 100644 index 0000000000..4bccaaca92 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationEnrolmentMapping.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.operation.mgt; + +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; + +/** + * This holds results of Pending-operations to enrolment mappings. + */ +public class OperationEnrolmentMapping { + + int enrolmentId; + int tenantId; + long createdTime; + String deviceType; + String deviceId; + EnrolmentInfo.Status deviceStatus; + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public int getEnrolmentId() { + return enrolmentId; + } + + public void setEnrolmentId(int enrolmentId) { + this.enrolmentId = enrolmentId; + } + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public long getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(long createdTime) { + this.createdTime = createdTime; + } + + public EnrolmentInfo.Status getDeviceStatus() { + return deviceStatus; + } + + public void setDeviceStatus(String deviceStatus) { + this.deviceStatus = EnrolmentInfo.Status.valueOf(deviceStatus); + } + + public String getDeviceType() { + return deviceType; + } + + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; + } +} 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 41530bfb48..c22f3de950 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 @@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.MonitoringOperation; @@ -151,7 +152,7 @@ public class OperationManagerImpl implements OperationManager { // check whether device list is greater than batch size notification strategy has enable to send push // notification using scheduler task if (DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). - getPushNotificationConfiguration().getSchedulerBatchSize() < authorizedDeviceList.size() && + getPushNotificationConfiguration().getSchedulerBatchSize() <= authorizedDeviceList.size() && notificationStrategy != null) { isScheduled = notificationStrategy.getConfig().isScheduled(); } @@ -193,6 +194,8 @@ public class OperationManagerImpl implements OperationManager { if (log.isDebugEnabled()) { log.debug("Sending push notification to " + deviceId + " from add operation method."); } + operation.setId(operationId); + operation.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + operationId); notificationStrategy.execute(new NotificationContext(deviceId, operation)); operationMappingDAO.updateOperationMapping(operationId, enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.PushNotificationStatus.COMPLETED); } catch (PushNotificationExecutionFailedException e) { @@ -293,19 +296,11 @@ public class OperationManagerImpl implements OperationManager { } private Device getDevice(DeviceIdentifier deviceId) throws OperationManagementException { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); try { - DeviceManagementDAOFactory.openConnection(); - return deviceDAO.getDevice(deviceId, tenantId); - } catch (SQLException e) { - throw new OperationManagementException("Error occurred while opening a connection the data " + - "source", e); - } catch (DeviceManagementDAOException e) { - OperationManagementDAOFactory.rollbackTransaction(); + return DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId, false); + } catch (DeviceManagementException e) { throw new OperationManagementException( - "Error occurred while retrieving device info", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); + "Error occurred while retrieving device info.", e); } } @@ -418,12 +413,8 @@ public class OperationManagerImpl implements OperationManager { int enrolmentId = enrolmentInfo.getId(); //Changing the enrollment status & attempt count if the device is marked as inactive or unreachable switch (enrolmentInfo.getStatus()) { - case ACTIVE: - this.resetAttemptCount(enrolmentId); - break; case INACTIVE: case UNREACHABLE: - this.resetAttemptCount(enrolmentId); this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE); break; } @@ -479,12 +470,8 @@ public class OperationManagerImpl implements OperationManager { int enrolmentId = enrolmentInfo.getId(); //Changing the enrollment status & attempt count if the device is marked as inactive or unreachable switch (enrolmentInfo.getStatus()) { - case ACTIVE: - this.resetAttemptCount(enrolmentId); - break; case INACTIVE: case UNREACHABLE: - this.resetAttemptCount(enrolmentId); this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE); break; } @@ -554,7 +541,7 @@ public class OperationManagerImpl implements OperationManager { Operation.Status.valueOf(operation.getStatus(). toString())); } - if (isUpdated && operation.getOperationResponse() != null) { + if (operation.getOperationResponse() != null) { operationDAO.addOperationResponse(enrolmentId, operationId, operation.getOperationResponse()); } OperationManagementDAOFactory.commitTransaction(); @@ -827,6 +814,28 @@ public class OperationManagerImpl implements OperationManager { } } + public Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) throws OperationManagementException { + // This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer. + int operationId = Integer.parseInt( + activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, "")); + if (operationId == 0) { + throw new IllegalArgumentException("Operation ID cannot be null or zero (0)."); + } + + Device device = this.getDevice(deviceId); + try { + OperationManagementDAOFactory.openConnection(); + return operationDAO.getActivityByDevice(operationId, device.getId()); + } catch (SQLException e) { + throw new OperationManagementException("Error occurred while opening a connection to the data source.", e); + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the operation with activity Id '" + + activity + " and device Id: " + deviceId.getId(), e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + } + @Override public List getOperationUpdatedAfter(long timestamp) throws OperationManagementException { return null; @@ -1040,24 +1049,6 @@ public class OperationManagerImpl implements OperationManager { return updateStatus; } - private boolean resetAttemptCount(int enrolmentId) throws OperationManagementException { - boolean resetStatus; - try { - OperationManagementDAOFactory.beginTransaction(); - resetStatus = operationDAO.resetAttemptCount(enrolmentId); - OperationManagementDAOFactory.commitTransaction(); - } catch (OperationManagementDAOException e) { - OperationManagementDAOFactory.rollbackTransaction(); - throw new OperationManagementException("Error occurred while resetting attempt count of device id : '" + - enrolmentId + "'", e); - } catch (TransactionManagementException e) { - throw new OperationManagementException("Error occurred while initiating a transaction", e); - } finally { - OperationManagementDAOFactory.closeConnection(); - } - return resetStatus; - } - private boolean isTaskScheduledOperation(Operation operation, List deviceIds) { DeviceManagementProviderService deviceManagementProviderService = DeviceManagementDataHolder.getInstance(). getDeviceManagementProvider(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerRepository.java index c9c863593c..8a44192f00 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerRepository.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerRepository.java @@ -18,7 +18,7 @@ */ package org.wso2.carbon.device.mgt.core.operation.mgt; -import org.wso2.carbon.device.mgt.common.DeviceTypeIdentifier; +import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import java.util.Map; @@ -26,21 +26,21 @@ import java.util.concurrent.ConcurrentHashMap; public class OperationManagerRepository { - private Map operationManagers; + private Map operationManagers; public OperationManagerRepository() { operationManagers = new ConcurrentHashMap<>(); } - public void addOperationManager(DeviceTypeIdentifier type, OperationManager operationManager) { + public void addOperationManager(DeviceTypeServiceIdentifier type, OperationManager operationManager) { operationManagers.put(type, operationManager); } - public OperationManager getOperationManager(DeviceTypeIdentifier type) { + public OperationManager getOperationManager(DeviceTypeServiceIdentifier type) { return operationManagers.get(type); } - public void removeOperationManager(DeviceTypeIdentifier type) { + public void removeOperationManager(DeviceTypeServiceIdentifier type) { operationManagers.remove(type); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationMapping.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationMapping.java index 6f42a78d15..d85fe5ea89 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationMapping.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationMapping.java @@ -27,6 +27,7 @@ public class OperationMapping { private DeviceIdentifier deviceIdentifier; private int operationId; + private int enrollmentId; private int tenantId; private Operation.Status status; private Operation.PushNotificationStatus pushNotificationStatus; @@ -39,6 +40,14 @@ public class OperationMapping { this.operationId = operationId; } + public int getEnrollmentId() { + return enrollmentId; + } + + public void setEnrollmentId(int enrollmentId) { + this.enrollmentId = enrollmentId; + } + public int getTenantId() { return tenantId; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java index 5e3848cf9b..dc9b6dfb9a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java @@ -70,6 +70,8 @@ public interface OperationDAO { Activity getActivity(int operationId) throws OperationManagementDAOException; + Activity getActivityByDevice(int operationId, int deviceId) throws OperationManagementDAOException; + int getEnrolmentIdFromMappingId(int enrollmentOpMappingId) throws OperationManagementDAOException; List getOperationsUpdatedAfter(long timestamp) throws OperationManagementDAOException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java index 72d02ec9bc..b28b773d7b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java @@ -18,10 +18,12 @@ */ package org.wso2.carbon.device.mgt.core.operation.mgt.dao; -import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping; +import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping; import java.util.List; +import java.util.Map; public interface OperationMappingDAO { @@ -34,4 +36,30 @@ public interface OperationMappingDAO { void updateOperationMapping(List operationMappingList) throws OperationManagementDAOException; + /** + * This method returns first pending/repeated operation available for each active enrolment of given device-type + * where the operation was created after the given timestamp. + * + * @param minDuration - Upper limit of Operation created time + * @param maxDuration - Lower limit of Operation created time + * @param deviceTypeId - Device Type Id of required devices + * @return List - List of OperationEnrolmentMapping objects containing required data + * @throws OperationManagementDAOException + */ + List getFirstPendingOperationMappingsForActiveEnrolments(long minDuration, + long maxDuration, int deviceTypeId) + throws OperationManagementDAOException; + + /** + * This method returns the timestamp of last completed Operation for each active enrolment of given device-type + * where the operation was completed after the given timestamp. + * + * @param timeStamp - Timestamp of considered time-interval + * @param deviceTypeId - Device Type of required devices + * @return List - List of OperationEnrolmentMapping objects containing required data + * @throws OperationManagementDAOException + */ + Map getLastConnectedTimeForActiveEnrolments(long timeStamp, int deviceTypeId) + throws OperationManagementDAOException; + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java index c847c7652c..3020096972 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java @@ -178,6 +178,7 @@ public class ConfigOperationDAOImpl extends GenericOperationDAOImpl { ois = new ObjectInputStream(bais); configOperation = (ConfigOperation) ois.readObject(); configOperation.setStatus(status); + configOperation.setId(rs.getInt("OPERATION_ID")); operations.add(configOperation); } } catch (IOException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index 3e50f49800..b0cc226c43 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -135,9 +135,9 @@ public class GenericOperationDAOImpl implements OperationDAO { ResultSet rs = null; try { Connection connection = OperationManagementDAOFactory.getConnection(); - String query = "SELECT EOM.ID FROM DM_ENROLMENT_OP_MAPPING AS EOM INNER JOIN DM_OPERATION DM " + - "ON DM.ID = EOM.OPERATION_ID WHERE EOM.ENROLMENT_ID = ? AND DM.OPERATION_CODE = ? " + - "AND EOM.STATUS = ?;"; + String query = "SELECT EOM.ID FROM DM_ENROLMENT_OP_MAPPING EOM INNER JOIN DM_OPERATION DM " + + "ON DM.ID = EOM.OPERATION_ID WHERE EOM.ENROLMENT_ID = ? AND DM.OPERATION_CODE = ? " + + "AND EOM.STATUS = ?"; stmt = connection.prepareStatement(query); stmt.setInt(1, enrolmentId); stmt.setString(2, operationCode); @@ -149,8 +149,8 @@ public class GenericOperationDAOImpl implements OperationDAO { id = rs.getInt("ID"); } if (id != 0) { - stmt = connection.prepareStatement("UPDATE DM_ENROLMENT_OP_MAPPING SET STATUS = ?, " + - "UPDATED_TIMESTAMP = ? WHERE ID = ?"); + stmt = connection.prepareStatement( + "UPDATE DM_ENROLMENT_OP_MAPPING SET STATUS = ?, " + "UPDATED_TIMESTAMP = ? WHERE ID = ?"); stmt.setString(1, newStatus.toString()); stmt.setLong(2, System.currentTimeMillis() / 1000); stmt.setInt(3, id); @@ -158,8 +158,8 @@ public class GenericOperationDAOImpl implements OperationDAO { } } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while update device mapping operation status " + - "metadata", e); + throw new OperationManagementDAOException( + "Error occurred while update device mapping operation status " + "metadata", e); } finally { OperationManagementDAOUtil.cleanupResources(stmt); } @@ -173,9 +173,9 @@ public class GenericOperationDAOImpl implements OperationDAO { boolean result = false; try { Connection connection = OperationManagementDAOFactory.getConnection(); - String query = "SELECT EOM.ID FROM DM_ENROLMENT_OP_MAPPING AS EOM INNER JOIN DM_OPERATION DM " + - "ON DM.ID = EOM.OPERATION_ID WHERE EOM.ENROLMENT_ID = ? AND DM.OPERATION_CODE = ? AND " + - "EOM.STATUS = ?;"; + String query = "SELECT EOM.ID FROM DM_ENROLMENT_OP_MAPPING EOM INNER JOIN DM_OPERATION DM " + + "ON DM.ID = EOM.OPERATION_ID WHERE EOM.ENROLMENT_ID = ? AND DM.OPERATION_CODE = ? AND " + + "EOM.STATUS = ?"; stmt = connection.prepareStatement(query); stmt.setInt(1, enrolmentId); stmt.setString(2, operationCode); @@ -187,18 +187,18 @@ public class GenericOperationDAOImpl implements OperationDAO { id = rs.getInt("ID"); } if (id != 0) { - stmt = connection.prepareStatement("UPDATE DM_ENROLMENT_OP_MAPPING SET UPDATED_TIMESTAMP = ? " + - "WHERE ID = ?"); + stmt = connection.prepareStatement( + "UPDATE DM_ENROLMENT_OP_MAPPING SET UPDATED_TIMESTAMP = ? " + "WHERE ID = ?"); stmt.setLong(1, System.currentTimeMillis() / 1000); stmt.setInt(2, id); stmt.executeUpdate(); result = true; } } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while update device mapping operation status " + - "metadata", e); + throw new OperationManagementDAOException( + "Error occurred while update device mapping operation status " + "metadata", e); } finally { - OperationManagementDAOUtil.cleanupResources(stmt); + OperationManagementDAOUtil.cleanupResources(stmt, rs); } return result; } @@ -209,18 +209,31 @@ public class GenericOperationDAOImpl implements OperationDAO { PreparedStatement stmt = null; ByteArrayOutputStream bao = null; ObjectOutputStream oos = null; + ResultSet rs = null; try { Connection connection = OperationManagementDAOFactory.getConnection(); - stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID,ENROLMENT_ID," + - "OPERATION_RESPONSE, RECEIVED_TIMESTAMP) VALUES(?, ?, ?, ?)"); + + stmt = connection.prepareStatement("SELECT ID FROM DM_ENROLMENT_OP_MAPPING WHERE ENROLMENT_ID = ? " + + "AND OPERATION_ID = ?"); + stmt.setInt(1, enrolmentId); + stmt.setInt(2, operationId); + + rs = stmt.executeQuery(); + int enPrimaryId = 0; + if(rs.next()){ + enPrimaryId = rs.getInt("ID"); + } + stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID, ENROLMENT_ID, " + + "EN_OP_MAP_ID, OPERATION_RESPONSE, RECEIVED_TIMESTAMP) VALUES(?, ?, ?, ?, ?)"); bao = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bao); oos.writeObject(operationResponse); stmt.setInt(1, operationId); stmt.setInt(2, enrolmentId); - stmt.setBytes(3, bao.toByteArray()); - stmt.setTimestamp(4, new Timestamp(new Date().getTime())); + stmt.setInt(3, enPrimaryId); + stmt.setBytes(4, bao.toByteArray()); + stmt.setTimestamp(5, new Timestamp(new Date().getTime())); stmt.executeUpdate(); } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while inserting operation response", e); @@ -241,7 +254,7 @@ public class GenericOperationDAOImpl implements OperationDAO { log.warn("Error occurred while closing ObjectOutputStream", e); } } - OperationManagementDAOUtil.cleanupResources(stmt); + OperationManagementDAOUtil.cleanupResources(stmt, rs); } } @@ -310,6 +323,82 @@ public class GenericOperationDAOImpl implements OperationDAO { @Override public Activity getActivity(int operationId) throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Activity activity = null; + List activityStatusList = new ArrayList<>(); + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT eom.ENROLMENT_ID, eom.OPERATION_ID, eom.ID AS EOM_MAPPING_ID, dor.ID AS OP_RES_ID,\n" + + "de.DEVICE_ID, d.DEVICE_IDENTIFICATION, \n" + + "d.DEVICE_TYPE_ID, dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, \n" + + "eom.UPDATED_TIMESTAMP, op.OPERATION_CODE, op.TYPE AS OPERATION_TYPE, dor.OPERATION_RESPONSE, \n" + + "dor.RECEIVED_TIMESTAMP FROM DM_ENROLMENT_OP_MAPPING eom \n" + + "INNER JOIN DM_OPERATION op ON op.ID=eom.OPERATION_ID\n" + + "INNER JOIN DM_ENROLMENT de ON de.ID=eom.ENROLMENT_ID\n" + + "INNER JOIN DM_DEVICE d ON d.ID=de.DEVICE_ID \n" + + "INNER JOIN DM_DEVICE_TYPE dt ON dt.ID=d.DEVICE_TYPE_ID\n" + + "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE dor ON dor.ENROLMENT_ID=de.id \n" + + "AND dor.OPERATION_ID = eom.OPERATION_ID\n" + + "WHERE eom.OPERATION_ID = ? AND de.TENANT_ID = ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, operationId); + stmt.setInt(2, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + rs = stmt.executeQuery(); + + int enrolmentId = 0; + ActivityStatus activityStatus = null; + + while (rs.next()) { + if (enrolmentId == 0) { + activity = new Activity(); + activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); + activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString()); + activity.setCode(rs.getString("OPERATION_CODE")); + } + if (enrolmentId != rs.getInt("ENROLMENT_ID")) { + activityStatus = new ActivityStatus(); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + deviceIdentifier.setType(rs.getString("DEVICE_TYPE_NAME")); + activityStatus.setDeviceIdentifier(deviceIdentifier); + + activityStatus.setStatus(ActivityStatus.Status.valueOf(rs.getString("STATUS"))); + + List operationResponses = new ArrayList<>(); + if (rs.getInt("UPDATED_TIMESTAMP") != 0) { + activityStatus.setUpdatedTimestamp(new java.util.Date(rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } + activityStatus.setResponses(operationResponses); + + activityStatusList.add(activityStatus); + + enrolmentId = rs.getInt("ENROLMENT_ID"); + activity.setActivityStatus(activityStatusList); + } else { + if (rs.getInt("UPDATED_TIMESTAMP") != 0) { + activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + } + } + } + } catch (SQLException e) { + throw new OperationManagementDAOException("Error occurred while getting the operation details from " + + "the database.", e); + } catch (ClassNotFoundException e) { + throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e); + } catch (IOException e) { + throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return activity; + } + + public Activity getActivityByDevice(int operationId, int deviceId) throws OperationManagementDAOException { + PreparedStatement stmt = null; ResultSet rs = null; Activity activity = null; @@ -327,11 +416,12 @@ public class GenericOperationDAOImpl implements OperationDAO { "INNER JOIN DM_DEVICE_TYPE AS dt ON dt.ID=d.DEVICE_TYPE_ID\n" + "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE AS dor ON dor.ENROLMENT_ID=de.id \n" + "AND dor.OPERATION_ID = eom.OPERATION_ID\n" + - "WHERE eom.OPERATION_ID = ? AND de.TENANT_ID = ?"; + "WHERE eom.OPERATION_ID = ? AND de.device_id = ? AND de.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, operationId); - stmt.setInt(2, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + stmt.setInt(2, deviceId); + stmt.setInt(3, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); rs = stmt.executeQuery(); int enrolmentId = 0; @@ -397,27 +487,8 @@ public class GenericOperationDAOImpl implements OperationDAO { List activities = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); -// String sql = "SELECT eom.ENROLMENT_ID, eom.OPERATION_ID, eom.ID AS EOM_MAPPING_ID, dor.ID AS OP_RES_ID,\n" + -// "de.DEVICE_ID, d.DEVICE_IDENTIFICATION, \n" + -// "d.DEVICE_TYPE_ID, dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, \n" + -// "eom.UPDATED_TIMESTAMP, op.OPERATION_CODE, op.TYPE AS OPERATION_TYPE, dor.OPERATION_RESPONSE, \n" + -// "dor.RECEIVED_TIMESTAMP FROM DM_ENROLMENT_OP_MAPPING AS eom \n" + -// "INNER JOIN DM_OPERATION AS op ON op.ID=eom.OPERATION_ID\n" + -// "INNER JOIN DM_ENROLMENT AS de ON de.ID=eom.ENROLMENT_ID\n" + -// "INNER JOIN DM_DEVICE AS d ON d.ID=de.DEVICE_ID \n" + -// "INNER JOIN DM_DEVICE_TYPE AS dt ON dt.ID=d.DEVICE_TYPE_ID\n" + -// "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE AS dor ON dor.ENROLMENT_ID=de.id \n" + -// "AND dor.OPERATION_ID=eom.OPERATION_ID\n" + -// "WHERE eom.UPDATED_TIMESTAMP > ? AND de.TENANT_ID = ? ORDER BY eom.OPERATION_ID"; -// if(limit > 0) { -// sql = sql + " LIMIT ?"; -// } -// -// if(offset > 0) { -// sql = sql + " OFFSET ?"; -// } - +/* String sql = "SELECT opm.ENROLMENT_ID, opm.CREATED_TIMESTAMP, opm.UPDATED_TIMESTAMP, opm.OPERATION_ID,\n" + "op.OPERATION_CODE, op.TYPE as OPERATION_TYPE, opm.STATUS, en.DEVICE_ID,\n" + "ops.RECEIVED_TIMESTAMP, ops.ID as OP_RES_ID, ops.OPERATION_RESPONSE,\n" + @@ -437,15 +508,60 @@ public class GenericOperationDAOImpl implements OperationDAO { } else { sql += "ORDER BY opm.UPDATED_TIMESTAMP asc LIMIT ? OFFSET ?"; } - +*/ + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String sql = "SELECT " + + " opr.ENROLMENT_ID, " + + " opr.CREATED_TIMESTAMP, " + + " opr.UPDATED_TIMESTAMP, " + + " opr.OPERATION_ID, " + + " opr.OPERATION_CODE, " + + " opr.OPERATION_TYPE, " + + " opr.STATUS, " + + " opr.DEVICE_ID, " + + " opr.DEVICE_IDENTIFICATION, " + + " opr.DEVICE_TYPE, " + + " ops.RECEIVED_TIMESTAMP, " + + " ops.ID OP_RES_ID, " + + " ops.OPERATION_RESPONSE " + + " FROM " + + " (SELECT " + + " opm.ID MAPPING_ID, " + + " opm.ENROLMENT_ID, " + + " opm.CREATED_TIMESTAMP, " + + " opm.UPDATED_TIMESTAMP, " + + " opm.OPERATION_ID, " + + " op.OPERATION_CODE, " + + " op.TYPE OPERATION_TYPE, " + + " opm.STATUS, " + + " en.DEVICE_ID, " + + " de.DEVICE_IDENTIFICATION, " + + " dt.NAME DEVICE_TYPE, " + + " de.TENANT_ID " + + " FROM" + + " DM_ENROLMENT_OP_MAPPING opm " + + " INNER JOIN DM_OPERATION op ON opm.OPERATION_ID = op.ID " + + " INNER JOIN DM_ENROLMENT en ON opm.ENROLMENT_ID = en.ID " + + " INNER JOIN DM_DEVICE de ON en.DEVICE_ID = de.ID " + + " INNER JOIN DM_DEVICE_TYPE dt ON dt.ID = de.DEVICE_TYPE_ID " + + " WHERE " + + " opm.UPDATED_TIMESTAMP > ? " + + " AND de.TENANT_ID = ? " + + " ORDER BY opm.UPDATED_TIMESTAMP " + + " LIMIT ? OFFSET ?) opr " + + " LEFT JOIN DM_DEVICE_OPERATION_RESPONSE ops ON opr.MAPPING_ID = ops.EN_OP_MAP_ID " + + " WHERE " + + " opr.UPDATED_TIMESTAMP > ? " + + " AND opr.TENANT_ID = ? "; stmt = conn.prepareStatement(sql); stmt.setLong(1, timestamp); - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); stmt.setInt(2, tenantId); stmt.setInt(3, limit); stmt.setInt(4, offset); + stmt.setLong(5, timestamp); + stmt.setInt(6, tenantId); rs = stmt.executeQuery(); @@ -548,9 +664,9 @@ public class GenericOperationDAOImpl implements OperationDAO { ResultSet rs = null; try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT COUNT(*) AS COUNT FROM DM_ENROLMENT_OP_MAPPING AS m \n" + - "INNER JOIN DM_ENROLMENT AS d ON m.ENROLMENT_ID = d.ID \n" + - "WHERE m.UPDATED_TIMESTAMP > ? AND d.TENANT_ID = ?;"; + String sql = "SELECT COUNT(*) AS COUNT FROM DM_ENROLMENT_OP_MAPPING m \n" + + "INNER JOIN DM_ENROLMENT d ON m.ENROLMENT_ID = d.ID \n" + + "WHERE m.UPDATED_TIMESTAMP > ? AND d.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setLong(1, timestamp); stmt.setInt(2, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); @@ -559,8 +675,8 @@ public class GenericOperationDAOImpl implements OperationDAO { return rs.getInt("COUNT"); } } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while getting the activity count from " + - "the database.", e); + throw new OperationManagementDAOException( + "Error occurred while getting the activity count from " + "the database.", e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -1104,10 +1220,10 @@ public class GenericOperationDAOImpl implements OperationDAO { Map> operationMappingsTenantMap = new HashMap<>(); try { conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT op.ENROLMENT_ID, op.OPERATION_ID, dt.NAME ,d.TENANT_ID FROM DM_DEVICE d, " + - "DM_ENROLMENT_OP_MAPPING op, DM_DEVICE_TYPE dt WHERE op.STATUS = ? AND " + - "op.PUSH_NOTIFICATION_STATUS = ? AND d.DEVICE_TYPE_ID = dt.ID AND d.ID=op.ENROLMENT_ID ORDER BY " + - "op.OPERATION_ID LIMIT ?"; + String sql = "SELECT op.ENROLMENT_ID, op.OPERATION_ID, d.DEVICE_IDENTIFICATION, dt.NAME as DEVICE_TYPE, " + + "d.TENANT_ID FROM DM_DEVICE d, DM_ENROLMENT_OP_MAPPING op, DM_DEVICE_TYPE dt WHERE op.STATUS = ?" + + " AND op.PUSH_NOTIFICATION_STATUS = ? AND d.DEVICE_TYPE_ID = dt.ID AND d.ID=op.ENROLMENT_ID ORDER" + + " BY op.OPERATION_ID LIMIT ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, opStatus.toString()); stmt.setString(2, pushNotificationStatus.toString()); @@ -1122,8 +1238,11 @@ public class GenericOperationDAOImpl implements OperationDAO { } operationMapping = new OperationMapping(); operationMapping.setOperationId(rs.getInt("OPERATION_ID")); - operationMapping.setDeviceIdentifier(new DeviceIdentifier(String.valueOf(rs.getInt("ENROLMENT_ID")), - rs.getString("NAME"))); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + deviceIdentifier.setType(rs.getString("DEVICE_TYPE")); + operationMapping.setDeviceIdentifier(deviceIdentifier); + operationMapping.setEnrollmentId(rs.getInt("ENROLMENT_ID")); operationMapping.setTenantId(tenantID); operationMappings.add(operationMapping); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java index 0846813fdf..9399b40b46 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java @@ -18,7 +18,9 @@ */ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; @@ -27,8 +29,12 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationMappingDAO; import java.sql.Connection; import java.sql.PreparedStatement; +import java.sql.ResultSet; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; public class OperationMappingDAOImpl implements OperationMappingDAO { @@ -109,7 +115,7 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { if (conn.getMetaData().supportsBatchUpdates()) { for (OperationMapping operationMapping : operationMappingList) { stmt.setString(1, operationMapping.getPushNotificationStatus().toString()); - stmt.setInt(2, Integer.parseInt(operationMapping.getDeviceIdentifier().getId())); + stmt.setInt(2, operationMapping.getEnrollmentId()); stmt.setInt(3, operationMapping.getOperationId()); stmt.addBatch(); } @@ -117,7 +123,7 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { } else { for (OperationMapping operationMapping : operationMappingList) { stmt.setString(1, operationMapping.getPushNotificationStatus().toString()); - stmt.setInt(2, Integer.parseInt(operationMapping.getDeviceIdentifier().getId())); + stmt.setInt(2, operationMapping.getEnrollmentId()); stmt.setInt(3, operationMapping.getOperationId()); stmt.executeUpdate(); } @@ -129,4 +135,83 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { OperationManagementDAOUtil.cleanupResources(stmt, null); } } + + @Override + public List getFirstPendingOperationMappingsForActiveEnrolments(long minDuration, + long maxDuration, int deviceTypeId) throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + List enrolmentOperationMappingList = null; + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + //We are specifically looking for operation mappings in 'Pending' & 'Repeated' states. Further we want + //devices to be active at that moment. Hence filtering by 'ACTIVE' & 'UNREACHABLE' device states. + String sql = "SELECT ENROLMENT_ID, D.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFIER, MIN(CREATED_TIMESTAMP) " + + "AS CREATED_TIMESTAMP, E.STATUS AS ENROLMENT_STATUS, E.TENANT_ID FROM " + + "DM_ENROLMENT_OP_MAPPING OP INNER JOIN DM_ENROLMENT E ON OP.ENROLMENT_ID = E.ID INNER JOIN " + + "DM_DEVICE D ON E.DEVICE_ID = D.ID WHERE " + + "OP.STATUS IN ('"+ Operation.Status.PENDING.name() + "','" + Operation.Status.REPEATED.name() + "') " + + "AND OP.CREATED_TIMESTAMP BETWEEN ? AND ? AND E.STATUS IN ('" + EnrolmentInfo.Status.ACTIVE.name() + + "','" + EnrolmentInfo.Status.UNREACHABLE.name() + "') AND D.DEVICE_TYPE_ID = ? GROUP BY ENROLMENT_ID," + + " D.DEVICE_IDENTIFICATION, E.STATUS, E.TENANT_ID"; + stmt = conn.prepareStatement(sql); + stmt.setLong(1, maxDuration); + stmt.setLong(2, minDuration); + stmt.setInt(3, deviceTypeId); + rs = stmt.executeQuery(); + enrolmentOperationMappingList = new ArrayList<>(); + while (rs.next()) { + OperationEnrolmentMapping enrolmentOperationMapping = this.getEnrolmentOpMapping(rs); + enrolmentOperationMappingList.add(enrolmentOperationMapping); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("Error occurred while fetching pending operation mappings for " + + "active devices of type '" + deviceTypeId + "'", e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return enrolmentOperationMappingList; + } + + @Override + public Map getLastConnectedTimeForActiveEnrolments(long timeStamp, int deviceTypeId) throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Map lastConnectedTimeMap = null; + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + //We are specifically looking for operation mappings in 'Pending' & 'Repeated' states. Further we want + //devices to be active at that moment. Hence filtering by 'ACTIVE' & 'UNREACHABLE' device states. + String sql = "SELECT OP.ENROLMENT_ID AS EID, MAX(OP.UPDATED_TIMESTAMP) AS LAST_CONNECTED_TIME FROM " + + "DM_ENROLMENT_OP_MAPPING OP INNER JOIN DM_ENROLMENT E ON OP.ENROLMENT_ID = E.ID INNER JOIN " + + "DM_DEVICE D ON E.DEVICE_ID = D.ID WHERE " + + "OP.STATUS = '" + Operation.Status.COMPLETED.name() + "'" + + "AND OP.UPDATED_TIMESTAMP >= ? AND E.STATUS IN ('" + EnrolmentInfo.Status.ACTIVE.name() + + "','" + EnrolmentInfo.Status.UNREACHABLE.name() + "') AND D.DEVICE_TYPE_ID = ? GROUP BY ENROLMENT_ID"; + stmt = conn.prepareStatement(sql); + stmt.setLong(1, timeStamp); + stmt.setInt(2, deviceTypeId); + rs = stmt.executeQuery(); + lastConnectedTimeMap = new HashMap<>(); + while (rs.next()) { + lastConnectedTimeMap.put(rs.getInt("EID"), rs.getLong("LAST_CONNECTED_TIME")); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("Error occurred while fetching last connected time for " + + "active devices of type '" + deviceTypeId + "'", e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return lastConnectedTimeMap; + } + + private OperationEnrolmentMapping getEnrolmentOpMapping(ResultSet rs) throws SQLException { + OperationEnrolmentMapping enrolmentOperationMapping = new OperationEnrolmentMapping(); + enrolmentOperationMapping.setEnrolmentId(rs.getInt("ENROLMENT_ID")); + enrolmentOperationMapping.setDeviceId(rs.getString("DEVICE_IDENTIFIER")); + enrolmentOperationMapping.setTenantId(rs.getInt("TENANT_ID")); + enrolmentOperationMapping.setCreatedTime(rs.getLong("CREATED_TIMESTAMP")); + enrolmentOperationMapping.setDeviceStatus(rs.getString("ENROLMENT_STATUS")); + return enrolmentOperationMapping; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/MySQLOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/MySQLOperationDAOImpl.java index db625f483c..f935cab57a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/MySQLOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/MySQLOperationDAOImpl.java @@ -18,15 +18,25 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; +import org.wso2.carbon.device.mgt.common.operation.mgt.ActivityStatus; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationResponse; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.GenericOperationDAOImpl; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil; +import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; +import java.sql.ResultSet; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; /** * This class holds the implementation of OperationDAO which can be used to support MySQl db syntax. @@ -66,4 +76,163 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { } return isUpdated; } + + + @Override + public List getActivitiesUpdatedAfter(long timestamp, int limit, + int offset) throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + List activities = new ArrayList<>(); + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String sql = "SELECT " + + " opr.ENROLMENT_ID, " + + " opr.CREATED_TIMESTAMP, " + + " opr.UPDATED_TIMESTAMP, " + + " opr.OPERATION_ID, " + + " opr.OPERATION_CODE, " + + " opr.OPERATION_TYPE, " + + " opr.STATUS, " + + " opr.DEVICE_ID, " + + " opr.DEVICE_IDENTIFICATION, " + + " opr.DEVICE_TYPE, " + + " ops.RECEIVED_TIMESTAMP, " + + " ops.ID OP_RES_ID, " + + " ops.OPERATION_RESPONSE " + + " FROM " + + " (SELECT " + + " opm.ID MAPPING_ID, " + + " opm.ENROLMENT_ID, " + + " opm.CREATED_TIMESTAMP, " + + " opm.UPDATED_TIMESTAMP, " + + " opm.OPERATION_ID, " + + " op.OPERATION_CODE, " + + " op.TYPE OPERATION_TYPE, " + + " opm.STATUS, " + + " en.DEVICE_ID, " + + " de.DEVICE_IDENTIFICATION, " + + " dt.NAME DEVICE_TYPE, " + + " de.TENANT_ID " + + " FROM" + + " DM_ENROLMENT_OP_MAPPING opm FORCE INDEX (IDX_ENROLMENT_OP_MAPPING) " + + " INNER JOIN DM_OPERATION op ON opm.OPERATION_ID = op.ID " + + " INNER JOIN DM_ENROLMENT en ON opm.ENROLMENT_ID = en.ID " + + " INNER JOIN DM_DEVICE de ON en.DEVICE_ID = de.ID " + + " INNER JOIN DM_DEVICE_TYPE dt ON dt.ID = de.DEVICE_TYPE_ID " + + " WHERE" + + " opm.UPDATED_TIMESTAMP > ? " + + " AND de.TENANT_ID = ? " + + " ORDER BY opm.UPDATED_TIMESTAMP " + + " LIMIT ? OFFSET ?) opr " + + " LEFT JOIN DM_DEVICE_OPERATION_RESPONSE ops ON opr.MAPPING_ID = ops.EN_OP_MAP_ID " + + " WHERE " + + " opr.UPDATED_TIMESTAMP > ? " + + " AND opr.TENANT_ID = ? "; + + stmt = conn.prepareStatement(sql); + + stmt.setLong(1, timestamp); + stmt.setInt(2, tenantId); + stmt.setInt(3, limit); + stmt.setInt(4, offset); + stmt.setLong(5, timestamp); + stmt.setInt(6, tenantId); + + rs = stmt.executeQuery(); + + int operationId = 0; + int enrolmentId = 0; + int responseId = 0; + Activity activity = null; + ActivityStatus activityStatus = null; + while (rs.next()) { + + if (operationId != rs.getInt("OPERATION_ID")) { + activity = new Activity(); + activities.add(activity); + List statusList = new ArrayList<>(); + activityStatus = new ActivityStatus(); + + operationId = rs.getInt("OPERATION_ID"); + enrolmentId = rs.getInt("ENROLMENT_ID"); + + activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); + activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString()); + activity.setCode(rs.getString("OPERATION_CODE")); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + deviceIdentifier.setType(rs.getString("DEVICE_TYPE")); + activityStatus.setDeviceIdentifier(deviceIdentifier); + + activityStatus.setStatus(ActivityStatus.Status.valueOf(rs.getString("STATUS"))); + + List operationResponses = new ArrayList<>(); + if (rs.getInt("UPDATED_TIMESTAMP") != 0) { + activityStatus.setUpdatedTimestamp(new java.util.Date( + rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); + + } + if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + responseId = rs.getInt("OP_RES_ID"); + } + activityStatus.setResponses(operationResponses); + statusList.add(activityStatus); + activity.setActivityStatus(statusList); + activity.setActivityId(OperationDAOUtil.getActivityId(rs.getInt("OPERATION_ID"))); + + } + + if (operationId == rs.getInt("OPERATION_ID") && enrolmentId != rs.getInt("ENROLMENT_ID")) { + activityStatus = new ActivityStatus(); + + activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); + activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString()); + activity.setCode(rs.getString("OPERATION_CODE")); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + deviceIdentifier.setType(rs.getString("DEVICE_TYPE")); + activityStatus.setDeviceIdentifier(deviceIdentifier); + + activityStatus.setStatus(ActivityStatus.Status.valueOf(rs.getString("STATUS"))); + + List operationResponses = new ArrayList<>(); + if (rs.getInt("UPDATED_TIMESTAMP") != 0) { + activityStatus.setUpdatedTimestamp(new java.util.Date( + rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); + } + if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + responseId = rs.getInt("OP_RES_ID"); + } + activityStatus.setResponses(operationResponses); + activity.getActivityStatus().add(activityStatus); + + enrolmentId = rs.getInt("ENROLMENT_ID"); + } + + if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) { + if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { + activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + responseId = rs.getInt("OP_RES_ID"); + } + } + } + } catch (SQLException e) { + throw new OperationManagementDAOException("Error occurred while getting the operation details from " + + "the database.", e); + } catch (ClassNotFoundException e) { + throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e); + } catch (IOException e) { + throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return activities; + } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java index 321a13e46c..ac3607ce25 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java @@ -138,77 +138,47 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { } @Override - public void updateEnrollmentOperationsStatus(int enrolmentId, String operationCode, - Operation.Status existingStatus, Operation.Status newStatus) throws OperationManagementDAOException { + public Map> getOperationMappingsByStatus(Operation.Status opStatus, Operation.PushNotificationStatus pushNotificationStatus, + int limit) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; + OperationMapping operationMapping; + Map> operationMappingsTenantMap = new HashMap<>(); try { - Connection connection = OperationManagementDAOFactory.getConnection(); - String query = "SELECT EOM.ID FROM DM_ENROLMENT_OP_MAPPING EOM INNER JOIN DM_OPERATION DM " - + "ON DM.ID = EOM.OPERATION_ID WHERE EOM.ENROLMENT_ID = ? AND DM.OPERATION_CODE = ? " - + "AND EOM.STATUS = ?"; - stmt = connection.prepareStatement(query); - stmt.setInt(1, enrolmentId); - stmt.setString(2, operationCode); - stmt.setString(3, existingStatus.toString()); - // This will return only one result always. - rs = stmt.executeQuery(); - int id = 0; - while (rs.next()) { - id = rs.getInt("ID"); - } - if (id != 0) { - stmt = connection.prepareStatement( - "UPDATE DM_ENROLMENT_OP_MAPPING SET STATUS = ?, " + "UPDATED_TIMESTAMP = ? WHERE ID = ?"); - stmt.setString(1, newStatus.toString()); - stmt.setLong(2, System.currentTimeMillis() / 1000); - stmt.setInt(3, id); - stmt.executeUpdate(); - } - - } catch (SQLException e) { - throw new OperationManagementDAOException( - "Error occurred while update device mapping operation status " + "metadata", e); - } finally { - OperationManagementDAOUtil.cleanupResources(stmt); - } - } + Connection conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT op.ENROLMENT_ID, op.OPERATION_ID, d.DEVICE_IDENTIFICATION, dt.NAME as DEVICE_TYPE, d" + + ".TENANT_ID FROM DM_DEVICE d, DM_ENROLMENT_OP_MAPPING op, DM_DEVICE_TYPE dt WHERE op.STATUS = ? " + + "AND op.PUSH_NOTIFICATION_STATUS = ? AND d.DEVICE_TYPE_ID = dt.ID AND d.ID=op.ENROLMENT_ID AND " + + "ROWNUM <= ? ORDER BY op.OPERATION_ID"; - @Override - public boolean updateTaskOperation(int enrolmentId, String operationCode) throws OperationManagementDAOException { - PreparedStatement stmt = null; - ResultSet rs = null; - boolean result = false; - try { - Connection connection = OperationManagementDAOFactory.getConnection(); - String query = "SELECT EOM.ID FROM DM_ENROLMENT_OP_MAPPING EOM INNER JOIN DM_OPERATION DM " - + "ON DM.ID = EOM.OPERATION_ID WHERE EOM.ENROLMENT_ID = ? AND DM.OPERATION_CODE = ? AND " - + "EOM.STATUS = ?"; - stmt = connection.prepareStatement(query); - stmt.setInt(1, enrolmentId); - stmt.setString(2, operationCode); - stmt.setString(3, Operation.Status.PENDING.toString()); - // This will return only one result always. + stmt = conn.prepareStatement(sql); + stmt.setString(1, opStatus.toString()); + stmt.setString(2, pushNotificationStatus.toString()); + stmt.setInt(3, limit); rs = stmt.executeQuery(); - int id = 0; - if (rs.next()) { - id = rs.getInt("ID"); - } - if (id != 0) { - stmt = connection.prepareStatement( - "UPDATE DM_ENROLMENT_OP_MAPPING SET UPDATED_TIMESTAMP = ? " + "WHERE ID = ?"); - stmt.setLong(1, System.currentTimeMillis() / 1000); - stmt.setInt(2, id); - stmt.executeUpdate(); - result = true; + while (rs.next()) { + int tenantID = rs.getInt("TENANT_ID"); + List operationMappings = operationMappingsTenantMap.get(tenantID); + if (operationMappings == null) { + operationMappings = new LinkedList<>(); + operationMappingsTenantMap.put(tenantID, operationMappings); + } + operationMapping = new OperationMapping(); + operationMapping.setOperationId(rs.getInt("OPERATION_ID")); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + deviceIdentifier.setType(rs.getString("DEVICE_TYPE")); + operationMapping.setDeviceIdentifier(deviceIdentifier); + operationMapping.setEnrollmentId(rs.getInt("ENROLMENT_ID")); + operationMapping.setTenantId(tenantID); + operationMappings.add(operationMapping); } } catch (SQLException e) { - throw new OperationManagementDAOException( - "Error occurred while update device mapping operation status " + "metadata", e); + throw new OperationManagementDAOException("SQL error while getting operation mappings from database. ", e); } finally { - OperationManagementDAOUtil.cleanupResources(stmt); + OperationManagementDAOUtil.cleanupResources(stmt, rs); } - return result; + return operationMappingsTenantMap; } @Override @@ -218,7 +188,7 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { List activities = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT opm.ENROLMENT_ID, opm.CREATED_TIMESTAMP, opm.UPDATED_TIMESTAMP, opm.OPERATION_ID,\n" + /*String sql = "SELECT opm.ENROLMENT_ID, opm.CREATED_TIMESTAMP, opm.UPDATED_TIMESTAMP, opm.OPERATION_ID,\n" + "op.OPERATION_CODE, op.TYPE OPERATION_TYPE, opm.STATUS, en.DEVICE_ID,\n" + "ops.RECEIVED_TIMESTAMP, ops.ID OP_RES_ID, ops.OPERATION_RESPONSE,\n" + "de.DEVICE_IDENTIFICATION, dt.NAME DEVICE_TYPE\n" + "FROM DM_ENROLMENT_OP_MAPPING opm\n" @@ -235,12 +205,62 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { } else { sql += "ORDER BY opm.UPDATED_TIMESTAMP asc OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; } + */ + + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + String sql = "SELECT " + + " opr.ENROLMENT_ID, " + + " opr.CREATED_TIMESTAMP, " + + " opr.UPDATED_TIMESTAMP, " + + " opr.OPERATION_ID, " + + " opr.OPERATION_CODE, " + + " opr.OPERATION_TYPE, " + + " opr.STATUS, " + + " opr.DEVICE_ID, " + + " opr.DEVICE_IDENTIFICATION, " + + " opr.DEVICE_TYPE, " + + " ops.RECEIVED_TIMESTAMP, " + + " ops.ID OP_RES_ID, " + + " ops.OPERATION_RESPONSE " + + " FROM " + + " (SELECT " + + " opm.ID MAPPING_ID, " + + " opm.ENROLMENT_ID, " + + " opm.CREATED_TIMESTAMP, " + + " opm.UPDATED_TIMESTAMP, " + + " opm.OPERATION_ID, " + + " op.OPERATION_CODE, " + + " op.TYPE OPERATION_TYPE, " + + " opm.STATUS, " + + " en.DEVICE_ID, " + + " de.DEVICE_IDENTIFICATION, " + + " dt.NAME DEVICE_TYPE, " + + " de.TENANT_ID " + + " FROM " + + " DM_ENROLMENT_OP_MAPPING opm " + + " INNER JOIN DM_OPERATION op ON opm.OPERATION_ID = op.ID " + + " INNER JOIN DM_ENROLMENT en ON opm.ENROLMENT_ID = en.ID " + + " INNER JOIN DM_DEVICE de ON en.DEVICE_ID = de.ID " + + " INNER JOIN DM_DEVICE_TYPE dt ON dt.ID = de.DEVICE_TYPE_ID " + + " WHERE " + + " opm.UPDATED_TIMESTAMP > ? " + + " AND de.TENANT_ID = ? " + + " ORDER BY opm.UPDATED_TIMESTAMP " + + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY) opr " + + " LEFT JOIN DM_DEVICE_OPERATION_RESPONSE ops ON opr.MAPPING_ID = ops.EN_OP_MAP_ID " + + " WHERE " + + " opr.UPDATED_TIMESTAMP > ? " + + " AND opr.TENANT_ID = ? "; + + stmt = conn.prepareStatement(sql); stmt.setLong(1, timestamp); - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); stmt.setInt(2, tenantId); stmt.setInt(3, offset); stmt.setInt(4, limit); + stmt.setLong(5, timestamp); + stmt.setInt(6, tenantId); rs = stmt.executeQuery(); @@ -340,71 +360,4 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { } return activities; } - - @Override - public int getActivityCountUpdatedAfter(long timestamp) throws OperationManagementDAOException { - PreparedStatement stmt = null; - ResultSet rs = null; - try { - Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT COUNT(*) COUNT FROM DM_ENROLMENT_OP_MAPPING m \n" - + "INNER JOIN DM_ENROLMENT d ON m.ENROLMENT_ID = d.ID \n" - + "WHERE m.UPDATED_TIMESTAMP > ? AND d.TENANT_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setLong(1, timestamp); - stmt.setInt(2, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); - rs = stmt.executeQuery(); - if (rs.next()) { - return rs.getInt("COUNT"); - } - } catch (SQLException e) { - throw new OperationManagementDAOException( - "Error occurred while getting the activity count from " + "the database.", e); - } finally { - OperationManagementDAOUtil.cleanupResources(stmt, rs); - } - return 0; - } - - - @Override - public Map> getOperationMappingsByStatus(Operation.Status opStatus, Operation.PushNotificationStatus pushNotificationStatus, - int limit) throws OperationManagementDAOException { - PreparedStatement stmt = null; - ResultSet rs = null; - OperationMapping operationMapping; - Map> operationMappingsTenantMap = new HashMap<>(); - try { - Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT op.ENROLMENT_ID, op.OPERATION_ID, dt.NAME ,d.TENANT_ID FROM DM_DEVICE d, " + - "DM_ENROLMENT_OP_MAPPING op, DM_DEVICE_TYPE dt WHERE op.STATUS = ? AND op" + - ".PUSH_NOTIFICATION_STATUS = ? AND d.DEVICE_TYPE_ID = dt.ID AND d.ID=op.ENROLMENT_ID AND ROWNUM" + - " <= ? ORDER BY op.OPERATION_ID"; - - stmt = conn.prepareStatement(sql); - stmt.setString(1, opStatus.toString()); - stmt.setString(2, pushNotificationStatus.toString()); - stmt.setInt(3, limit); - rs = stmt.executeQuery(); - while (rs.next()) { - int tenantID = rs.getInt("TENANT_ID"); - List operationMappings = operationMappingsTenantMap.get(tenantID); - if (operationMappings == null) { - operationMappings = new LinkedList<>(); - operationMappingsTenantMap.put(tenantID, operationMappings); - } - operationMapping = new OperationMapping(); - operationMapping.setOperationId(rs.getInt("OPERATION_ID")); - operationMapping.setDeviceIdentifier(new DeviceIdentifier(String.valueOf(rs.getInt("ENROLMENT_ID")), - rs.getString("NAME"))); - operationMapping.setTenantId(tenantID); - operationMappings.add(operationMapping); - } - } catch (SQLException e) { - throw new OperationManagementDAOException("SQL error while getting operation mappings from database. ", e); - } finally { - OperationManagementDAOUtil.cleanupResources(stmt, rs); - } - return operationMappingsTenantMap; - } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java index d19a5b151b..c71bac8448 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java @@ -145,7 +145,7 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { List activities = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT opm.ENROLMENT_ID, opm.CREATED_TIMESTAMP, opm.UPDATED_TIMESTAMP, opm.OPERATION_ID,\n" + /*String sql = "SELECT opm.ENROLMENT_ID, opm.CREATED_TIMESTAMP, opm.UPDATED_TIMESTAMP, opm.OPERATION_ID,\n" + "op.OPERATION_CODE, op.TYPE OPERATION_TYPE, opm.STATUS, en.DEVICE_ID,\n" + "ops.RECEIVED_TIMESTAMP, ops.ID OP_RES_ID, ops.OPERATION_RESPONSE,\n" + "de.DEVICE_IDENTIFICATION, dt.NAME DEVICE_TYPE\n" + "FROM DM_ENROLMENT_OP_MAPPING opm\n" @@ -161,13 +161,61 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { sql += "ORDER BY opm.OPERATION_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; } else { sql += "ORDER BY opm.UPDATED_TIMESTAMP asc OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - } + }*/ + + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + String sql = "SELECT " + + " opr.ENROLMENT_ID, " + + " opr.CREATED_TIMESTAMP, " + + " opr.UPDATED_TIMESTAMP, " + + " opr.OPERATION_ID, " + + " opr.OPERATION_CODE, " + + " opr.OPERATION_TYPE, " + + " opr.STATUS, " + + " opr.DEVICE_ID, " + + " opr.DEVICE_IDENTIFICATION, " + + " opr.DEVICE_TYPE, " + + " ops.RECEIVED_TIMESTAMP, " + + " ops.ID OP_RES_ID, " + + " ops.OPERATION_RESPONSE " + + " FROM " + + " (SELECT " + + " opm.ID MAPPING_ID, " + + " opm.ENROLMENT_ID, " + + " opm.CREATED_TIMESTAMP, " + + " opm.UPDATED_TIMESTAMP, " + + " opm.OPERATION_ID, " + + " op.OPERATION_CODE, " + + " op.TYPE OPERATION_TYPE, " + + " opm.STATUS, " + + " en.DEVICE_ID, " + + " de.DEVICE_IDENTIFICATION, " + + " dt.NAME DEVICE_TYPE, " + + " de.TENANT_ID " + + " FROM" + + " DM_ENROLMENT_OP_MAPPING opm " + + " INNER JOIN DM_OPERATION op ON opm.OPERATION_ID = op.ID " + + " INNER JOIN DM_ENROLMENT en ON opm.ENROLMENT_ID = en.ID " + + " INNER JOIN DM_DEVICE de ON en.DEVICE_ID = de.ID " + + " INNER JOIN DM_DEVICE_TYPE dt ON dt.ID = de.DEVICE_TYPE_ID " + + " WHERE " + + " opm.UPDATED_TIMESTAMP > ? " + + " AND de.TENANT_ID = ? " + + " ORDER BY opm.UPDATED_TIMESTAMP " + + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY) opr " + + " LEFT JOIN DM_DEVICE_OPERATION_RESPONSE ops ON opr.MAPPING_ID = ops.EN_OP_MAP_ID " + + " WHERE" + + " opr.UPDATED_TIMESTAMP > ? " + + " AND opr.TENANT_ID = ? "; + stmt = conn.prepareStatement(sql); stmt.setLong(1, timestamp); - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); stmt.setInt(2, tenantId); stmt.setInt(3, offset); stmt.setInt(4, limit); + stmt.setLong(5, timestamp); + stmt.setInt(6, tenantId); rs = stmt.executeQuery(); @@ -277,14 +325,15 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { Map> operationMappingsTenantMap = new HashMap<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT op.ENROLMENT_ID, op.OPERATION_ID, dt.NAME ,d.TENANT_ID FROM DM_DEVICE d, " + - "DM_ENROLMENT_OP_MAPPING op, DM_DEVICE_TYPE dt WHERE op.STATUS = ? AND op" + - ".PUSH_NOTIFICATION_STATUS = ? AND d.DEVICE_TYPE_ID = dt.ID " + + String sql = "SELECT op.ENROLMENT_ID, op.OPERATION_ID, d.DEVICE_IDENTIFICATION, dt.NAME as DEVICE_TYPE, d" + + ".TENANT_ID FROM DM_DEVICE d, DM_ENROLMENT_OP_MAPPING op, DM_DEVICE_TYPE dt WHERE op.STATUS = ? " + + "AND op.PUSH_NOTIFICATION_STATUS = ? AND d.DEVICE_TYPE_ID = dt.ID " + "AND d.ID=op.ENROLMENT_ID ORDER BY op.OPERATION_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setString(1, opStatus.toString()); stmt.setString(2, pushNotificationStatus.toString()); - stmt.setInt(3, limit); + stmt.setInt(3, 0); + stmt.setInt(4, limit); rs = stmt.executeQuery(); while (rs.next()) { int tenantID = rs.getInt("TENANT_ID"); @@ -295,8 +344,11 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { } operationMapping = new OperationMapping(); operationMapping.setOperationId(rs.getInt("OPERATION_ID")); - operationMapping.setDeviceIdentifier(new DeviceIdentifier(String.valueOf(rs.getInt("ENROLMENT_ID")), - rs.getString("NAME"))); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + deviceIdentifier.setType(rs.getString("DEVICE_TYPE")); + operationMapping.setDeviceIdentifier(deviceIdentifier); + operationMapping.setEnrollmentId(rs.getInt("ENROLMENT_ID")); operationMapping.setTenantId(tenantID); operationMappings.add(operationMapping); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/PushNotificationBasedOperationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/PushNotificationBasedOperationManager.java index 0d92577135..79ffacb370 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/PushNotificationBasedOperationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/PushNotificationBasedOperationManager.java @@ -116,6 +116,11 @@ public class PushNotificationBasedOperationManager implements OperationManager { return this.operationManager.getOperationByActivityId(activity); } + @Override + public Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) throws OperationManagementException { + return this.operationManager.getOperationByActivityIdAndDevice(activity, deviceId); + } + @Override public List getOperationUpdatedAfter(long timestamp) throws OperationManagementException { return this.operationManager.getOperationUpdatedAfter(timestamp); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/task/PushNotificationSchedulerTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/task/PushNotificationSchedulerTask.java index 3ac4126f30..133ba08cb0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/task/PushNotificationSchedulerTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/task/PushNotificationSchedulerTask.java @@ -77,7 +77,7 @@ public class PushNotificationSchedulerTask implements Runnable { try { if (log.isDebugEnabled()) { log.debug("Sending push notification for operationId :" + operationMapping.getOperationId() + - "to deviceId : " + operationMapping.getDeviceIdentifier().getId()); + " to deviceId : " + operationMapping.getDeviceIdentifier().getId()); } // Set tenant id and domain PrivilegedCarbonContext.startTenantFlow(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java index b2c779c037..cf7a1eb069 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java @@ -23,6 +23,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; @@ -62,7 +63,7 @@ public class ProcessorImpl implements Processor { @Override public List execute(SearchContext searchContext) throws SearchMgtException { - if(!Utils.validateOperators(searchContext.getConditions())){ + if (!Utils.validateOperators(searchContext.getConditions())) { throw new SearchMgtException("Invalid validator is provided."); } @@ -268,10 +269,10 @@ public class ProcessorImpl implements Processor { } else if (type.getColumnType().equals(ValueType.columnType.INTEGER)) { stmt.setInt(x, type.getIntValue()); x++; - } else if (type.getColumnType().equals(ValueType.columnType.LONG)){ + } else if (type.getColumnType().equals(ValueType.columnType.LONG)) { stmt.setLong(x, type.getLongValue()); x++; - } else if(type.getColumnType().equals(ValueType.columnType.DOUBLE)){ + } else if (type.getColumnType().equals(ValueType.columnType.DOUBLE)) { stmt.setDouble(x, type.getDoubleValue()); x++; } @@ -360,8 +361,10 @@ public class ProcessorImpl implements Processor { try { conn = this.getConnection(); String query = "SELECT * FROM DM_DEVICE_INFO WHERE DEVICE_ID IN ("; - if (conn.getMetaData().getDatabaseProductName().contains("H2") || conn.getMetaData() - .getDatabaseProductName().contains("MySQL")) { + if (conn.getMetaData().getDatabaseProductName().contains(DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2) || conn.getMetaData() + .getDatabaseProductName().contains(DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL) || + conn.getMetaData().getDatabaseProductName().contains(DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE) || + conn.getMetaData().getDatabaseProductName().contains(DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL)) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < devices.size(); i++) { builder.append("?,"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java index 936f8f68f1..d5d0b1700a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java @@ -119,7 +119,6 @@ public class QueryBuilderImpl implements QueryBuilder { log.debug("Property with OR Query : " + queries.get(Constants.PROP_OR)); log.debug("Location related Query : " + queries.get(Constants.LOCATION)); } - return queries; } @@ -342,10 +341,10 @@ public class QueryBuilderImpl implements QueryBuilder { "DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" + "DD.PLUGGED_IN, DD.UPDATE_TIMESTAMP, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + "DL.STATE, DL.COUNTRY, DL.UPDATE_TIMESTAMP AS DL_UPDATED_TIMESTAMP, DE.OWNER, DE.OWNERSHIP, DE.STATUS " + - "AS DE_STATUS FROM DM_DEVICE_DETAIL AS DD INNER JOIN DM_DEVICE AS D ON D.ID=DD.DEVICE_ID\n" + - "LEFT JOIN DM_DEVICE_LOCATION AS DL ON DL.DEVICE_ID=D.ID \n" + - "INNER JOIN DM_DEVICE_TYPE AS DT ON DT.ID=D.DEVICE_TYPE_ID\n" + - "INNER JOIN DM_ENROLMENT AS DE ON D.ID=DE.DEVICE_ID\n" + + "AS DE_STATUS FROM DM_DEVICE_DETAIL DD INNER JOIN DM_DEVICE D ON D.ID=DD.DEVICE_ID\n" + + "LEFT JOIN DM_DEVICE_LOCATION DL ON DL.DEVICE_ID=D.ID \n" + + "INNER JOIN DM_DEVICE_TYPE DT ON DT.ID=D.DEVICE_TYPE_ID\n" + + "INNER JOIN DM_ENROLMENT DE ON D.ID=DE.DEVICE_ID\n" + "WHERE D.TENANT_ID = ? "; ValueType type = new ValueType(); @@ -370,11 +369,11 @@ public class QueryBuilderImpl implements QueryBuilder { "DD.PLUGGED_IN, DD.UPDATE_TIMESTAMP, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + "DL.STATE, DL.COUNTRY, DL.UPDATE_TIMESTAMP AS DL_UPDATED_TIMESTAMP, DI.KEY_FIELD, DI.VALUE_FIELD, \n" + "DE.OWNER, DE.OWNERSHIP, DE.STATUS AS DE_STATUS " + - "FROM DM_DEVICE_DETAIL AS DD INNER JOIN DM_DEVICE AS D ON D.ID=DD.DEVICE_ID\n" + - "LEFT JOIN DM_DEVICE_LOCATION AS DL ON DL.DEVICE_ID=D.ID \n" + - "INNER JOIN DM_DEVICE_TYPE AS DT ON DT.ID=D.DEVICE_TYPE_ID\n" + - "INNER JOIN DM_ENROLMENT AS DE ON D.ID=DE.DEVICE_ID\n" + - "LEFT JOIN DM_DEVICE_INFO AS DI ON DI.DEVICE_ID=D.ID\n" + + "FROM DM_DEVICE_DETAIL DD INNER JOIN DM_DEVICE D ON D.ID=DD.DEVICE_ID\n" + + "LEFT JOIN DM_DEVICE_LOCATION DL ON DL.DEVICE_ID=D.ID \n" + + "INNER JOIN DM_DEVICE_TYPE DT ON DT.ID=D.DEVICE_TYPE_ID\n" + + "INNER JOIN DM_ENROLMENT DE ON D.ID=DE.DEVICE_ID\n" + + "LEFT JOIN DM_DEVICE_INFO DI ON DI.DEVICE_ID=D.ID\n" + "WHERE D.TENANT_ID = ? "; ValueType type = new ValueType(); 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 9117468541..e52d7f38c3 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 @@ -32,7 +32,10 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; +import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationExecutionFailedException; import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; +import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; import java.util.Date; import java.util.HashMap; @@ -54,6 +57,18 @@ public interface DeviceManagementProviderService { */ List getAllDevices(String deviceType) throws DeviceManagementException; + /** + * Method to retrieve all the devices of a given device type. + * + * @param deviceType Device-type of the required devices + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return List of devices of given device-type. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * devices. + */ + List getAllDevices(String deviceType, boolean requireDeviceInfo) throws DeviceManagementException; + /** * Method to retrieve all the devices registered in the system. * @@ -63,6 +78,38 @@ public interface DeviceManagementProviderService { */ List getAllDevices() throws DeviceManagementException; + /** + * Method to retrieve all the devices registered in the system. + * + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return List of registered devices. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * devices. + */ + List getAllDevices(boolean requireDeviceInfo) throws DeviceManagementException; + + /** + * Method to retrieve all the devices registered in the system. + * + * @param since - Date value where the resource was last modified + * @return List of registered devices. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * devices. + */ + List getDevices(Date since) throws DeviceManagementException; + + /** + * Method to retrieve all the devices registered in the system. + * + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return List of registered devices. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * devices. + */ + List getDevices(Date since, boolean requireDeviceInfo) throws DeviceManagementException; + /** * Method to retrieve all the devices with pagination support. * @@ -73,6 +120,18 @@ public interface DeviceManagementProviderService { */ PaginationResult getDevicesByType(PaginationRequest request) throws DeviceManagementException; + /** + * Method to retrieve all the devices with pagination support. + * + * @param request PaginationRequest object holding the data for pagination + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return PaginationResult - Result including the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * devices. + */ + PaginationResult getDevicesByType(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException; + /** * Method to retrieve all the devices with pagination support. * @@ -83,21 +142,91 @@ public interface DeviceManagementProviderService { */ PaginationResult getAllDevices(PaginationRequest request) throws DeviceManagementException; - void sendEnrolmentInvitation(String templateName, EmailMetaInfo metaInfo) throws DeviceManagementException; + /** + * Method to retrieve all the devices with pagination support. + * + * @param request PaginationRequest object holding the data for pagination + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return PaginationResult - Result including the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * devices. + */ + PaginationResult getAllDevices(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException; - void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException; + /** + * Returns the device of specified id. + * + * @param deviceId device Id + * @return Device returns null when device is not available. + * @throws DeviceManagementException + */ + Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException; - FeatureManager getFeatureManager(String deviceType) throws DeviceManagementException; + /** + * Returns the device of specified id. + * + * @param deviceId device Id + * @return Device returns null when device is not available. + * @throws DeviceManagementException + */ + Device getDeviceWithTypeProperties(DeviceIdentifier deviceId) throws DeviceManagementException; /** - * Proxy method to get the tenant configuration of a given platform. + * Returns the device of specified id. * - * @param deviceType Device platform - * @return Tenant configuration settings of the particular tenant and platform. - * @throws DeviceManagementException If some unusual behaviour is observed while fetching the - * configuration. + * @param deviceId device Id + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return Device returns null when device is not available. + * @throws DeviceManagementException */ - PlatformConfiguration getConfiguration(String deviceType) throws DeviceManagementException; + Device getDevice(DeviceIdentifier deviceId, boolean requireDeviceInfo) throws DeviceManagementException; + + /** + * Returns the device of specified id. + * + * @param deviceId device Id + * @param since - Date value where the resource was last modified + * @return Device returns null when device is not available. + * @throws DeviceManagementException + */ + Device getDevice(DeviceIdentifier deviceId, Date since) throws DeviceManagementException; + + /** + * Returns the device of specified id. + * + * @param deviceId device Id + * @param since - Date value where the resource was last modified + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return Device returns null when device is not available. + * @throws DeviceManagementException + */ + Device getDevice(DeviceIdentifier deviceId, Date since, boolean requireDeviceInfo) throws DeviceManagementException; + + /** + * Returns the device of specified id with the given status. + * + * @param deviceId device Id + * @param status - Status of the device + * + * @return Device returns null when device is not available. + * @throws DeviceManagementException + */ + Device getDevice(DeviceIdentifier deviceId, EnrolmentInfo.Status status) throws DeviceManagementException; + + /** + * Returns the device of specified id with the given status. + * + * @param deviceId device Id + * @param status - Status of the device + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return Device returns null when device is not available. + * @throws DeviceManagementException + */ + Device getDevice(DeviceIdentifier deviceId, EnrolmentInfo.Status status, boolean requireDeviceInfo) throws DeviceManagementException; /** * Method to get the list of devices owned by an user with paging information. @@ -109,6 +238,18 @@ public interface DeviceManagementProviderService { */ PaginationResult getDevicesOfUser(PaginationRequest request) throws DeviceManagementException; + /** + * Method to get the list of devices owned by an user with paging information. + * + * @param request PaginationRequest object holding the data for pagination + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return List of devices owned by a particular user along with the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * device list + */ + PaginationResult getDevicesOfUser(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException; + /** * Method to get the list of devices filtered by the ownership with paging information. * @@ -119,6 +260,18 @@ public interface DeviceManagementProviderService { */ PaginationResult getDevicesByOwnership(PaginationRequest request) throws DeviceManagementException; + /** + * Method to get the list of devices filtered by the ownership with paging information. + * + * @param request PaginationRequest object holding the data for pagination + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return List of devices owned by a particular user along with the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * device list + */ + PaginationResult getDevicesByOwnership(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException; + /** * Method to get the list of devices owned by an user. * @@ -129,16 +282,42 @@ public interface DeviceManagementProviderService { */ List getDevicesOfUser(String userName) throws DeviceManagementException; + /** + * Method to get the list of devices owned by an user. + * + * @param userName Username of the user + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return List of devices owned by a particular user + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * device list + */ + List getDevicesOfUser(String userName, boolean requireDeviceInfo) throws DeviceManagementException; + /** * This method returns the list of device owned by a user of given device type. * * @param userName user name. * @param deviceType device type name - * @return - * @throws DeviceManagementException + * @return List of device owned by the given user and type. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * device list */ List getDevicesOfUser(String userName, String deviceType) throws DeviceManagementException; + /** + * This method returns the list of device owned by a user of given device type. + * + * @param userName user name. + * @param deviceType device type name + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return List of device owned by the given user and type. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * device list + */ + List getDevicesOfUser(String userName, String deviceType, boolean requireDeviceInfo) throws DeviceManagementException; + /** * Method to get the list of devices owned by users of a particular user-role. * @@ -150,32 +329,50 @@ public interface DeviceManagementProviderService { List getAllDevicesOfRole(String roleName) throws DeviceManagementException; /** - * Method to get the device count of user. + * Method to get the list of devices owned by users of a particular user-role. * - * @return device count - * @throws DeviceManagementException If some unusual behaviour is observed while counting - * the devices + * @param roleName Role name of the users + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return List of devices owned by users of a particular role + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * device list */ - int getDeviceCount(String username) throws DeviceManagementException; + List getAllDevicesOfRole(String roleName, boolean requireDeviceInfo) throws DeviceManagementException; /** - * Method to get the count of all types of devices. + * This method is used to retrieve list of devices based on the device status with paging information. * - * @return device count - * @throws DeviceManagementException If some unusual behaviour is observed while counting - * the devices + * @param request PaginationRequest object holding the data for pagination and filter info + * @return List of devices in given status along with the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * device list */ - int getDeviceCount() throws DeviceManagementException; + PaginationResult getDevicesByStatus(PaginationRequest request) throws DeviceManagementException; + + /** + * This method is used to retrieve list of devices based on the device status with paging information. + * + * @param request PaginationRequest object holding the data for pagination and filter info + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return List of devices in given status along with the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * device list + */ + PaginationResult getDevicesByStatus(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException; /** * Method to get the list of devices that matches with the given device name. * - * @param deviceName name of the device + * @param request PaginationRequest object holding the data for pagination and filter info + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. * @return List of devices that matches with the given device name. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the * device list */ - List getDevicesByNameAndType(String deviceName, String type, int offset, int limit) throws DeviceManagementException; + List getDevicesByNameAndType(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException; /** * This method is used to retrieve list of devices that matches with the given device name with paging information. @@ -187,7 +384,17 @@ public interface DeviceManagementProviderService { */ PaginationResult getDevicesByName(PaginationRequest request) throws DeviceManagementException; - void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status active) throws DeviceManagementException; + /** + * This method is used to retrieve list of devices that matches with the given device name with paging information. + * + * @param request PaginationRequest object holding the data for pagination + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return List of devices in given status along with the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * device list + */ + PaginationResult getDevicesByName(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException; /** * This method is used to retrieve list of devices based on the device status. @@ -199,14 +406,53 @@ public interface DeviceManagementProviderService { List getDevicesByStatus(EnrolmentInfo.Status status) throws DeviceManagementException; /** - * This method is used to retrieve list of devices based on the device status with paging information. + * This method is used to retrieve list of devices based on the device status. * - * @param request PaginationRequest object holding the data for pagination - * @return List of devices in given status along with the required parameters necessary to do pagination. + * @param status Device status + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return List of devices + * @throws DeviceManagementException + */ + List getDevicesByStatus(EnrolmentInfo.Status status, boolean requireDeviceInfo) throws DeviceManagementException; + + /** + * Method to get the device count of user. + * + * @return device count + * @throws DeviceManagementException If some unusual behaviour is observed while counting + * the devices + */ + int getDeviceCount(String username) throws DeviceManagementException; + + /** + * Method to get the count of all types of devices. + * + * @return device count + * @throws DeviceManagementException If some unusual behaviour is observed while counting + * the devices + */ + int getDeviceCount() throws DeviceManagementException; + + HashMap getTenantedDevice(DeviceIdentifier deviceIdentifier) throws DeviceManagementException; + + void sendEnrolmentInvitation(String templateName, EmailMetaInfo metaInfo) throws DeviceManagementException; + + void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException; + + FeatureManager getFeatureManager(String deviceType) throws DeviceManagementException; + + /** + * Proxy method to get the tenant configuration of a given platform. + * + * @param deviceType Device platform + * @return Tenant configuration settings of the particular tenant and platform. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the - * device list + * configuration. */ - PaginationResult getDevicesByStatus(PaginationRequest request) throws DeviceManagementException; + PlatformConfiguration getConfiguration(String deviceType) throws DeviceManagementException; + + void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status active) throws DeviceManagementException; /** * This method is used to check whether the device is enrolled with the give user. @@ -247,21 +493,6 @@ public interface DeviceManagementProviderService { boolean setActive(DeviceIdentifier deviceId, boolean status) throws DeviceManagementException; - /** - * Returns the device of specified id. - * - * @param deviceId device Id - * @return Device returns null when device is not avaialble. - * @throws DeviceManagementException - */ - Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException; - - Device getDevice(DeviceIdentifier deviceId, Date since) throws DeviceManagementException; - - HashMap getTenantedDevice(DeviceIdentifier deviceIdentifier) throws DeviceManagementException; - - Device getDevice(DeviceIdentifier deviceId, EnrolmentInfo.Status status) throws DeviceManagementException; - List getAvailableDeviceTypes() throws DeviceManagementException; boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException; @@ -273,6 +504,8 @@ public interface DeviceManagementProviderService { boolean setStatus(DeviceIdentifier deviceId, String currentOwner, EnrolmentInfo.Status status) throws DeviceManagementException; + boolean setStatus(String currentOwner, EnrolmentInfo.Status status) throws DeviceManagementException; + void notifyOperationToDevices(Operation operation, List deviceIds) throws DeviceManagementException; @@ -304,6 +537,8 @@ public interface DeviceManagementProviderService { Activity getOperationByActivityId(String activity) throws OperationManagementException; + Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) throws OperationManagementException; + List getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException; List getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementException; @@ -328,4 +563,32 @@ public interface DeviceManagementProviderService { */ boolean changeDeviceStatus(DeviceIdentifier deviceIdentifier, EnrolmentInfo.Status newStatus) throws DeviceManagementException; + + /** + * This will handle add and update of device type services. + * @param deviceManagementService + */ + void registerDeviceType(DeviceManagementService deviceManagementService) throws DeviceManagementException; + + /** + * This retrieves the device type info for the given type + * @param deviceType name of the type. + * @throws DeviceManagementException + */ + DeviceType getDeviceType(String deviceType) throws DeviceManagementException; + + /** + * This retrieves the device type info for the given type + * @throws DeviceManagementException + */ + List getDeviceTypes() throws DeviceManagementException; + + /** + * This retrieves the device pull notification payload and passes to device type pull notification subscriber. + * @throws PullNotificationExecutionFailedException + */ + void notifyPullNotificationSubscriber(DeviceIdentifier deviceIdentifier, Operation operation) + throws PullNotificationExecutionFailedException; + + List getDeviceEnrolledTenants() 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 6672311c3d..1e09960283 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 @@ -28,7 +28,9 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManager; import org.wso2.carbon.device.mgt.common.DeviceNotFoundException; -import org.wso2.carbon.device.mgt.common.DeviceTypeIdentifier; +import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationExecutionFailedException; +import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber; +import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.FeatureManager; import org.wso2.carbon.device.mgt.common.InitialOperationConfig; @@ -57,6 +59,7 @@ import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository; +import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl; import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; @@ -176,7 +179,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } int tenantId = this.getTenantId(); - Device existingDevice = this.getDevice(deviceIdentifier); + Device existingDevice = this.getDevice(deviceIdentifier, false); if (existingDevice != null) { EnrolmentInfo existingEnrolmentInfo = existingDevice.getEnrolmentInfo(); @@ -210,6 +213,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv enrolmentId = enrollmentDAO. addEnrollment(existingDevice.getId(), newEnrolmentInfo, tenantId); DeviceManagementDAOFactory.commitTransaction(); + this.removeDeviceFromCache(deviceIdentifier); if (log.isDebugEnabled()) { log.debug("An enrolment is successfully added with the id '" + enrolmentId + "' associated with " + "the device identified by key '" + @@ -282,8 +286,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv boolean status = deviceManager.modifyEnrollment(device); try { int tenantId = this.getTenantId(); + Device currentDevice = this.getDevice(deviceIdentifier, false); DeviceManagementDAOFactory.beginTransaction(); - Device currentDevice = deviceDAO.getDevice(deviceIdentifier, tenantId); device.setId(currentDevice.getId()); if (device.getEnrolmentInfo().getId() == 0) { device.getEnrolmentInfo().setId(currentDevice.getEnrolmentInfo().getId()); @@ -294,6 +298,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv deviceDAO.updateDevice(device, tenantId); enrollmentDAO.updateEnrollment(device.getEnrolmentInfo()); DeviceManagementDAOFactory.commitTransaction(); + this.removeDeviceFromCache(deviceIdentifier); } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceManagementException("Error occurred while modifying the device " + @@ -333,32 +338,33 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } return false; } - try { - int tenantId = this.getTenantId(); - DeviceManagementDAOFactory.beginTransaction(); - Device device = deviceDAO.getDevice(deviceId, tenantId); - if (device == null) { - if (log.isDebugEnabled()) { - log.debug("Device not found for id '" + deviceId.getId() + "'"); - } - return false; + int tenantId = this.getTenantId(); + + Device device = this.getDevice(deviceId, false); + if (device == null) { + if (log.isDebugEnabled()) { + log.debug("Device not found for id '" + deviceId.getId() + "'"); } + return false; + } - if (device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.REMOVED)) { - if (log.isDebugEnabled()) { - log.debug("Device has already disenrolled : " + deviceId.getId() + "'"); - } - return false; + if (device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.REMOVED)) { + if (log.isDebugEnabled()) { + log.debug("Device has already disenrolled : " + deviceId.getId() + "'"); } - DeviceType deviceType = deviceTypeDAO.getDeviceType(device.getType(), tenantId); + return true; + } + try { device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); device.getEnrolmentInfo().setStatus(EnrolmentInfo.Status.REMOVED); + DeviceManagementDAOFactory.beginTransaction(); enrollmentDAO.updateEnrollment(device.getId(), device.getEnrolmentInfo(), tenantId); deviceDAO.updateDevice(device, tenantId); DeviceManagementDAOFactory.commitTransaction(); + this.removeDeviceFromCache(deviceId); } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceManagementException("Error occurred while dis-enrolling '" + deviceId.getType() + @@ -373,19 +379,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException { - try { - DeviceManagementDAOFactory.openConnection(); - Device device = deviceDAO.getDevice(deviceId, this.getTenantId()); - if (device != null) { - return true; - } - } catch (DeviceManagementDAOException e) { - throw new DeviceManagementException("Error occurred while obtaining the enrollment information device for" + - "id '" + deviceId.getId() + "'", e); - } catch (SQLException e) { - throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); + Device device = this.getDevice(deviceId, false); + if (device != null) { + return true; } return false; } @@ -416,9 +412,45 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return deviceManager.setActive(deviceId, status); } + @Override + public List getAllDevices(String deviceType) throws DeviceManagementException { + return this.getAllDevices(deviceType, true); + } + + @Override + public List getAllDevices(String deviceType, boolean requireDeviceInfo) throws DeviceManagementException { + List allDevices; + try { + DeviceManagementDAOFactory.openConnection(); + allDevices = deviceDAO.getDevices(deviceType, this.getTenantId()); + if (allDevices == null) { + if (log.isDebugEnabled()) { + log.debug("No device is found upon the type '" + deviceType + "'"); + } + return null; + } + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while retrieving all devices of type '" + + deviceType + "' that are being managed within the scope of current tenant", e); + } catch (SQLException e) { + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + if (requireDeviceInfo) { + return this.getAllDeviceInfo(allDevices); + } + return allDevices; + } + @Override public List getAllDevices() throws DeviceManagementException { - List devices = new ArrayList<>(); + return this.getAllDevices(true); + } + + @Override + public List getAllDevices(boolean requireDeviceInfo) throws DeviceManagementException { List allDevices; try { DeviceManagementDAOFactory.openConnection(); @@ -432,60 +464,19 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } - for (Device device : allDevices) { - DeviceInfo info = null; - try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'", e); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - device.setDeviceInfo(info); - - try { - DeviceManagementDAOFactory.openConnection(); - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); - } catch (DeviceManagementDAOException e) { - log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + - "which carries the id '" + device.getId() + "'", e); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - DeviceManager deviceManager = this.getDeviceManager(device.getType()); - if (deviceManager == null) { - if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + - "Therefore, not attempting method 'isEnrolled'"); - } - devices.add(device); - continue; - } - Device dmsDevice = - deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); - } - devices.add(device); + if (requireDeviceInfo) { + return this.getAllDeviceInfo(allDevices); } - return devices; + return allDevices; } + @Override public List getDevices(Date since) throws DeviceManagementException { - List devices = new ArrayList<>(); + return this.getDevices(since, true); + } + + @Override + public List getDevices(Date since, boolean requireDeviceInfo) throws DeviceManagementException { List allDevices; try { DeviceManagementDAOFactory.openConnection(); @@ -499,62 +490,20 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } - for (Device device : allDevices) { - DeviceInfo info = null; - try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'"); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - device.setDeviceInfo(info); - - try { - DeviceManagementDAOFactory.openConnection(); - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); - } catch (DeviceManagementDAOException e) { - log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + - "which carries the id '" + device.getId() + "'", e); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - DeviceManager deviceManager = this.getDeviceManager(device.getType()); - if (deviceManager == null) { - if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + - "Therefore, not attempting method 'isEnrolled'"); - } - devices.add(device); - continue; - } - Device dmsDevice = - deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); - } - devices.add(device); + if (requireDeviceInfo) { + return this.getAllDeviceInfo(allDevices); } - return devices; + return allDevices; } @Override public PaginationResult getDevicesByType(PaginationRequest request) throws DeviceManagementException { + return this.getDevicesByType(request, true); + } + + @Override + public PaginationResult getDevicesByType(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException { PaginationResult paginationResult = new PaginationResult(); - List devices = new ArrayList<>(); List allDevices = new ArrayList<>(); int count = 0; int tenantId = this.getTenantId(); @@ -572,43 +521,13 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } finally { DeviceManagementDAOFactory.closeConnection(); } - for (Device device : allDevices) { - DeviceInfo info = null; - try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - device.setDeviceInfo(info); - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'"); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - device.setDeviceInfo(info); - DeviceManager deviceManager = this.getDeviceManager(device.getType()); - if (deviceManager == null) { - if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + - "Therefore, not attempting method 'isEnrolled'"); - } - devices.add(device); - continue; - } - Device dmsDevice = - deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); - } - devices.add(device); + + if (requireDeviceInfo) { + paginationResult.setData(this.getAllDeviceInfo(allDevices)); + } else { + paginationResult.setData(allDevices); } - paginationResult.setData(devices); + paginationResult.setRecordsFiltered(count); paginationResult.setRecordsTotal(count); return paginationResult; @@ -616,168 +535,79 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public PaginationResult getAllDevices(PaginationRequest request) throws DeviceManagementException { + return this.getAllDevices(request, true); + } + + @Override + public PaginationResult getAllDevices(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException { List devicesForRoles = null; PaginationResult paginationResult = new PaginationResult(); - List devices = new ArrayList<>(); List allDevices = new ArrayList<>(); int count = 0; int tenantId = this.getTenantId(); request = DeviceManagerUtil.validateDeviceListPageSize(request); if (!StringUtils.isEmpty(request.getOwnerRole())) { - devicesForRoles = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider() - .getAllDevicesOfRole(request.getOwnerRole()); - } - try { - DeviceManagementDAOFactory.openConnection(); - allDevices = deviceDAO.getDevices(request, tenantId); - count = deviceDAO.getDeviceCount(request, tenantId); - } catch (DeviceManagementDAOException e) { - throw new DeviceManagementException("Error occurred while retrieving device list pertaining to " + - "the current tenant", e); - } catch (SQLException e) { - throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - devices = processDevices(devices, allDevices); - - if (devicesForRoles != null) { - count += devicesForRoles.size(); - devices = processDevices(devices, devicesForRoles); - } - paginationResult.setData(devices); - paginationResult.setRecordsFiltered(count); - paginationResult.setRecordsTotal(count); - return paginationResult; - } - - private List processDevices(List devices, List allDevices) throws DeviceManagementException { - for (Device device : allDevices) { - DeviceInfo info = null; - try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); + devicesForRoles = this.getAllDevicesOfRole(request.getOwnerRole(), false); + if (devicesForRoles != null) { + count = devicesForRoles.size(); + if (requireDeviceInfo) { + paginationResult.setData(getAllDeviceInfo(devicesForRoles)); } - device.setDeviceInfo(info); - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'"); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); } - device.setDeviceInfo(info); - + } else { try { DeviceManagementDAOFactory.openConnection(); - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); + allDevices = deviceDAO.getDevices(request, tenantId); + count = deviceDAO.getDeviceCount(request, tenantId); } catch (DeviceManagementDAOException e) { - log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + - "which carries the id '" + device.getId() + "'", e); + throw new DeviceManagementException("Error occurred while retrieving device list pertaining to " + + "the current tenant", e); } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); } finally { DeviceManagementDAOFactory.closeConnection(); } - - DeviceManager deviceManager = this.getDeviceManager(device.getType()); - if (deviceManager == null) { - if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + - "Therefore, not attempting method 'isEnrolled'"); - } - devices.add(device); - continue; - } - Device dmsDevice = - deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); + if (requireDeviceInfo) { + paginationResult.setData(getAllDeviceInfo(allDevices)); + } else { + paginationResult.setData(allDevices); } - devices.add(device); } - return devices; + paginationResult.setRecordsFiltered(count); + paginationResult.setRecordsTotal(count); + return paginationResult; } @Override - public List getAllDevices(String deviceType) throws DeviceManagementException { - List devices = new ArrayList<>(); - List allDevices; - try { - DeviceManagementDAOFactory.openConnection(); - allDevices = deviceDAO.getDevices(deviceType, this.getTenantId()); - if (allDevices == null) { - if (log.isDebugEnabled()) { - log.debug("No device is found upon the type '" + deviceType + "'"); - } - return null; - } - } catch (DeviceManagementDAOException e) { - throw new DeviceManagementException("Error occurred while retrieving all devices of type '" + - deviceType + "' that are being managed within the scope of current tenant", e); - } catch (SQLException e) { - throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - for (Device device : allDevices) { - DeviceInfo info = null; + public Device getDevice(DeviceIdentifier deviceId, boolean requireDeviceInfo) throws DeviceManagementException { + int tenantId = this.getTenantId(); + Device device = this.getDeviceFromCache(deviceId); + if (device == null) { try { DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); + device = deviceDAO.getDevice(deviceId, tenantId); + if (device == null) { + String msg = "No device is found upon the type '" + deviceId.getType() + "' and id '" + + deviceId.getId() + "'"; + if (log.isDebugEnabled()) { + log.debug(msg); + } + return null; } - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'"); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - device.setDeviceInfo(info); - - try { - DeviceManagementDAOFactory.openConnection(); - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); + this.addDeviceToCache(deviceId, device); } catch (DeviceManagementDAOException e) { - log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + - "which carries the id '" + device.getId() + "'", e); + throw new DeviceManagementException("Error occurred while obtaining the device for id " + + "'" + deviceId.getId() + "'", e); } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); } finally { DeviceManagementDAOFactory.closeConnection(); } - - DeviceManager deviceManager = this.getDeviceManager(deviceType); - if (deviceManager == null) { - if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + deviceType + "' is null. " + - "Therefore, not attempting method 'isEnrolled'"); - } - devices.add(device); - continue; - } - Device dmsDevice = - deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); - } - devices.add(device); } - return devices; + if (requireDeviceInfo) { + device = this.getAllDeviceInfo(device); + } + return device; } @Override @@ -857,57 +687,37 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException { - Device device; - try { - DeviceManagementDAOFactory.openConnection(); - device = deviceDAO.getDevice(deviceId, this.getTenantId()); - if (device == null) { - String msg = "No device is found upon the type '" + deviceId.getType() + "' and id '" + - deviceId.getId() + "'"; - if (log.isDebugEnabled()) { - log.debug(msg); - } - return null; - } - DeviceInfo info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - device.setDeviceInfo(info); + return this.getDevice(deviceId, true); + } - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); - } catch (DeviceManagementDAOException e) { - throw new DeviceManagementException("Error occurred while obtaining the device for id " + - "'" + deviceId.getId() + "'", e); - } catch (SQLException e) { - throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); - } catch (DeviceDetailsMgtDAOException e) { - throw new DeviceManagementException("Error occurred while fetching advanced device information", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - // The changes made here to prevent unit tests getting failed. They failed because when running the unit - // tests there is no osgi services. So getDeviceManager() returns a null. - DeviceManager deviceManager = this.getDeviceManager(deviceId.getType()); + @Override + public Device getDeviceWithTypeProperties(DeviceIdentifier deviceId) throws DeviceManagementException { + Device device = this.getDevice(deviceId, false); + + DeviceManager deviceManager = this.getDeviceManager(device.getType()); if (deviceManager == null) { if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + deviceId.getType() + "' is null. " + - "Therefore, not attempting method 'getDevice'"); + log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + + "Therefore, not attempting method 'isEnrolled'"); } return device; } - Device pluginSpecificInfo = deviceManager.getDevice(deviceId); - if (pluginSpecificInfo != null) { - device.setFeatures(pluginSpecificInfo.getFeatures()); - device.setProperties(pluginSpecificInfo.getProperties()); + Device dmsDevice = + deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + if (dmsDevice != null) { + device.setFeatures(dmsDevice.getFeatures()); + device.setProperties(dmsDevice.getProperties()); } return device; } @Override public Device getDevice(DeviceIdentifier deviceId, Date since) throws DeviceManagementException { + return this.getDevice(deviceId, since, true); + } + + @Override + public Device getDevice(DeviceIdentifier deviceId, Date since, boolean requireDeviceInfo) throws DeviceManagementException { Device device; try { DeviceManagementDAOFactory.openConnection(); @@ -919,43 +729,28 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } return null; } - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (device.getDeviceInfo() != null) { - device.getDeviceInfo().setLocation(location); - } - - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); } catch (DeviceManagementDAOException e) { throw new DeviceManagementException("Error occurred while obtaining the device for id " + "'" + deviceId.getId() + "'", e); } catch (SQLException e) { throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); - } catch (DeviceDetailsMgtDAOException e) { - throw new DeviceManagementException("Error occurred while fetching advanced device information", e); } finally { DeviceManagementDAOFactory.closeConnection(); } - // The changes made here to prevent unit tests getting failed. They failed because when running the unit - // tests there is no osgi services. So getDeviceManager() returns a null. - DeviceManager deviceManager = this.getDeviceManager(deviceId.getType()); - if (deviceManager == null) { - if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + deviceId.getType() + "' is null. " + - "Therefore, not attempting method 'getDevice'"); - } - return device; - } - Device pluginSpecificInfo = deviceManager.getDevice(deviceId); - if (pluginSpecificInfo != null) { - device.setFeatures(pluginSpecificInfo.getFeatures()); - device.setProperties(pluginSpecificInfo.getProperties()); + if (requireDeviceInfo) { + device = this.getAllDeviceInfo(device); } return device; } @Override public Device getDevice(DeviceIdentifier deviceId, EnrolmentInfo.Status status) throws DeviceManagementException { + return this.getDevice(deviceId, status, true); + } + + @Override + public Device getDevice(DeviceIdentifier deviceId, EnrolmentInfo.Status status, boolean requireDeviceInfo) + throws DeviceManagementException { Device device; try { DeviceManagementDAOFactory.openConnection(); @@ -967,47 +762,24 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } return null; } - DeviceInfo info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - device.setDeviceInfo(info); - - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); } catch (DeviceManagementDAOException e) { throw new DeviceManagementException("Error occurred while obtaining the device for id " + "'" + deviceId.getId() + "'", e); } catch (SQLException e) { throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); - } catch (DeviceDetailsMgtDAOException e) { - throw new DeviceManagementException("Error occurred while obtaining information of the device with id " + - "'" + deviceId.getId() + "'", e); } finally { DeviceManagementDAOFactory.closeConnection(); } - // The changes made here to prevent unit tests getting failed. They failed because when running the unit - // tests there is no osgi services. So getDeviceManager() returns a null. - DeviceManager deviceManager = this.getDeviceManager(deviceId.getType()); - if (deviceManager == null) { - if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + deviceId.getType() + "' is null. " + - "Therefore, not attempting method 'getDevice'"); - } - return device; - } - Device pluginSpecificInfo = deviceManager.getDevice(deviceId); - if (pluginSpecificInfo != null) { - device.setFeatures(pluginSpecificInfo.getFeatures()); - device.setProperties(pluginSpecificInfo.getProperties()); + if (requireDeviceInfo) { + device = this.getAllDeviceInfo(device); } + return device; } @Override public List getAvailableDeviceTypes() throws DeviceManagementException { - List deviceTypesProvidedByTenant; + List deviceTypesProvidedByTenant; List publicSharedDeviceTypesInDB; List deviceTypesResponse = new ArrayList<>(); try { @@ -1015,17 +787,17 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv int tenantId = this.getTenantId(); deviceTypesProvidedByTenant = deviceTypeDAO.getDeviceTypesByProvider(tenantId); publicSharedDeviceTypesInDB = deviceTypeDAO.getSharedDeviceTypes(); - Map registeredTypes = + Map registeredTypes = pluginRepository.getAllDeviceManagementServices(tenantId); Set deviceTypeSetForTenant = new HashSet<>(); if (registeredTypes != null) { if (deviceTypesProvidedByTenant != null) { - for (String deviceType : deviceTypesProvidedByTenant) { - DeviceTypeIdentifier providerKey = new DeviceTypeIdentifier(deviceType, tenantId); - if (registeredTypes.get(providerKey) != null) { - deviceTypesResponse.add(deviceType); - deviceTypeSetForTenant.add(deviceType); + for (DeviceType deviceType : deviceTypesProvidedByTenant) { + DeviceTypeServiceIdentifier providerKey = new DeviceTypeServiceIdentifier(deviceType.getName(), tenantId); + if (registeredTypes.get(providerKey) != null || deviceType.getDeviceTypeMetaDefinition() != null) { + deviceTypesResponse.add(deviceType.getName()); + deviceTypeSetForTenant.add(deviceType.getName()); } } } @@ -1033,7 +805,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv // priority to that if (publicSharedDeviceTypesInDB != null) { for (String deviceType : publicSharedDeviceTypesInDB) { - DeviceTypeIdentifier providerKey = new DeviceTypeIdentifier(deviceType); + DeviceTypeServiceIdentifier providerKey = new DeviceTypeServiceIdentifier(deviceType); if (registeredTypes.get(providerKey) != null && !deviceTypeSetForTenant.contains(deviceType)) { deviceTypesResponse.add(deviceType); } @@ -1095,14 +867,15 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv EnrolmentInfo.Status status) throws DeviceManagementException { try { boolean success = false; - DeviceManagementDAOFactory.beginTransaction(); int tenantId = this.getTenantId(); - Device device = deviceDAO.getDevice(deviceId, tenantId); + Device device = this.getDevice(deviceId, false); EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); + DeviceManagementDAOFactory.beginTransaction(); if (enrolmentInfo != null) { success = enrollmentDAO.setStatus(enrolmentInfo.getId(), currentOwner, status, tenantId); } DeviceManagementDAOFactory.commitTransaction(); + this.removeDeviceFromCache(deviceId); return success; } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); @@ -1111,20 +884,40 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv throw new DeviceManagementException("Error occurred while initiating transaction", e); } finally { DeviceManagementDAOFactory.closeConnection(); + } + } + @Override + public boolean setStatus(String currentOwner, + EnrolmentInfo.Status status) throws DeviceManagementException { + try { + boolean success = false; + int tenantId = this.getTenantId(); + DeviceManagementDAOFactory.beginTransaction(); + success = enrollmentDAO.setStatus(currentOwner, status, tenantId); + DeviceManagementDAOFactory.commitTransaction(); + return success; + } catch (DeviceManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + throw new DeviceManagementException("Error occurred while setting enrollment status", e); + } catch (TransactionManagementException e) { + throw new DeviceManagementException("Error occurred while initiating transaction", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); } } @Override + @Deprecated public void notifyOperationToDevices(Operation operation, List deviceIds) throws DeviceManagementException { - for (DeviceIdentifier deviceId : deviceIds) { - DeviceManagementService dms = - pluginRepository.getDeviceManagementService(deviceId.getType(), this.getTenantId()); - //TODO FIX THIS WITH PUSH NOTIFICATIONS - //dms.notifyOperationToDevices(operation, deviceIds); - } +// for (DeviceIdentifier deviceId : deviceIds) { +// DeviceManagementService dms = +// pluginRepository.getDeviceManagementService(deviceId.getType(), this.getTenantId()); +// //TODO FIX THIS WITH PUSH NOTIFICATIONS +// //dms.notifyOperationToDevices(operation, deviceIds); +// } } @@ -1239,6 +1032,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return DeviceManagementDataHolder.getInstance().getOperationManager().getOperationByActivityId(activity); } + public Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) throws OperationManagementException { + return DeviceManagementDataHolder.getInstance().getOperationManager().getOperationByActivityIdAndDevice(activity, deviceId); + } + @Override public List getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException { return DeviceManagementDataHolder.getInstance().getOperationManager().getActivitiesUpdatedAfter(timestamp); @@ -1290,7 +1087,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public List getDevicesOfUser(String username) throws DeviceManagementException { - List devices = new ArrayList<>(); + return this.getDevicesOfUser(username, true); + } + + @Override + public List getDevicesOfUser(String username, boolean requireDeviceInfo) throws DeviceManagementException { List userDevices; try { DeviceManagementDAOFactory.openConnection(); @@ -1304,61 +1105,20 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } - for (Device device : userDevices) { - DeviceInfo info = null; - try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'"); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - device.setDeviceInfo(info); - - try { - DeviceManagementDAOFactory.openConnection(); - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); - } catch (DeviceManagementDAOException e) { - log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + - "which carries the id '" + device.getId() + "'", e); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - DeviceManager deviceManager = this.getDeviceManager(device.getType()); - if (deviceManager == null) { - if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + - "Therefore, not attempting method 'isEnrolled'"); - } - devices.add(device); - continue; - } - Device dmsDevice = - deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); - } - devices.add(device); + if (requireDeviceInfo) { + return this.getAllDeviceInfo(userDevices); } - return devices; + return userDevices; } @Override public List getDevicesOfUser(String username, String deviceType) throws DeviceManagementException { - List devices = new ArrayList<>(); + return this.getDevicesOfUser(username, deviceType, true); + } + + @Override + public List getDevicesOfUser(String username, String deviceType, boolean requireDeviceInfo) throws + DeviceManagementException { List userDevices; try { DeviceManagementDAOFactory.openConnection(); @@ -1372,66 +1132,24 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } - for (Device device : userDevices) { - DeviceInfo info = null; - try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'"); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - device.setDeviceInfo(info); - - try { - DeviceManagementDAOFactory.openConnection(); - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); - } catch (DeviceManagementDAOException e) { - log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + - "which carries the id '" + device.getId() + "'", e); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - DeviceManager deviceManager = this.getDeviceManager(device.getType()); - if (deviceManager == null) { - if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + - "Therefore, not attempting method 'isEnrolled'"); - } - devices.add(device); - continue; - } - Device dmsDevice = - deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); - } - devices.add(device); + if (requireDeviceInfo) { + return this.getAllDeviceInfo(userDevices); } - return devices; + return userDevices; } @Override - public PaginationResult getDevicesOfUser(PaginationRequest request) + public PaginationResult getDevicesOfUser(PaginationRequest request) throws DeviceManagementException { + return this.getDevicesOfUser(request, true); + } + + @Override + public PaginationResult getDevicesOfUser(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException { PaginationResult result = new PaginationResult(); int deviceCount = 0; int tenantId = this.getTenantId(); String username = request.getOwner(); - List devices = new ArrayList<>(); List userDevices = new ArrayList<>(); request = DeviceManagerUtil.validateDeviceListPageSize(request); try { @@ -1446,57 +1164,13 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } finally { DeviceManagementDAOFactory.closeConnection(); } - - for (Device device : userDevices) { - DeviceInfo info = null; - try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'"); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - device.setDeviceInfo(info); - - try { - DeviceManagementDAOFactory.openConnection(); - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); - } catch (DeviceManagementDAOException e) { - log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + - "which carries the id '" + device.getId() + "'", e); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - DeviceManager deviceManager = this.getDeviceManager(device.getType()); - if (deviceManager == null) { - if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + - "Therefore, not attempting method 'isEnrolled'"); - } - devices.add(device); - continue; - } - Device dmsDevice = - deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); - } - devices.add(device); - } - result.setData(devices); + + if (requireDeviceInfo) { + result.setData(this.getAllDeviceInfo(userDevices)); + } else { + result.setData(userDevices); + } + result.setRecordsTotal(deviceCount); result.setRecordsFiltered(deviceCount); return result; @@ -1505,8 +1179,13 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public PaginationResult getDevicesByOwnership(PaginationRequest request) throws DeviceManagementException { + return this.getDevicesByOwnership(request, true); + } + + @Override + public PaginationResult getDevicesByOwnership(PaginationRequest request, boolean requireDeviceInfo) + throws DeviceManagementException { PaginationResult result = new PaginationResult(); - List devices = new ArrayList<>(); List allDevices; int deviceCount = 0; int tenantId = this.getTenantId(); @@ -1524,47 +1203,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } finally { DeviceManagementDAOFactory.closeConnection(); } - for (Device device : allDevices) { - DeviceInfo info = null; - try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'"); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - device.setDeviceInfo(info); - - try { - DeviceManagementDAOFactory.openConnection(); - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); - } catch (DeviceManagementDAOException e) { - log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + - "which carries the id '" + device.getId() + "'", e); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - Device dmsDevice = this.getDeviceManager(device.getType()). - getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); - } - devices.add(device); + if (requireDeviceInfo) { + result.setData(this.getAllDeviceInfo(allDevices)); + } else { + result.setData(allDevices); } - result.setData(devices); + result.setRecordsTotal(deviceCount); result.setRecordsFiltered(deviceCount); return result; @@ -1572,6 +1216,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public List getAllDevicesOfRole(String role) throws DeviceManagementException { + return this.getAllDevicesOfRole(role, true); + } + + @Override + public List getAllDevicesOfRole(String role, boolean requireDeviceInfo) throws DeviceManagementException { List devices = new ArrayList<>(); String[] users; int tenantId = this.getTenantId(); @@ -1594,45 +1243,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } finally { DeviceManagementDAOFactory.closeConnection(); } - for (Device device : userDevices) { - DeviceInfo info = null; - try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'"); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - device.setDeviceInfo(info); - - try { - DeviceManagementDAOFactory.openConnection(); - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); - } catch (DeviceManagementDAOException e) { - log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + - "which carries the id '" + device.getId() + "'", e); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - Device dmsDevice = this.getDeviceManager(device.getType()). - getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); - } - devices.add(device); + if (requireDeviceInfo) { + this.getAllDeviceInfo(userDevices); } } return devices; @@ -1668,70 +1280,40 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public List getDevicesByNameAndType(String deviceName, String type, int offset, int limit) throws DeviceManagementException { + public List getDevicesByNameAndType(PaginationRequest request, boolean requireDeviceInfo) + throws DeviceManagementException { List devices = new ArrayList<>(); List allDevices; - limit = DeviceManagerUtil.validateDeviceListPageSize(limit); + int limit = DeviceManagerUtil.validateDeviceListPageSize(request.getRowCount()); try { DeviceManagementDAOFactory.openConnection(); - allDevices = deviceDAO.getDevicesByNameAndType(deviceName, type, this.getTenantId(), offset, limit); + allDevices = deviceDAO.getDevicesByNameAndType(request.getDeviceName(), request.getDeviceType(), + this.getTenantId(), request.getStartIndex(), limit); } catch (DeviceManagementDAOException e) { throw new DeviceManagementException("Error occurred while fetching the list of devices that matches to '" - + deviceName + "'", e); + + request.getDeviceName() + "'", e); } catch (SQLException e) { throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); } finally { DeviceManagementDAOFactory.closeConnection(); } - for (Device device : allDevices) { - DeviceInfo info = null; - try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'"); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - device.setDeviceInfo(info); - - try { - DeviceManagementDAOFactory.openConnection(); - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); - } catch (DeviceManagementDAOException e) { - log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + - "which carries the id '" + device.getId() + "'", e); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - Device dmsDevice = this.getDeviceManager(device.getType()). - getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); - } - devices.add(device); + if (requireDeviceInfo) { + return this.getAllDeviceInfo(allDevices); } - return devices; + return allDevices; } @Override - public PaginationResult getDevicesByName(PaginationRequest request) - throws DeviceManagementException { + public PaginationResult getDevicesByName(PaginationRequest request) throws DeviceManagementException { + return this.getDevicesByName(request, true); + } + + @Override + public PaginationResult getDevicesByName(PaginationRequest request, boolean requireDeviceInfo) throws + DeviceManagementException { PaginationResult result = new PaginationResult(); int tenantId = this.getTenantId(); - List devices = new ArrayList<>(); List allDevices = new ArrayList<>(); String deviceName = request.getDeviceName(); request = DeviceManagerUtil.validateDeviceListPageSize(request); @@ -1749,47 +1331,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } finally { DeviceManagementDAOFactory.closeConnection(); } - for (Device device : allDevices) { - DeviceInfo info = null; - try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'"); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - device.setDeviceInfo(info); - - try { - DeviceManagementDAOFactory.openConnection(); - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); - } catch (DeviceManagementDAOException e) { - log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + - "which carries the id '" + device.getId() + "'", e); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - Device dmsDevice = this.getDeviceManager(device.getType()). - getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); - } - devices.add(device); + if (requireDeviceInfo) { + result.setData(this.getAllDeviceInfo(allDevices)); + } else { + result.setData(allDevices); } - result.setData(devices); return result; } @@ -1832,8 +1378,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } } + @Override public List getDevicesByStatus(EnrolmentInfo.Status status) throws DeviceManagementException { - List devices = new ArrayList<>(); + return this.getDevicesByStatus(status, true); + } + + @Override + public List getDevicesByStatus(EnrolmentInfo.Status status, boolean requireDeviceInfo) throws + DeviceManagementException { List allDevices; try { DeviceManagementDAOFactory.openConnection(); @@ -1846,54 +1398,21 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } finally { DeviceManagementDAOFactory.closeConnection(); } - for (Device device : allDevices) { - DeviceInfo info = null; - try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'"); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - device.setDeviceInfo(info); - - try { - DeviceManagementDAOFactory.openConnection(); - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); - } catch (DeviceManagementDAOException e) { - log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + - "which carries the id '" + device.getId() + "'", e); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - Device dmsDevice = this.getDeviceManager(device.getType()). - getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); - } - devices.add(device); + if (requireDeviceInfo) { + return this.getAllDeviceInfo(allDevices); } - return devices; + return allDevices; + } + + @Override + public PaginationResult getDevicesByStatus(PaginationRequest request) throws DeviceManagementException { + return this.getDevicesByStatus(request, true); } @Override - public PaginationResult getDevicesByStatus(PaginationRequest request) + public PaginationResult getDevicesByStatus(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException { PaginationResult result = new PaginationResult(); - List devices = new ArrayList<>(); List allDevices = new ArrayList<>(); int tenantId = this.getTenantId(); String status = request.getStatus(); @@ -1912,65 +1431,19 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } finally { DeviceManagementDAOFactory.closeConnection(); } - for (Device device : allDevices) { - DeviceInfo info = null; - try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); - if (info != null) { - info.setLocation(location); - } - } catch (DeviceDetailsMgtDAOException e) { - log.error("Error occurred while retrieving advance info of '" + device.getType() + - "' that carries the id '" + device.getDeviceIdentifier() + "'"); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - device.setDeviceInfo(info); - - try { - DeviceManagementDAOFactory.openConnection(); - List applications = applicationDAO.getInstalledApplications(device.getId()); - device.setApplications(applications); - } catch (DeviceManagementDAOException e) { - log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + - "which carries the id '" + device.getId() + "'", e); - } catch (SQLException e) { - log.error("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - Device dmsDevice = this.getDeviceManager(device.getType()). - getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); - } - devices.add(device); + if (requireDeviceInfo) { + result.setData(this.getAllDeviceInfo(allDevices)); + } else { + result.setData(allDevices); } - result.setData(devices); return result; } @Override public boolean isEnrolled(DeviceIdentifier deviceId, String user) throws DeviceManagementException { - try { - DeviceManagementDAOFactory.openConnection(); - Device device = deviceDAO.getDevice(deviceId, this.getTenantId()); - if (device != null && device.getEnrolmentInfo().getOwner().equals(user)) { - return true; - } - } catch (DeviceManagementDAOException e) { - throw new DeviceManagementException("Error occurred while obtaining the enrollment information device for" + - "id '" + deviceId.getId() + "' and user : " + user, e); - } catch (SQLException e) { - throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); + Device device = this.getDevice(deviceId, false); + if (device != null && device.getEnrolmentInfo() != null && device.getEnrolmentInfo().getOwner().equals(user)) { + return true; } return false; } @@ -1998,7 +1471,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv public boolean changeDeviceStatus(DeviceIdentifier deviceIdentifier, EnrolmentInfo.Status newStatus) throws DeviceManagementException { boolean isDeviceUpdated = false; - Device device = getDevice(deviceIdentifier); + Device device = getDevice(deviceIdentifier, false); int deviceId = device.getId(); EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); enrolmentInfo.setStatus(newStatus); @@ -2019,6 +1492,21 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return isDeviceUpdated; } + @Override + public List getDeviceEnrolledTenants() throws DeviceManagementException { + try { + DeviceManagementDAOFactory.openConnection(); + return deviceDAO.getDeviceEnrolledTenants(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while retrieving the tenants " + + "which have device enrolled.", e); + } catch (SQLException e) { + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + private boolean updateEnrollment(int deviceId, EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementException { boolean isUpdatedEnrollment = false; @@ -2052,21 +1540,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return CarbonContext.getThreadLocalCarbonContext().getTenantId(); } -// private int getTenantId(String tenantDomain) throws DeviceManagementException { -// RealmService realmService = -// (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null); -// if (realmService == null) { -// throw new IllegalStateException(""); -// } -// try { -// return realmService.getTenantManager().getTenantId(tenantDomain); -// } catch (UserStoreException e) { -// throw new DeviceManagementException(""); -// } -// } - private DeviceManager getDeviceManager(String deviceType) { - DeviceManagementService deviceManagementService = pluginRepository.getDeviceManagementService(deviceType, this.getTenantId()); if (deviceManagementService == null) { @@ -2114,22 +1588,21 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv deviceIdentifiers.add(deviceIdentifier); if (init != null) { List initialOperations = init.getOperations(); - - for (String str : initialOperations) { - CommandOperation operation = new CommandOperation(); - operation.setEnabled(true); - operation.setType(Operation.Type.COMMAND); - operation.setCode(str); - try { - deviceManagementProviderService. - addOperation(deviceType, - operation, deviceIdentifiers); - } catch (OperationManagementException e) { - throw new DeviceManagementException("Unable to find the device with the id: '" + deviceIdentifier.getId(), - e); - } catch (InvalidDeviceException e) { - throw new DeviceManagementException("Unable to find the device with the id: '" + deviceIdentifier.getId(), - e); + if (initialOperations != null) { + for (String str : initialOperations) { + CommandOperation operation = new CommandOperation(); + operation.setEnabled(true); + operation.setType(Operation.Type.COMMAND); + operation.setCode(str); + try { + deviceManagementProviderService.addOperation(deviceType, operation, deviceIdentifiers); + } catch (OperationManagementException e) { + throw new DeviceManagementException("Unable to add the operation for the device with the id: '" + + deviceIdentifier.getId(), e); + } catch (InvalidDeviceException e) { + throw new DeviceManagementException("Unable to find the device with the id: '" + + deviceIdentifier.getId(), e); + } } } } @@ -2165,4 +1638,176 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return defaultGroup; } } + + @Override + public void registerDeviceType(DeviceManagementService deviceManagementService) throws DeviceManagementException { + if (deviceManagementService != null) { + pluginRepository.addDeviceManagementProvider(deviceManagementService); + } + } + + @Override + public DeviceType getDeviceType(String deviceType) throws DeviceManagementException { + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + return deviceTypeDAO.getDeviceType(deviceType, tenantId); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while obtaining the device type " + deviceType, e); + } catch (SQLException e) { + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Override + public List getDeviceTypes() throws DeviceManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + DeviceManagementDAOFactory.openConnection(); + return deviceTypeDAO.getDeviceTypes(tenantId); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while obtaining the device types for tenant " + + tenantId, e); + } catch (SQLException e) { + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Override + public void notifyPullNotificationSubscriber(DeviceIdentifier deviceIdentifier, Operation operation) + throws PullNotificationExecutionFailedException { + DeviceManagementService dms = + pluginRepository.getDeviceManagementService(deviceIdentifier.getType(), this.getTenantId()); + if (dms == null) { + String message = "Device type '" + deviceIdentifier.getType() + "' does not have an associated device management " + + "plugin registered within the framework"; + if (log.isDebugEnabled()) { + log.debug(message); + } + throw new PullNotificationExecutionFailedException(message); + } + PullNotificationSubscriber pullNotificationSubscriber = dms.getPullNotificationSubscriber(); + if (pullNotificationSubscriber == null) { + throw new PullNotificationExecutionFailedException("Pull Notification Subscriber is not configured " + + "for device type" + deviceIdentifier.getType()); + } + pullNotificationSubscriber.execute(deviceIdentifier, operation); + } + + /** + * Returns all the device-info including location of the given device. + */ + private DeviceInfo getDeviceInfo(Device device) { + DeviceInfo info = null; + try { + DeviceManagementDAOFactory.openConnection(); + info = deviceInfoDAO.getDeviceInformation(device.getId()); + DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId()); + if (info != null) { + info.setLocation(location); + } + } catch (DeviceDetailsMgtDAOException e) { + log.error("Error occurred while retrieving advance info of '" + device.getType() + + "' that carries the id '" + device.getDeviceIdentifier() + "'"); + } catch (SQLException e) { + log.error("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + return info; + } + + /** + * Returns all the installed apps of the given device. + */ + private List getInstalledApplications(Device device) { + List applications = new ArrayList<>(); + try { + DeviceManagementDAOFactory.openConnection(); + applications = applicationDAO.getInstalledApplications(device.getId()); + device.setApplications(applications); + } catch (DeviceManagementDAOException e) { + log.error("Error occurred while retrieving the application list of '" + device.getType() + "', " + + "which carries the id '" + device.getId() + "'", e); + } catch (SQLException e) { + log.error("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + return applications; + } + + /** + * Returns all the available information (device-info, location, applications and plugin-db data) + * of the given device list. + */ + private List getAllDeviceInfo(List allDevices) + throws DeviceManagementException { + List devices = new ArrayList<>(); + if (allDevices != null) { + for (Device device : allDevices) { + device.setDeviceInfo(this.getDeviceInfo(device)); + device.setApplications(this.getInstalledApplications(device)); + + DeviceManager deviceManager = this.getDeviceManager(device.getType()); + if (deviceManager == null) { + if (log.isDebugEnabled()) { + log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + + "Therefore, not attempting method 'isEnrolled'"); + } + devices.add(device); + continue; + } + Device dmsDevice = + deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + if (dmsDevice != null) { + device.setFeatures(dmsDevice.getFeatures()); + device.setProperties(dmsDevice.getProperties()); + } + devices.add(device); + } + } + return devices; + } + + /** + * Returns all the available information (device-info, location, applications and plugin-db data) + * of a given device. + */ + private Device getAllDeviceInfo(Device device) throws DeviceManagementException { + device.setDeviceInfo(this.getDeviceInfo(device)); + device.setApplications(this.getInstalledApplications(device)); + + DeviceManager deviceManager = this.getDeviceManager(device.getType()); + if (deviceManager == null) { + if (log.isDebugEnabled()) { + log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + + "Therefore, not attempting method 'isEnrolled'"); + } + return device; + } + Device dmsDevice = + deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + if (dmsDevice != null) { + device.setFeatures(dmsDevice.getFeatures()); + device.setProperties(dmsDevice.getProperties()); + } + return device; + } + + private Device getDeviceFromCache(DeviceIdentifier deviceIdentifier) { + return DeviceCacheManagerImpl.getInstance().getDeviceFromCache(deviceIdentifier, this.getTenantId()); + } + + private void addDeviceToCache(DeviceIdentifier deviceIdentifier, Device device) { + DeviceCacheManagerImpl.getInstance().addDeviceToCache(deviceIdentifier, device, this.getTenantId()); + } + + private void removeDeviceFromCache(DeviceIdentifier deviceIdentifier) { + DeviceCacheManagerImpl.getInstance().removeDeviceFromCache(deviceIdentifier, this.getTenantId()); + } } 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 875cc859e5..054a923c43 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 @@ -212,4 +212,12 @@ public interface GroupManagementProviderService { */ List getGroups(DeviceIdentifier deviceIdentifier) throws GroupManagementException; + /** + * Checks for the default group existence and create group based on device ownership. + * @param groupName + * @return + * @throws GroupManagementException + */ + DeviceGroup createDefaultGroup(String groupName) 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 94b480978e..ad8ecf77d1 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 @@ -30,10 +30,7 @@ import org.wso2.carbon.device.mgt.common.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.TransactionManagementException; -import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; -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.RoleDoesNotExistException; +import org.wso2.carbon.device.mgt.common.group.mgt.*; import org.wso2.carbon.device.mgt.core.dao.GroupDAO; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; @@ -367,39 +364,41 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid @Override public void manageGroupSharing(int groupId, List newRoles) throws GroupManagementException, RoleDoesNotExistException { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - UserStoreManager userStoreManager; - try { - userStoreManager = - DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( - tenantId).getUserStoreManager(); - List currentUserRoles = getRoles(groupId); - GroupManagementDAOFactory.beginTransaction(); - for (String role : newRoles) { - if (!userStoreManager.isExistingRole(role)) { - throw new RoleDoesNotExistException("Role '" + role + "' does not exists in the user store."); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + UserStoreManager userStoreManager; + try { + userStoreManager = + DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( + tenantId).getUserStoreManager(); + List currentUserRoles = getRoles(groupId); + GroupManagementDAOFactory.beginTransaction(); + if (newRoles != null) { + for (String role : newRoles) { + if (!userStoreManager.isExistingRole(role)) { + throw new RoleDoesNotExistException("Role '" + role + "' does not exists in the user store."); + } + // Removing role from current user roles of the group will return true if role exist. + // So we don't need to add it to the db again. + if (!currentUserRoles.remove(role)) { + // If group doesn't have the role, it is adding to the db. + groupDAO.addRole(groupId, role, tenantId); + } + } } - // Removing role from current user roles of the group will return true if role exist. - // So we don't need to add it to the db again. - if (!currentUserRoles.remove(role)) { - // If group doesn't have the role, it is adding to the db. - groupDAO.addRole(groupId, role, tenantId); + for (String role : currentUserRoles) { + // Removing old roles from db which are not available in the new roles list. + groupDAO.removeRole(groupId, role, tenantId); } - } - for (String role : currentUserRoles) { - // Removing old roles from db which are not available in the new roles list. - groupDAO.removeRole(groupId, role, tenantId); - } - GroupManagementDAOFactory.commitTransaction(); - } catch (GroupManagementDAOException e) { - GroupManagementDAOFactory.rollbackTransaction(); - throw new GroupManagementException(e); - } catch (UserStoreException e) { - throw new GroupManagementException("User store error in updating sharing roles.", e); - } catch (TransactionManagementException e) { - throw new GroupManagementException(e); - } finally { - GroupManagementDAOFactory.closeConnection(); + GroupManagementDAOFactory.commitTransaction(); + } catch (GroupManagementDAOException e) { + GroupManagementDAOFactory.rollbackTransaction(); + throw new GroupManagementException(e); + } catch (UserStoreException e) { + throw new GroupManagementException("User store error in updating sharing roles.", e); + } catch (TransactionManagementException e) { + throw new GroupManagementException(e); + } finally { + GroupManagementDAOFactory.closeConnection(); } } @@ -430,12 +429,15 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); List devices; try { + rowCount = DeviceManagerUtil.validateDeviceListPageSize(rowCount); GroupManagementDAOFactory.openConnection(); devices = this.groupDAO.getDevices(groupId, startIndex, rowCount, tenantId); } catch (GroupManagementDAOException e) { throw new GroupManagementException("Error occurred while getting devices in group.", e); } catch (SQLException e) { throw new GroupManagementException("Error occurred while opening a connection to the data source.", e); + } catch (DeviceManagementException e) { + throw new GroupManagementException("Error occurred while validating the limit of the devices to be returned", e); } finally { GroupManagementDAOFactory.closeConnection(); } @@ -469,12 +471,13 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid try { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); GroupManagementDAOFactory.beginTransaction(); - for (DeviceIdentifier deviceIdentifier : deviceIdentifiers){ - device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier); + for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) { + device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider(). + getDevice(deviceIdentifier, false); if (device == null) { throw new DeviceNotFoundException("Device not found for id '" + deviceIdentifier.getId() + "'"); } - if (!this.groupDAO.isDeviceMappedToGroup(groupId, device.getId(), tenantId)){ + if (!this.groupDAO.isDeviceMappedToGroup(groupId, device.getId(), tenantId)) { this.groupDAO.addDevice(groupId, device.getId(), tenantId); } } @@ -501,8 +504,9 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid try { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); GroupManagementDAOFactory.beginTransaction(); - for (DeviceIdentifier deviceIdentifier : deviceIdentifiers){ - device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier); + for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) { + device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider(). + getDevice(deviceIdentifier, false); if (device == null) { throw new DeviceNotFoundException("Device not found for id '" + deviceIdentifier.getId() + "'"); } @@ -551,10 +555,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid public List getGroups(DeviceIdentifier deviceIdentifier) throws GroupManagementException { DeviceManagementProviderService managementProviderService = new DeviceManagementProviderServiceImpl(); try { - Device device = managementProviderService.getDevice(deviceIdentifier); + Device device = managementProviderService.getDevice(deviceIdentifier, false); GroupManagementDAOFactory.openConnection(); return groupDAO.getGroups(device.getId(), - PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); } catch (DeviceManagementException e) { throw new GroupManagementException("Error occurred while retrieving the device details.", e); } catch (GroupManagementDAOException e) { @@ -565,4 +569,31 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid GroupManagementDAOFactory.closeConnection(); } } + + /** + * {@inheritDoc} + */ + @Override + public DeviceGroup createDefaultGroup(String groupName) throws GroupManagementException { + + DeviceGroup defaultGroup = this.getGroup(groupName); + if (defaultGroup == null) { + defaultGroup = new DeviceGroup(groupName); + // Setting system level user (wso2.system.user) as the owner + defaultGroup.setOwner(CarbonConstants.REGISTRY_SYSTEM_USERNAME); + defaultGroup.setDescription("Default system group for devices with " + groupName + " ownership."); + try { + this.createGroup(defaultGroup, DeviceGroupConstants.Roles.DEFAULT_ADMIN_ROLE, + DeviceGroupConstants.Permissions.DEFAULT_ADMIN_PERMISSIONS); + } catch (GroupAlreadyExistException e) { + if (log.isDebugEnabled()) { + log.debug("Default group: " + defaultGroup.getName() + " already exists. Skipping group creation.", + e); + } + } + return this.getGroup(groupName); + } else { + return defaultGroup; + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/DeviceStatusTaskException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/DeviceStatusTaskException.java new file mode 100644 index 0000000000..76db9731bb --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/DeviceStatusTaskException.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2017, 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. + */ + + +package org.wso2.carbon.device.mgt.core.status.task; + +/** + * This exception class defines the custom exceptions thrown by the DeviceStatusMonitoringTask related components. + */ +public class DeviceStatusTaskException extends Exception { + + private static final long serialVersionUID = -31222242646464497L; + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public DeviceStatusTaskException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public DeviceStatusTaskException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public DeviceStatusTaskException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public DeviceStatusTaskException() { + super(); + } + + public DeviceStatusTaskException(Throwable cause) { + super(cause); + } + +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/DeviceStatusTaskManagerService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/DeviceStatusTaskManagerService.java new file mode 100644 index 0000000000..5cab3012ef --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/DeviceStatusTaskManagerService.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.status.task; + +import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; + +/** + * This interface defines the methods that should be implemented by the management service of + * DeviceStatusMonitoringTask. + */ +public interface DeviceStatusTaskManagerService { + + /** + * This method will start the task. + * + * @param deviceType - DeviceType + * @param deviceStatusTaskConfig - DeviceStatusTaskConfig + * @throws DeviceStatusTaskException + */ + void startTask(DeviceType deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskConfig) + throws DeviceStatusTaskException; + + /** + * This method will stop the task. + * + * @param deviceType - DeviceType + * @param deviceStatusTaskConfig - DeviceStatusTaskConfig + * @throws DeviceStatusTaskException + */ + void stopTask(DeviceType deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskConfig) + throws DeviceStatusTaskException; + + /** + * This will update the task frequency which it runs. + * + * @param deviceType + * @param deviceStatusTaskConfig - DeviceStatusTaskConfig + * @throws DeviceStatusTaskException + */ + void updateTask(DeviceType deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskConfig) + throws DeviceStatusTaskException; + + /** + * This will check weather the task is scheduled. + * @param deviceType - Device Type + * @throws DeviceStatusTaskException + */ + boolean isTaskScheduled(DeviceType deviceType) throws DeviceStatusTaskException; +} \ No newline at end of file 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 new file mode 100644 index 0000000000..101e549c63 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.status.task.impl; + +import com.google.gson.Gson; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskException; +import org.wso2.carbon.ntask.core.Task; + +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 + * necessary. + */ +public class DeviceStatusMonitoringTask implements Task { + + 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) { + 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 + public void init() { + + } + + @Override + public void execute() { + List operationEnrolmentMappings = null; + List enrolmentInfoTobeUpdated = new ArrayList<>(); + List identifiers = new ArrayList<>(); + Map lastActivities = null; + EnrolmentInfo enrolmentInfo; + DeviceIdentifier deviceIdentifier; + try { + operationEnrolmentMappings = this.getOperationEnrolmentMappings(); + if (operationEnrolmentMappings != null && operationEnrolmentMappings.size() > 0) { + lastActivities = this.getLastDeviceActivities(); + } + } catch (DeviceStatusTaskException e) { + log.error("Error occurred while fetching OperationEnrolment mappings of deviceType '" + deviceType + "'", e); + } + for (OperationEnrolmentMapping mapping:operationEnrolmentMappings) { + long lastActivity = -1; + if (lastActivities != null && lastActivities.containsKey(mapping.getEnrolmentId())) { + lastActivity = lastActivities.get(mapping.getEnrolmentId()); + } + EnrolmentInfo.Status newStatus = this.determineDeviceStatus(mapping, lastActivity); + if (newStatus != mapping.getDeviceStatus()) { + enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setId(mapping.getEnrolmentId()); + enrolmentInfo.setStatus(newStatus); + enrolmentInfoTobeUpdated.add(enrolmentInfo); + + deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(mapping.getDeviceId()); + deviceIdentifier.setId(mapping.getDeviceType()); + identifiers.add(deviceIdentifier); + } + } + + if (enrolmentInfoTobeUpdated.size() > 0) { + try { + this.updateDeviceStatus(enrolmentInfoTobeUpdated); + //Remove updated entries from cache + //DeviceCacheManagerImpl.getInstance().removeDevicesFromCache(identifiers); + } catch (DeviceStatusTaskException e) { + log.error("Error occurred while updating non-responsive device-status of devices of type '" + deviceType + "'",e); + } + } + } + + private EnrolmentInfo.Status determineDeviceStatus(OperationEnrolmentMapping opMapping, long lastActivityTime) { + long lastPendingOpBefore = (System.currentTimeMillis()/1000) - opMapping.getCreatedTime(); + EnrolmentInfo.Status newStatus = null; + if (lastPendingOpBefore >= this.deviceStatusTaskPluginConfig.getIdleTimeToMarkInactive()) { + newStatus = EnrolmentInfo.Status.INACTIVE; + } else if (lastPendingOpBefore >= this.deviceStatusTaskPluginConfig.getIdleTimeToMarkUnreachable()) { + newStatus = EnrolmentInfo.Status.UNREACHABLE; + } + if (lastActivityTime != -1) { + long lastActivityBefore = (System.currentTimeMillis()/1000) - lastActivityTime; + if (lastActivityBefore < lastPendingOpBefore) { + return opMapping.getDeviceStatus(); + } + } + return newStatus; + } + + private long getMinTimeWindow() { + return (System.currentTimeMillis()/1000) - this.deviceStatusTaskPluginConfig.getIdleTimeToMarkUnreachable(); + } + + private long getMaxTimeWindow() { + //Need to consider the frequency of the task as well + return (System.currentTimeMillis()/1000) - this.deviceStatusTaskPluginConfig.getIdleTimeToMarkInactive() - + this.deviceStatusTaskPluginConfig.getFrequency(); + } + + private boolean updateDeviceStatus(List enrolmentInfos) throws + DeviceStatusTaskException { + boolean updateStatus; + try { + DeviceManagementDAOFactory.beginTransaction(); + updateStatus = DeviceManagementDAOFactory.getEnrollmentDAO().updateEnrollmentStatus(enrolmentInfos); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + throw new DeviceStatusTaskException("Error occurred while updating enrollment status of devices of type '" + + deviceType + "'", e); + } catch (TransactionManagementException e) { + throw new DeviceStatusTaskException("Error occurred while initiating a transaction for updating the device " + + "status of type '" + deviceType +"'", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + return updateStatus; + } + + private List getOperationEnrolmentMappings() throws DeviceStatusTaskException { + List operationEnrolmentMappings = null; + try { + OperationManagementDAOFactory.openConnection(); + operationEnrolmentMappings = OperationManagementDAOFactory. + getOperationMappingDAO().getFirstPendingOperationMappingsForActiveEnrolments(this.getMinTimeWindow(), + this.getMaxTimeWindow(), this.deviceTypeId); + } catch (SQLException e) { + throw new DeviceStatusTaskException("Error occurred while getting Enrolment operation mappings for " + + "determining device status of deviceType '" + deviceType + "'", e); + } catch (OperationManagementDAOException e) { + throw new DeviceStatusTaskException("Error occurred obtaining a DB connection for fetching " + + "operation-enrolment mappings for status monitoring of deviceType '" + deviceType + "'", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + return operationEnrolmentMappings; + } + + private Map getLastDeviceActivities() throws DeviceStatusTaskException { + Map lastActivities = null; + try { + OperationManagementDAOFactory.openConnection(); + lastActivities = OperationManagementDAOFactory. + getOperationMappingDAO().getLastConnectedTimeForActiveEnrolments(this.getMaxTimeWindow(), + this.deviceTypeId); + } catch (SQLException e) { + throw new DeviceStatusTaskException("Error occurred while getting last activities for " + + "determining device status of deviceType '" + deviceType + "'", e); + } catch (OperationManagementDAOException e) { + throw new DeviceStatusTaskException("Error occurred obtaining a DB connection for fetching " + + "last activities for status monitoring of deviceType '" + deviceType + "'", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + return lastActivities; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusTaskManagerServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusTaskManagerServiceImpl.java new file mode 100644 index 0000000000..988be3f4d0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusTaskManagerServiceImpl.java @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.core.status.task.impl; + +import com.google.gson.Gson; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskException; +import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskManagerService; +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.HashMap; +import java.util.Map; + +/** + * Implementation of DeviceStatusTaskManagerService. + */ +public class DeviceStatusTaskManagerServiceImpl implements DeviceStatusTaskManagerService { + + private static final Log log = LogFactory.getLog(DeviceStatusTaskManagerServiceImpl.class); + + public static final String DEVICE_STATUS_MONITORING_TASK_TYPE = "DEVICE_STATUS_MONITORING"; + static final String DEVICE_TYPE = "DEVICE_TYPE"; + static final String DEVICE_TYPE_ID = "DEVICE_TYPE_ID"; + static final String DEVICE_STATUS_TASK_CONFIG = "DEVICE_STATUS_TASK_CONFIG"; + private static final String TASK_CLASS = DeviceStatusMonitoringTask.class.getName(); + + @Override + public void startTask(DeviceType deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskConfig) + throws DeviceStatusTaskException { + log.info("Device Status monitoring Task adding for " + deviceType.getName()); + + try { + TaskService taskService = DeviceManagementDataHolder.getInstance().getTaskService(); + taskService.registerTaskType(DEVICE_STATUS_MONITORING_TASK_TYPE); + + if (log.isDebugEnabled()) { + log.debug("Device Status monitoring task is started for the device type " + deviceType.getName()); + log.debug( + "Device Status monitoring task is at frequency of : " + deviceStatusTaskConfig.getFrequency()); + } + + TaskManager taskManager = taskService.getTaskManager(DEVICE_STATUS_MONITORING_TASK_TYPE); + + TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); + //Convert to milli seconds + triggerInfo.setIntervalMillis(deviceStatusTaskConfig.getFrequency()*1000); + triggerInfo.setRepeatCount(-1); + + Gson gson = new Gson(); + String deviceStatusTaskConfigs = gson.toJson(deviceStatusTaskConfig); + + Map properties = new HashMap<>(); + + properties.put(DEVICE_TYPE, deviceType.getName()); + properties.put(DEVICE_TYPE_ID, deviceType.getId() + ""); + properties.put(DEVICE_STATUS_TASK_CONFIG, deviceStatusTaskConfigs); + + String taskName = DEVICE_STATUS_MONITORING_TASK_TYPE + "_" + deviceType.getName() + "_" + deviceType.getId(); + + if (!taskManager.isTaskScheduled(taskName)) { + TaskInfo taskInfo = new TaskInfo(taskName, TASK_CLASS, properties, triggerInfo); + taskManager.registerTask(taskInfo); + taskManager.rescheduleTask(taskInfo.getName()); + } else { + throw new DeviceStatusTaskException( + "Device Status monitoring task is already started for this device-type : " + deviceType.getName()); + } + } catch (TaskException e) { + throw new DeviceStatusTaskException("Error occurred while creating the Device Status monitoring task " + + "for device-type : " + deviceType.getName(), e); + } + } + + @Override + public void stopTask(DeviceType deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskConfig) + throws DeviceStatusTaskException { + try { + TaskService taskService = DeviceManagementDataHolder.getInstance().getTaskService(); + String taskName = DEVICE_STATUS_MONITORING_TASK_TYPE + "_" + deviceType.getName() + "_" + deviceType.getId(); + if (taskService.isServerInit()) { + TaskManager taskManager = taskService.getTaskManager(DEVICE_STATUS_MONITORING_TASK_TYPE); + taskManager.deleteTask(taskName); + } + } catch (TaskException e) { + throw new DeviceStatusTaskException("Error occurred while deleting the Device Status monitoring task " + + "for device-type : " + deviceType.getName(), e); + } + } + + @Override + public void updateTask(DeviceType deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskConfig) + throws DeviceStatusTaskException { + try { + TaskService taskService = DeviceManagementDataHolder.getInstance().getTaskService(); + TaskManager taskManager = taskService.getTaskManager(DEVICE_STATUS_MONITORING_TASK_TYPE); + String taskName = DEVICE_STATUS_MONITORING_TASK_TYPE + "_" + deviceType + "_" + deviceType.getId(); + if (taskManager.isTaskScheduled(taskName)) { + taskManager.deleteTask(taskName); + TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); + triggerInfo.setIntervalMillis(deviceStatusTaskConfig.getFrequency()); + triggerInfo.setRepeatCount(-1); + + Map properties = new HashMap<>(); + properties.put(DEVICE_TYPE, deviceType.getName()); + properties.put(DEVICE_TYPE_ID, deviceType.getId() + ""); + + Gson gson = new Gson(); + String deviceStatusTaskConfigs = gson.toJson(deviceStatusTaskConfig); + properties.put(DEVICE_STATUS_TASK_CONFIG, deviceStatusTaskConfigs); + + TaskInfo taskInfo = new TaskInfo(taskName, TASK_CLASS, properties, triggerInfo); + + taskManager.registerTask(taskInfo); + taskManager.rescheduleTask(taskInfo.getName()); + } else { + throw new DeviceStatusTaskException( + "Device details retrieving Device Status monitoring task has not been started for this device-type " + + deviceType.getName() + ". Please start the task first."); + } + + } catch (TaskException e) { + throw new DeviceStatusTaskException("Error occurred while updating the Device Status monitoring " + + "task for device-type : " + deviceType.getName(), e); + } + } + + @Override + public boolean isTaskScheduled(DeviceType deviceType) throws DeviceStatusTaskException { + String taskName = DEVICE_STATUS_MONITORING_TASK_TYPE + "_" + deviceType.getName() + "_" + deviceType.getId(); + TaskService taskService = DeviceManagementDataHolder.getInstance().getTaskService(); + TaskManager taskManager; + try { + taskManager = taskService.getTaskManager(DEVICE_STATUS_MONITORING_TASK_TYPE); + return taskManager.isTaskScheduled(taskName); + } catch (TaskException e) { + throw new DeviceStatusTaskException("Error occurred while checking Device Status monitoring task for device-type : " + + deviceType.getName(), e); + } + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManager.java index 46128a37aa..c4db7c3531 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManager.java @@ -45,7 +45,7 @@ public interface DeviceTaskManager { // String getTaskImplementedClazz() throws DeviceMgtTaskException; /** - * This method checks wheather task is enabled in config file. + * This method checks whether task is enabled in config file. * @return - return true or false * @throws DeviceMgtTaskException */ @@ -67,7 +67,7 @@ public interface DeviceTaskManager { // List getValidOperationNames(String deviceType) throws DeviceMgtTaskException; /** - * This method will check wheather give operation is added by the task. + * This method will check whether given operation is added by the task. * @param opName - Operation name * @return - true or false * @throws DeviceMgtTaskException 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 6d1228563c..7b65a3b6ee 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 @@ -22,20 +22,26 @@ package org.wso2.carbon.device.mgt.core.task.impl; import com.google.gson.Gson; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManager; import org.wso2.carbon.ntask.core.Task; +import org.wso2.carbon.user.api.UserStoreException; +import java.util.List; import java.util.Map; public class DeviceDetailsRetrieverTask implements Task { private static Log log = LogFactory.getLog(DeviceDetailsRetrieverTask.class); -// private DeviceTaskManager deviceTaskManager = new DeviceTaskManagerImpl(); private String deviceType; private String oppConfig; private OperationMonitoringTaskConfig operationMonitoringTaskConfig; + private boolean executeForTenants = false; + private final String IS_CLOUD = "is.cloud"; @Override public void setProperties(Map map) { @@ -54,21 +60,62 @@ public class DeviceDetailsRetrieverTask implements Task { @Override public void execute() { - if (log.isDebugEnabled()) { - log.debug("Device details retrieving task started to run."); + + if(System.getProperty(IS_CLOUD) != null && Boolean.parseBoolean(System.getProperty(IS_CLOUD))){ + executeForTenants = true; } + if(executeForTenants){ + this.executeForAllTenants(); + } else { + if (log.isDebugEnabled()) { + log.debug("Device details retrieving task started to run."); + } + DeviceTaskManager deviceTaskManager = new DeviceTaskManagerImpl(deviceType, + operationMonitoringTaskConfig); + //pass the configurations also from here, monitoring tasks + try { + deviceTaskManager.addOperations(); + } catch (DeviceMgtTaskException e) { + log.error( + "Error occurred while trying to add the operations to device to retrieve device details.", e); + } + } + } - DeviceTaskManager deviceTaskManager = new DeviceTaskManagerImpl(deviceType, - operationMonitoringTaskConfig); - //pass the configurations also from here, monitoring tasks + private void executeForAllTenants() { + + if (log.isDebugEnabled()) { + log.debug("Device details retrieving task started to run for all tenants."); + } try { - deviceTaskManager.addOperations(); - } catch (DeviceMgtTaskException e) { - log.error( - "Error occurred while trying to add the operations to device to retrieve device details.", - e); + List tenants = DeviceManagementDataHolder.getInstance(). + getDeviceManagementProvider().getDeviceEnrolledTenants(); + for (Integer tenant : tenants) { + String tenantDomain = DeviceManagementDataHolder.getInstance(). + getRealmService().getTenantManager().getDomain(tenant); + try { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenant); + DeviceTaskManager deviceTaskManager = new DeviceTaskManagerImpl(deviceType, + operationMonitoringTaskConfig); + //pass the configurations also from here, monitoring tasks + try { + deviceTaskManager.addOperations(); + } catch (DeviceMgtTaskException e) { + log.error("Error occurred while trying to add the operations to " + + "device to retrieve device details.", e); + } + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } + } catch (UserStoreException e) { + log.error("Error occurred while trying to get the available tenants", e); + } catch (DeviceManagementException e) { + log.error("Error occurred while trying to get the available tenants " + + "from device manager provider service.", e); } - } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java index 16fff9ce13..41d291e74e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java @@ -90,15 +90,21 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager { List operations; operations = this.getValidOperationNames(); //list operations for each device type - devices = deviceManagementProviderService.getAllDevices(deviceType);//list devices for each type + devices = deviceManagementProviderService.getAllDevices(deviceType, false);//list devices for each type if (!devices.isEmpty()) { - for (String str : operations) { - CommandOperation operation = new CommandOperation(); - operation.setEnabled(true); - operation.setType(Operation.Type.COMMAND); - operation.setCode(str); - deviceManagementProviderService.addOperation(deviceType, operation, - DeviceManagerUtil.getValidDeviceIdentifiers(devices)); + if (operations != null && DeviceManagerUtil.getValidDeviceIdentifiers(devices).size() != 0) { + for (String str : operations) { + CommandOperation operation = new CommandOperation(); + operation.setEnabled(true); + operation.setType(Operation.Type.COMMAND); + operation.setCode(str); + deviceManagementProviderService.addOperation(deviceType, operation, + DeviceManagerUtil.getValidDeviceIdentifiers(devices)); + } + } else { + if (log.isDebugEnabled()) { + log.debug("No operations are available."); + } } } else { if (log.isDebugEnabled()) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerServiceImpl.java index d23939f866..b8119222db 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerServiceImpl.java @@ -53,7 +53,6 @@ public class DeviceTaskManagerServiceImpl implements DeviceTaskManagerService { log.info("Task adding for " + deviceType); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - try { TaskService taskService = DeviceManagementDataHolder.getInstance().getTaskService(); taskService.registerTaskType(TASK_TYPE); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index c5558fe92a..50582799ce 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -21,10 +21,21 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.device.mgt.common.*; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; +import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey; 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.config.datasource.DataSourceConfig; @@ -43,18 +54,30 @@ import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.NetworkUtils; +import javax.cache.Cache; +import javax.cache.CacheConfiguration; +import javax.cache.CacheManager; +import javax.cache.Caching; import javax.sql.DataSource; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; -import java.util.*; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; public final class DeviceManagerUtil { private static final Log log = LogFactory.getLog(DeviceManagerUtil.class); + private static boolean isDeviceCacheInistialized = false; + public static Document convertToDocument(File file) throws DeviceManagementException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); @@ -108,7 +131,8 @@ public final class DeviceManagerUtil { * @param isSharedWithAllTenants is this device type shared with all tenants. * @return status of the operation */ - public static boolean registerDeviceType(String typeName, int tenantId, boolean isSharedWithAllTenants) + public static boolean registerDeviceType(String typeName, int tenantId, boolean isSharedWithAllTenants + , DeviceTypeMetaDefinition deviceTypeDefinition) throws DeviceManagementException { boolean status; try { @@ -118,7 +142,13 @@ public final class DeviceManagerUtil { if (deviceType == null) { deviceType = new DeviceType(); deviceType.setName(typeName); + deviceType.setDeviceTypeMetaDefinition(deviceTypeDefinition); deviceTypeDAO.addDeviceType(deviceType, tenantId, isSharedWithAllTenants); + } else { + if (deviceTypeDefinition != null) { + deviceType.setDeviceTypeMetaDefinition(deviceTypeDefinition); + deviceTypeDAO.updateDeviceType(deviceType, tenantId); + } } DeviceManagementDAOFactory.commitTransaction(); status = true; @@ -136,6 +166,31 @@ public final class DeviceManagerUtil { return status; } + /** + * Get the DeviceType information from Database. + * + * @param typeName device type + * @param tenantId provider tenant Id + * @return DeviceType which contains info about the device-type. + */ + public static DeviceType getDeviceType(String typeName, int tenantId) throws DeviceManagementException { + DeviceType deviceType = null; + try { + DeviceManagementDAOFactory.openConnection(); + DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); + deviceType = deviceTypeDAO.getDeviceType(typeName, tenantId); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while fetching the device type '" + + typeName + "'", e); + } catch (SQLException e) { + throw new DeviceManagementException("SQL Error occurred while fetching the device type '" + + typeName + "'", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + return deviceType; + } + /** * Un-registers an existing device type from the device management metadata repository. * @@ -192,6 +247,7 @@ public final class DeviceManagerUtil { switch (device.getEnrolmentInfo().getStatus()) { case BLOCKED: case REMOVED: + break; case SUSPENDED: break; default: @@ -358,6 +414,17 @@ public final class DeviceManagerUtil { return limit; } + public static boolean isPublishLocationOperationResEnabled() throws DeviceManagementException { + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig(); + if (deviceManagementConfig != null) { + return deviceManagementConfig.getGeoLocationConfiguration().getPublishLocationOperationResponse(); + } else { + throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " + + "cdm-config.xml file."); + } + } + public static DeviceIDHolder validateDeviceIdentifiers(List deviceIDs) { List errorDeviceIdList = new ArrayList(); @@ -395,7 +462,8 @@ public final class DeviceManagerUtil { } public static boolean isValidDeviceIdentifier(DeviceIdentifier deviceIdentifier) throws DeviceManagementException { - Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier); + Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier, + false); if (device == null || device.getDeviceIdentifier() == null || device.getDeviceIdentifier().isEmpty() || device.getEnrolmentInfo() == null) { return false; @@ -404,4 +472,69 @@ public final class DeviceManagerUtil { } return true; } + + private static CacheManager getCacheManager() { + return Caching.getCacheManagerFactory().getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER); + } + + public static EventsPublisherService getEventPublisherService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + EventsPublisherService eventsPublisherService = + (EventsPublisherService) ctx.getOSGiService(EventsPublisherService.class, null); + if (eventsPublisherService == null) { + String msg = "Event Publisher service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return eventsPublisherService; + } + + public static void initializeDeviceCache() { + DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); + int deviceCacheExpiry = config.getDeviceCacheConfiguration().getExpiryTime(); + CacheManager manager = getCacheManager(); + if (config.getDeviceCacheConfiguration().isEnabled()) { + if(!isDeviceCacheInistialized) { + isDeviceCacheInistialized = true; + if (manager != null) { + if (deviceCacheExpiry > 0) { + manager.createCacheBuilder(DeviceManagementConstants.DEVICE_CACHE). + setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS, + deviceCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration. + Duration(TimeUnit.SECONDS, deviceCacheExpiry)).setStoreByValue(true).build(); + } else { + manager.getCache(DeviceManagementConstants.DEVICE_CACHE); + } + } else { + if (deviceCacheExpiry > 0) { + Caching.getCacheManager(). + createCacheBuilder(DeviceManagementConstants.DEVICE_CACHE). + setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS, + deviceCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration. + Duration(TimeUnit.SECONDS, deviceCacheExpiry)).setStoreByValue(true).build(); + } else { + Caching.getCacheManager().getCache(DeviceManagementConstants.DEVICE_CACHE); + } + } + } + } + } + + public static Cache getDeviceCache() { + DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); + CacheManager manager = getCacheManager(); + Cache deviceCache = null; + if (config.getDeviceCacheConfiguration().isEnabled()) { + if(!isDeviceCacheInistialized) { + initializeDeviceCache(); + } + if (manager != null) { + deviceCache = manager.getCache(DeviceManagementConstants.DEVICE_CACHE); + } else { + deviceCache = Caching.getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER). + getCache(DeviceManagementConstants.DEVICE_CACHE); + } + } + return deviceCache; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Exit_alert.siddhiql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Exit_alert.siddhiql new file mode 100644 index 0000000000..7f391b530b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Exit_alert.siddhiql @@ -0,0 +1,20 @@ +/* Enter a unique ExecutionPlan */ +@Plan:name('$executionPlanName') + +/* Enter a unique description for ExecutionPlan */ +-- @Plan:description('ExecutionPlan') + +/* define streams/tables and write queries here ... */ + +@Import('org.wso2.geo.StandardSpatialEvents:1.0.0') +define stream dataIn (id string, latitude double, longitude double, timeStamp long, type string ,speed float, heading float, eventId string); + +@Export('org.wso2.geo.ProcessedSpatialEvents:1.0.0') +define stream dataOut (id string, latitude double, longitude double, timeStamp long, type string ,speed float, heading float, eventId string, state string, information string); + +from dataIn[geo:within(longitude,latitude,"$geoFenceGeoJSON")==false and id == "$deviceId"]#geodashboard:subscribe() +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , "ALERTED" as state, "This device is outside $areaName area!!!" as information +insert into dataOut; +from dataIn[geo:within(longitude,latitude,"$geoFenceGeoJSON")!=false and id == "$deviceId"] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , "NORMAL" as state, "" as information +insert into dataOut; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Proximity_alert.siddhiql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Proximity_alert.siddhiql new file mode 100644 index 0000000000..fb64720391 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Proximity_alert.siddhiql @@ -0,0 +1,140 @@ +/* Enter a unique ExecutionPlan */ +@Plan:name('Geo-ExecutionPlan-Proximity_alert') + +/* Enter a unique description for ExecutionPlan */ +-- @Plan:description('ExecutionPlan') + +/* define streams/tables and write queries here ... */ + +@Import('org.wso2.geo.StandardSpatialEvents:1.0.0') +define stream dataIn (id string, latitude double, longitude double, timeStamp long, type string, speed float, heading float, eventId string ); + +@Export('org.wso2.geo.ProcessedSpatialEvents:1.0.0') +define stream dataOut ( id string, latitude double, longitude double, timeStamp long, type string, speed float, heading float, eventId string, state string, information string ); + +@IndexBy('id') +define table ProximityTable(id string, timeStamp long); + +@IndexBy('id') +define table AlertsTable(id string , proximityWith string, eventId string); + +from dataIn#geodashboard:subscribe() +select id, latitude, longitude, timeStamp, type, speed, heading, eventId +insert into initialStream; + +from initialStream[type == 'STOP'] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , "" as proximityInfo ,"false" as isProximity +insert into dataOutStream; + +from initialStream[type != 'STOP'] +select * +insert into objectInitialStream; + +from objectInitialStream#geo:proximity(id,longitude,latitude, $proximityDistance) +select id, latitude, longitude, timeStamp, type, speed, heading, eventId,inCloseProximity,proximityWith +insert into proxymityStream; + +from proxymityStream[AlertsTable.id == proxymityStream.id in AlertsTable] +select id, latitude, longitude, timeStamp, type, speed, heading, eventId,inCloseProximity,proximityWith,true as inAlertTable +insert into innerStreamOne; + +from proxymityStream[not(AlertsTable.id == proxymityStream.id in AlertsTable)] +select id, latitude, longitude, timeStamp, type, speed, heading, eventId,inCloseProximity,proximityWith,false as inAlertTable +insert into innerStreamOne; + +from proxymityStream[AlertsTable.id == proxymityStream.proximityWith in AlertsTable] +select id, latitude, longitude, timeStamp, type, speed, heading, eventId,inCloseProximity,proximityWith,true as inAlertTable +insert into innerStreamSeven; + +from proxymityStream[not(AlertsTable.id == proxymityStream.proximityWith in AlertsTable)] +select id, latitude, longitude, timeStamp, type, speed, heading, eventId,inCloseProximity,proximityWith,false as inAlertTable +insert into innerStreamSeven; + +from innerStreamOne[inCloseProximity == true AND not(inAlertTable)] +select id,str:concat(",",proximityWith) as proximityWith , eventId +insert into AlertsTable; + +from innerStreamSeven[inCloseProximity == true AND not(inAlertTable)] +select proximityWith as id,str:concat(",",id) as proximityWith , eventId +insert into AlertsTable; + +from innerStreamOne[innerStreamOne.inCloseProximity == true AND inAlertTable]#window.length(0) join AlertsTable +on innerStreamOne.id == AlertsTable.id +select innerStreamOne.id as id, str:concat(",", innerStreamOne.proximityWith, AlertsTable.proximityWith) as proximityWith, innerStreamOne.eventId as eventId +insert into updateStream; + +from innerStreamSeven[innerStreamSeven.inCloseProximity == true AND inAlertTable]#window.length(0) join AlertsTable +on innerStreamSeven.proximityWith == AlertsTable.id +select innerStreamSeven.proximityWith as id, str:concat(",", innerStreamSeven.id, AlertsTable.proximityWith) as proximityWith, innerStreamSeven.eventId as eventId +insert into updateStream; + +from innerStreamOne[innerStreamOne.inCloseProximity == false AND inAlertTable]#window.length(0) join AlertsTable +on innerStreamOne.id == AlertsTable.id +select innerStreamOne.id as id, str:replaceAll(AlertsTable.proximityWith, str:concat(",", innerStreamOne.proximityWith), "") as proximityWith, innerStreamOne.eventId as eventId +insert into updateStream; + +from innerStreamSeven[innerStreamSeven.inCloseProximity == false AND inAlertTable]#window.length(0) join AlertsTable +on innerStreamSeven.proximityWith == AlertsTable.id +select innerStreamSeven.proximityWith as id, str:replaceAll(AlertsTable.proximityWith, str:concat(",", innerStreamSeven.id), "") as proximityWith, innerStreamSeven.eventId as eventId +insert into updateStream; + +from updateStream +select * +update AlertsTable + on id== AlertsTable.id; + +from updateStream[proximityWith == ""] +delete AlertsTable + on id== AlertsTable.id; + +from objectInitialStream[AlertsTable.id == objectInitialStream.id in AlertsTable] +select id, latitude, longitude, timeStamp, type, speed, heading, eventId, true as inAlertTable +insert into publishStream; + +from objectInitialStream[not(AlertsTable.id == objectInitialStream.id in AlertsTable)] +select id, latitude, longitude, timeStamp, type, speed, heading, eventId, false as inAlertTable +insert into publishStream; + +from publishStream[inAlertTable == true]#window.length(0) join AlertsTable +on publishStream.id== AlertsTable.id +select publishStream.id as id, publishStream.latitude as latitude, publishStream.longitude as longitude, publishStream.timeStamp as timeStamp, publishStream.type as type, publishStream.speed as speed, publishStream.heading as heading, publishStream.eventId as eventId, AlertsTable.proximityWith as proximityInfo +insert into innerStreamTwo; + +from publishStream[inAlertTable == false] +delete ProximityTable on ProximityTable.id==id; + +from publishStream[inAlertTable == false] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , "" as proximityInfo ,"false" as isProximity +insert into dataOutStream; + +from innerStreamTwo[ProximityTable.id == innerStreamTwo.id in ProximityTable] +insert into innerStreamThree; + +from innerStreamThree#window.length(0) join ProximityTable +on innerStreamThree.id == ProximityTable.id +select innerStreamThree.id , innerStreamThree.latitude, innerStreamThree.longitude,innerStreamThree.timeStamp, innerStreamThree.type, innerStreamThree.speed, innerStreamThree.heading ,innerStreamThree.eventId, ProximityTable.timeStamp as storedTime, innerStreamThree.proximityInfo as proximityInfo +insert into innerStreamFour; + +from innerStreamFour[(timeStamp - storedTime) >= $proximityTime] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId ,proximityInfo,"true" as isProximity +insert into dataOutStream; + +from innerStreamFour[(timeStamp - storedTime) < $proximityTime] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , proximityInfo ,"false" as isProximity +insert into dataOutStream; + +from innerStreamTwo[not(ProximityTable.id == innerStreamTwo.id in ProximityTable)] +select innerStreamTwo.id, innerStreamTwo.timeStamp +insert into ProximityTable; + +from innerStreamTwo[not(ProximityTable.id == innerStreamTwo.id in ProximityTable)] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , "" as proximityInfo ,"false" as isProximity +insert into dataOutStream; + +from dataOutStream[isProximity == 'true'] +select id, latitude, longitude, timeStamp, type, speed, heading, eventId,"WARNING" as state,str:concat("Proximity with "," ",proximityInfo) as information +insert into dataOut; + +from dataOutStream[isProximity == 'false'] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId ,"NORMAL" as state,"" as information +insert into dataOut; \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Speed_alert.siddhiql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Speed_alert.siddhiql new file mode 100644 index 0000000000..65dad468d5 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Speed_alert.siddhiql @@ -0,0 +1,20 @@ +/* Enter a unique ExecutionPlan */ +@Plan:name('Geo-ExecutionPlan-Speed---$deviceId_alert') + +/* Enter a unique description for ExecutionPlan */ +-- @Plan:description('ExecutionPlan') + +/* define streams/tables and write queries here ... */ + +@Import('org.wso2.geo.StandardSpatialEvents:1.0.0') +define stream dataIn (id string, latitude double, longitude double, timeStamp long, type string, speed float, heading float, eventId string); + +@Export('org.wso2.geo.ProcessedSpatialEvents:1.0.0') +define stream dataOut (id string, latitude double, longitude double, timeStamp long, type string, speed float, heading float, eventId string, state string, information string); + +from dataIn[speed >= $speedAlertValue and id == "$deviceId"]#geodashboard:subscribe() +select id , latitude, longitude,timeStamp, type ,speed, heading ,eventId , "ALERTED" as state, "This device movement is not normal!!" as information +insert into dataOut; +from dataIn[speed < $speedAlertValue and id == "$deviceId"] +select id , latitude, longitude,timeStamp, type ,speed, heading ,eventId , "NORMAL" as state, "This device movement is normal" as information +insert into dataOut; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Stationery_alert.siddhiql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Stationery_alert.siddhiql new file mode 100644 index 0000000000..46bfbfe2e3 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Stationery_alert.siddhiql @@ -0,0 +1,89 @@ +/* Enter a unique ExecutionPlan */ +@Plan:name('$executionPlanName') + +/* Enter a unique description for ExecutionPlan */ +-- @Plan:description('ExecutionPlan') + +/* define streams/tables and write queries here ... */ + +@Import('org.wso2.geo.StandardSpatialEvents:1.0.0') +define stream dataIn (id string, latitude double, longitude double, timeStamp long, type string ,speed float, heading float, eventId string); + + +@Export('org.wso2.geo.ProcessedSpatialEvents:1.0.0') +define stream dataOut (id string, latitude double, longitude double, timeStamp long, type string ,speed float, heading float, eventId string, state string, information string); + +@IndexBy('id') +define table StationeryTable(id string, timeStamp long); + +@IndexBy('id') +define table AlertsTable(id string, stationary bool); + +from dataIn#geodashboard:subscribe() +select id, latitude, longitude, timeStamp, type, speed, heading, eventId,geo:within(longitude,latitude,"$geoFenceGeoJSON") as isWithin +insert into innerStreamOne; + +from innerStreamOne[isWithin == false] +delete StationeryTable on StationeryTable.id==id; + +from innerStreamOne[isWithin == false] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , "false" as isStationary +insert into dataOutStream; + +from innerStreamOne[isWithin == true]#geo:stationary(id,longitude,latitude, $fluctuationRadius) +select id, latitude, longitude, timeStamp, type, speed, heading, eventId,stationary +insert into innerStreamTwo; + +from innerStreamTwo[innerStreamTwo.stationary == true] +select innerStreamTwo.id, innerStreamTwo.stationary +insert into AlertsTable; + +from innerStreamTwo[innerStreamTwo.stationary == false] +delete AlertsTable on AlertsTable.id==id; + +from innerStreamTwo[innerStreamTwo.stationary == false] +delete StationeryTable on StationeryTable.id==id; + +from innerStreamOne[isWithin == true AND not(AlertsTable.id == innerStreamOne.id in AlertsTable)] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , "false" as isStationary +insert into dataOutStream; + +from innerStreamOne[isWithin == true AND AlertsTable.id == innerStreamOne.id in AlertsTable] +insert into innerStreamThree; + +from innerStreamThree#window.length(0) join AlertsTable +on innerStreamThree.id == AlertsTable.id +select innerStreamThree.id , innerStreamThree.latitude, innerStreamThree.longitude,innerStreamThree.timeStamp, innerStreamThree.type, innerStreamThree.speed, innerStreamThree.heading ,innerStreamThree.eventId +insert into innerStreamFour; + +from innerStreamFour[not(StationeryTable.id == innerStreamFour.id in StationeryTable)] +select innerStreamFour.id, innerStreamFour.timeStamp +insert into StationeryTable; + +from innerStreamOne[isWithin == true AND not(StationeryTable.id == innerStreamOne.id in StationeryTable)] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , "false" as isStationary +insert into dataOutStream; + +from innerStreamOne[isWithin == true AND StationeryTable.id == innerStreamOne.id in StationeryTable] +insert into innerStreamFive; + +from innerStreamFive#window.length(0) join StationeryTable +on innerStreamFive.id == StationeryTable.id +select innerStreamFive.id , innerStreamFive.latitude, innerStreamFive.longitude,innerStreamFive.timeStamp, innerStreamFive.type, innerStreamFive.speed, innerStreamFive.heading ,innerStreamFive.eventId, StationeryTable.timeStamp as storedTime +insert into innerStreamSix; + +from innerStreamSix[(timeStamp - storedTime) >= $stationeryTime] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId ,"true" as isStationary +insert into dataOutStream; + +from innerStreamSix[(timeStamp - storedTime) < $stationeryTime] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId ,"false" as isStationary +insert into dataOutStream; + +from dataOutStream[isStationary == 'true'] +select id ,latitude, longitude,timeStamp, type, speed, heading ,eventId ,"ALERTED" as state, "This device is in $stationeryName area!!!" as information +insert into dataOut; + +from dataOutStream[isStationary == 'false'] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId ,"NORMAL" as state,"" as information +insert into dataOut; \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Traffic_alert.siddhiql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Traffic_alert.siddhiql new file mode 100644 index 0000000000..5e6bb5b1a8 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Traffic_alert.siddhiql @@ -0,0 +1,17 @@ +/* Enter a unique ExecutionPlan */ +@Plan:name('$executionPlanName') + +/* Enter a unique description for ExecutionPlan */ +-- @Plan:description('ExecutionPlan') + +/* define streams/tables and write queries here ... */ + +@Import('rawGeoStream:1.0.0') +define stream dataIn (id string, timeStamp long, geometry string, state string, information string); + +@Export('AlertsNotifications:1.0.0') +define stream dataOut (id string, state string, information string, timeStamp long, latitude double, longitude double); + +from dataIn[geo:intersects(geometry, "$geoFenceGeoJSON")==true and geodashboard:needToNotify(id, str:concat(information, state), "sendFirst") == true and id == $deviceId] +select id, state, str:concat("Traffic alert in $areaName. State: ", state, " ", information) as information, timeStamp, 0.0 as latitude, 0.0 as longitude +insert into dataOut \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Within_alert.siddhiql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Within_alert.siddhiql new file mode 100644 index 0000000000..b58fd59e33 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/resources/alerts/Geo-ExecutionPlan-Within_alert.siddhiql @@ -0,0 +1,20 @@ +/* Enter a unique ExecutionPlan */ +@Plan:name('$executionPlanName') + +/* Enter a unique description for ExecutionPlan */ +-- @Plan:description('ExecutionPlan') + +/* define streams/tables and write queries here ... */ + +@Import('org.wso2.geo.StandardSpatialEvents:1.0.0') +define stream dataIn (id string, latitude double, longitude double, timeStamp long, type string ,speed float, heading float, eventId string); + +@Export('org.wso2.geo.ProcessedSpatialEvents:1.0.0') +define stream dataOut (id string, latitude double, longitude double, timeStamp long, type string ,speed float, heading float, eventId string, state string, information string); + +from dataIn[geo:within(longitude,latitude,"$geoFenceGeoJSON")==true and id == "$deviceId"]#geodashboard:subscribe() +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , "ALERTED" as state, "This device is in $areaName restricted area!!!" as information +insert into dataOut; +from dataIn[geo:within(longitude,latitude,"$geoFenceGeoJSON")!=true and id == "$deviceId"] +select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , "NORMAL" as state, "" as information +insert into dataOut; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java index d425133ce5..d555de0b41 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core; import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; +import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; @@ -77,4 +78,13 @@ public class TestDeviceManagementService implements DeviceManagementService { return null; } + @Override + public PullNotificationSubscriber getPullNotificationSubscriber() { + return null; + } + + @Override + public DeviceStatusTaskPluginConfig getDeviceStatusTaskPluginConfig() { + return null; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index eb06e9adcb..dadee68128 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -1,6 +1,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( ID INT AUTO_INCREMENT NOT NULL, NAME VARCHAR(300) NULL DEFAULT NULL, + DEVICE_TYPE_META VARCHAR(20000) NULL DEFAULT NULL, + LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, PROVIDER_TENANT_ID INTEGER DEFAULT 0, SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (ID) @@ -455,7 +457,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( DEVICE_ID INT NULL, LATITUDE DOUBLE NULL, LONGITUDE DOUBLE NULL, - STREET1 VARCHAR(45) NULL, + STREET1 VARCHAR(255) NULL, STREET2 VARCHAR(45) NULL, CITY VARCHAR(45) NULL, ZIP VARCHAR(10) NULL, 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 f56eb8b89b..752a7e31a1 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 - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml @@ -50,10 +50,6 @@ org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.common - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.core - org.apache.ws.commons.axiom.wso2 axiom @@ -62,10 +58,18 @@ org.wso2.carbon org.wso2.carbon.utils + + org.wso2.carbon + org.wso2.carbon.ndatasource.core + + + org.apache.felix + maven-scr-plugin + org.apache.felix maven-bundle-plugin @@ -77,14 +81,14 @@ ${carbon.device.mgt.version} Device Management Extensions Bundle + !org.wso2.carbon.device.mgt.extensions.internal, org.wso2.carbon.device.mgt.extensions.* org.wso2.carbon.governance.api.*, javax.xml.namespace;resolution:=optional, - org.wso2.carbon.device.mgt.core.*, org.wso2.carbon.context, - org.wso2.carbon.device.mgt.common, + org.wso2.carbon.device.mgt.common.*, org.wso2.carbon.device.mgt.common.license.mgt, org.wso2.carbon.registry.api, org.wso2.carbon.registry.core, @@ -93,8 +97,23 @@ org.wso2.carbon.base, javax.xml.bind, org.apache.commons.logging, - org.wso2.carbon.utils + org.wso2.carbon.utils, + javax.naming, + javax.sql, + javax.xml, + javax.xml.bind.annotation, + javax.xml.parsers;resolution:=optional, + org.apache.commons.lang, + org.osgi.service.component, + org.w3c.dom, + org.wso2.carbon.ndatasource.core, + org.wso2.carbon.registry.core.service, + org.wso2.carbon.utils.dbcreator, + org.wso2.carbon.utils.multitenancy, + org.osgi.framework + org.wso2.carbon.device.mgt.extensions.pull.notification, + org.wso2.carbon.device.mgt.extensions.pull.notification.* diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/DeviceTypeConfigIdentifier.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeConfigIdentifier.java similarity index 95% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/DeviceTypeConfigIdentifier.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeConfigIdentifier.java index a9288dd731..e2c2c02f1e 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/DeviceTypeConfigIdentifier.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeConfigIdentifier.java @@ -15,7 +15,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template; +package org.wso2.carbon.device.mgt.extensions.device.type.template; import java.io.Serializable; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeGeneratorServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeGeneratorServiceImpl.java new file mode 100644 index 0000000000..01bc313095 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeGeneratorServiceImpl.java @@ -0,0 +1,14 @@ +package org.wso2.carbon.device.mgt.extensions.device.type.template; + +import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; +import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService; +import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; + +public class DeviceTypeGeneratorServiceImpl implements DeviceTypeGeneratorService { + + @Override + public DeviceManagementService populateDeviceManagementService(String deviceTypeName + , DeviceTypeMetaDefinition deviceTypeMetaDefinition) { + return new HTTPDeviceTypeManagerService(deviceTypeName, deviceTypeMetaDefinition); + } +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/DeviceTypeManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java similarity index 82% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/DeviceTypeManager.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java index 98c5ef2870..8bf15732a0 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/DeviceTypeManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java @@ -16,10 +16,11 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template; +package org.wso2.carbon.device.mgt.extensions.device.type.template; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; @@ -31,23 +32,25 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.*; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.util.DeviceTypePluginConstants; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.exception.DeviceTypeDeployerFileException; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.exception.DeviceTypeMgtPluginException; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.dao.DeviceDAODefinition; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.dao.DeviceTypePluginDAOManager; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.feature.ConfigurationBasedFeatureManager; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.util.DeviceTypeUtils; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.*; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; +import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceDAODefinition; +import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager; +import org.wso2.carbon.device.mgt.extensions.device.type.template.feature.ConfigurationBasedFeatureManager; +import org.wso2.carbon.device.mgt.extensions.device.type.template.util.DeviceTypePluginConstants; +import org.wso2.carbon.device.mgt.extensions.device.type.template.util.DeviceTypeUtils; import org.wso2.carbon.device.mgt.extensions.license.mgt.registry.RegistryBasedLicenseManager; import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.api.Resource; +import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; +import java.io.File; import java.io.StringReader; import java.io.StringWriter; import java.nio.charset.Charset; @@ -63,10 +66,15 @@ public class DeviceTypeManager implements DeviceManager { private String deviceType; private DeviceTypePluginDAOManager deviceTypePluginDAOManager; private LicenseManager licenseManager; + private PlatformConfiguration defaultPlatformConfiguration; private boolean propertiesExist; private boolean requiredDeviceTypeAuthorization; private boolean claimable; + private static final String PATH_MOBILE_PLUGIN_CONF_DIR = + CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "device-mgt-plugin-configs" + File.separator + + "mobile"; + private FeatureManager featureManager; public DeviceTypeManager(DeviceTypeConfigIdentifier deviceTypeConfigIdentifier, @@ -100,13 +108,21 @@ public class DeviceTypeManager implements DeviceManager { } } catch (LicenseManagementException e) { String msg = "Error occurred while adding default license for " + deviceType + " devices"; - throw new DeviceTypeDeployerFileException(msg, e); + throw new DeviceTypeDeployerPayloadException(msg, e); } claimable = false; if (deviceTypeConfiguration.getClaimable() != null ) { claimable = deviceTypeConfiguration.getClaimable().isEnabled(); } + // Loading default platform configuration + try { + defaultPlatformConfiguration = this.getDefaultConfiguration(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while default platform configuration"; + throw new DeviceTypeDeployerPayloadException(msg, e); + } + DeviceDetails deviceDetails = deviceTypeConfiguration.getDeviceDetails(); if (deviceDetails != null) { @@ -123,7 +139,7 @@ public class DeviceTypeManager implements DeviceManager { } } if (deviceDefinitionTable == null) { - throw new DeviceTypeDeployerFileException("Could not find definition for table: " + tableName); + throw new DeviceTypeDeployerPayloadException("Could not find definition for table: " + tableName); } propertiesExist = true; @@ -150,11 +166,17 @@ public class DeviceTypeManager implements DeviceManager { } deviceTypePluginDAOManager = new DeviceTypePluginDAOManager(datasourceName, deviceDAODefinition); } else { - throw new DeviceTypeDeployerFileException("Invalid datasource name."); + throw new DeviceTypeDeployerPayloadException("Invalid datasource name."); } } finally { PrivilegedCarbonContext.endTenantFlow(); } + } else { + if (deviceDetails.getProperties() != null && deviceDetails.getProperties().getProperty() != null + && deviceDetails.getProperties().getProperty().size() > 0 ) { + deviceTypePluginDAOManager = new DeviceTypePluginDAOManager(deviceType, deviceDetails); + propertiesExist = true; + } } } } @@ -205,6 +227,8 @@ public class DeviceTypeManager implements DeviceManager { return (PlatformConfiguration) unmarshaller.unmarshal( new StringReader(new String((byte[]) resource.getContent(), Charset. forName(DeviceTypePluginConstants.CHARSET_UTF8)))); + } else if (defaultPlatformConfiguration != null) { + return defaultPlatformConfiguration; } return null; } catch (DeviceTypeMgtPluginException e) { @@ -371,6 +395,38 @@ public class DeviceTypeManager implements DeviceManager { return requiredDeviceTypeAuthorization; } + private PlatformConfiguration getDefaultConfiguration() throws DeviceManagementException { + + if (log.isDebugEnabled()) { + log.debug("Loading default " + deviceType + " platform configuration from " + deviceType + + "-default-platform-configuration.xml"); + } + try { + String platformConfigurationPath = + PATH_MOBILE_PLUGIN_CONF_DIR + File.separator + deviceType + "-default-platform-configuration.xml"; + File platformConfig = new File(platformConfigurationPath); + + if (platformConfig.exists()) { + Document doc = DeviceTypeUtils.convertToDocument(platformConfig); + JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class); + Unmarshaller unmarshaller = context.createUnmarshaller(); + return (PlatformConfiguration) unmarshaller.unmarshal(doc); + } else { + log.warn(deviceType + "-default-platform-configuration.xml is not available, hence default " + + deviceType + "platform configuration cannot be loaded."); + } + return null; + } catch (JAXBException e) { + throw new DeviceManagementException( + "Error occurred while parsing the " + deviceType + " default platform configuration : " + e + .getMessage(), e); + } catch (DeviceTypeMgtPluginException e) { + throw new DeviceManagementException( + "Error occurred while parsing the " + deviceType + " default platform configuration : " + e + .getMessage(), e); + } + } + @Override public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException { diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/DeviceTypeManagerService.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java similarity index 61% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/DeviceTypeManagerService.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java index e87d0d330c..9ff760b4c9 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/DeviceTypeManagerService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template; +package org.wso2.carbon.device.mgt.extensions.device.type.template; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -25,18 +25,26 @@ import org.wso2.carbon.device.mgt.common.DeviceManager; import org.wso2.carbon.device.mgt.common.InitialOperationConfig; import org.wso2.carbon.device.mgt.common.MonitoringOperation; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; +import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; import org.wso2.carbon.device.mgt.common.ProvisioningConfig; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; +import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.DeviceTypeConfiguration; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.Property; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.PushNotificationProvider; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.TaskConfiguration; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.policy.mgt.DefaultPolicyMonitoringManager; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.ConfigProperties; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceStatusTaskConfiguration; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Feature; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.PolicyMonitoring; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Property; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.PullNotificationSubscriberConfig; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.PushNotificationProvider; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.TaskConfiguration; +import org.wso2.carbon.device.mgt.extensions.device.type.template.policy.mgt.DefaultPolicyMonitoringManager; +import org.wso2.carbon.device.mgt.extensions.device.type.template.pull.notification.PullNotificationSubscriberLoader; import java.util.ArrayList; import java.util.HashMap; @@ -59,6 +67,8 @@ public class DeviceTypeManagerService implements DeviceManagementService { private List monitoringOperations; private PolicyMonitoringManager policyMonitoringManager; private InitialOperationConfig initialOperationConfig; + private PullNotificationSubscriber pullNotificationSubscriber; + private DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig; public DeviceTypeManagerService(DeviceTypeConfigIdentifier deviceTypeConfigIdentifier, DeviceTypeConfiguration deviceTypeConfiguration) { @@ -70,9 +80,10 @@ public class DeviceTypeManagerService implements DeviceManagementService { this.setOperationMonitoringConfig(deviceTypeConfiguration); this.initialOperationConfig = new InitialOperationConfig(); this.setInitialOperationConfig(deviceTypeConfiguration); - if (deviceTypeConfiguration.getPolicyMonitoring() != null ) { - this.policyMonitoringManager = new DefaultPolicyMonitoringManager(); - } + this.deviceStatusTaskPluginConfig = new DeviceStatusTaskPluginConfig(); + this.setDeviceStatusTaskPluginConfig(deviceTypeConfiguration.getDeviceStatusTaskConfiguration()); + this.setPolicyMonitoringManager(deviceTypeConfiguration.getPolicyMonitoring()); + this.setPullNotificationSubscriber(deviceTypeConfiguration.getPullNotificationSubscriberConfig()); } @Override @@ -113,8 +124,14 @@ public class DeviceTypeManagerService implements DeviceManagementService { if (pushNotificationProvider != null) { if (pushNotificationProvider.isFileBasedProperties()) { Map staticProps = new HashMap<>(); - for (Property property : pushNotificationProvider.getConfigProperties().getProperty()) { - staticProps.put(property.getName(), property.getValue()); + ConfigProperties configProperties = pushNotificationProvider.getConfigProperties(); + if (configProperties != null) { + List properties = configProperties.getProperty(); + if (properties != null && properties.size() > 0) { + for (Property property : properties) { + staticProps.put(property.getName(), property.getValue()); + } + } } pushNotificationConfig = new PushNotificationConfig(pushNotificationProvider.getType(), pushNotificationProvider.isScheduled(), staticProps); @@ -167,6 +184,15 @@ public class DeviceTypeManagerService implements DeviceManagementService { return initialOperationConfig; } + @Override + public PullNotificationSubscriber getPullNotificationSubscriber() { + return pullNotificationSubscriber; + } + + public DeviceStatusTaskPluginConfig getDeviceStatusTaskPluginConfig() { + return deviceStatusTaskPluginConfig; + } + private void setProvisioningConfig(String tenantDomain, DeviceTypeConfiguration deviceTypeConfiguration) { if (deviceTypeConfiguration.getProvisioningConfig() != null) { boolean sharedWithAllTenants = deviceTypeConfiguration.getProvisioningConfig().isSharedWithAllTenants(); @@ -176,11 +202,36 @@ public class DeviceTypeManagerService implements DeviceManagementService { } } + private void setDeviceStatusTaskPluginConfig(DeviceStatusTaskConfiguration deviceStatusTaskConfiguration) { + if (deviceStatusTaskConfiguration != null && deviceStatusTaskConfiguration.isEnabled()) { + deviceStatusTaskPluginConfig.setRequireStatusMonitoring(deviceStatusTaskConfiguration.isEnabled()); + deviceStatusTaskPluginConfig.setIdleTimeToMarkInactive(deviceStatusTaskConfiguration.getIdleTimeToMarkInactive()); + deviceStatusTaskPluginConfig.setIdleTimeToMarkUnreachable(deviceStatusTaskConfiguration.getIdleTimeToMarkUnreachable()); + deviceStatusTaskPluginConfig.setFrequency(deviceStatusTaskConfiguration.getFrequency()); + } + } + protected void setInitialOperationConfig(DeviceTypeConfiguration deviceTypeConfiguration) { if (deviceTypeConfiguration.getOperations() != null) { List ops = deviceTypeConfiguration.getOperations(); - if (ops != null && !ops.isEmpty()) { - initialOperationConfig.setOperations(ops); + if (!ops.isEmpty() && deviceTypeConfiguration.getFeatures() != null + && deviceTypeConfiguration.getFeatures().getFeature() != null) { + List validOps = new ArrayList<>(); + for (String operation : ops) { + boolean isFeatureExist = false; + for (Feature feature : deviceTypeConfiguration.getFeatures().getFeature()) { + if (feature.getCode().equals(operation)) { + isFeatureExist = true; + break; + } + } + if (isFeatureExist) { + validOps.add(operation); + } else { + log.warn("Couldn't fine a valid feature for the operation : " + operation); + } + } + initialOperationConfig.setOperations(validOps); } } } @@ -196,4 +247,21 @@ public class DeviceTypeManagerService implements DeviceManagementService { } return propertMap; } + + private void setPolicyMonitoringManager(PolicyMonitoring policyMonitoring) { + if (policyMonitoring != null && policyMonitoring.isEnabled()) { + this.policyMonitoringManager = new DefaultPolicyMonitoringManager(); + } + } + + private void setPullNotificationSubscriber(PullNotificationSubscriberConfig pullNotificationSubscriberConfig) { + if (pullNotificationSubscriberConfig != null) { + String className = pullNotificationSubscriberConfig.getClassName(); + if (className != null && !className.isEmpty()) { + PullNotificationSubscriberLoader pullNotificationSubscriberLoader = new PullNotificationSubscriberLoader + (className, pullNotificationSubscriberConfig.getConfigProperties()); + this.pullNotificationSubscriber = pullNotificationSubscriberLoader.getPullNotificationSubscriber(); + } + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HTTPDeviceTypeManagerService.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HTTPDeviceTypeManagerService.java new file mode 100644 index 0000000000..8f9f1f4e24 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HTTPDeviceTypeManagerService.java @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2016, 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. + * + */ +package org.wso2.carbon.device.mgt.extensions.device.type.template; + +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.Feature; +import org.wso2.carbon.device.mgt.common.InitialOperationConfig; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; +import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeDefinitionProvider; +import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Claimable; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.ConfigProperties; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceDetails; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Features; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.License; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.PolicyMonitoring; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Properties; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Property; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.ProvisioningConfig; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.PullNotificationSubscriberConfig; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.PushNotificationProvider; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * This inherits the capabiliy that is provided through the file based device type manager service. + * This will create and instance of device management service through a json payload. + */ +public class HTTPDeviceTypeManagerService extends DeviceTypeManagerService implements DeviceTypeDefinitionProvider { + + private DeviceTypeMetaDefinition deviceTypeMetaDefinition; + private static final String DEFAULT_PULL_NOTIFICATION_CLASS_NAME = "org.wso2.carbon.device.mgt.extensions.pull.notification.PullNotificationSubscriberImpl"; + + public HTTPDeviceTypeManagerService(String deviceTypeName, DeviceTypeMetaDefinition deviceTypeMetaDefinition) { + super(getDeviceTypeConfigIdentifier(deviceTypeName), getDeviceTypeConfiguration( + deviceTypeName, deviceTypeMetaDefinition)); + this.deviceTypeMetaDefinition = deviceTypeMetaDefinition; + } + + private static DeviceTypeConfiguration getDeviceTypeConfiguration(String deviceTypeName, DeviceTypeMetaDefinition + deviceTypeMetaDefinition) { + DeviceTypeConfiguration deviceTypeConfiguration = new DeviceTypeConfiguration(); + + if (deviceTypeMetaDefinition != null) { + Claimable claimable = new Claimable(); + claimable.setEnabled(deviceTypeMetaDefinition.isClaimable()); + deviceTypeConfiguration.setClaimable(claimable); + + if (deviceTypeMetaDefinition.getProperties() != null && + deviceTypeMetaDefinition.getProperties().size() > 0) { + DeviceDetails deviceDetails = new DeviceDetails(); + Properties properties = new Properties(); + properties.addProperties(deviceTypeMetaDefinition.getProperties()); + deviceDetails.setProperties(properties); + deviceTypeConfiguration.setDeviceDetails(deviceDetails); + } + if (deviceTypeMetaDefinition.getFeatures() != null && deviceTypeMetaDefinition.getFeatures().size() > 0) { + Features features = new Features(); + List featureList + = new ArrayList<>(); + for (Feature feature : deviceTypeMetaDefinition.getFeatures()) { + org.wso2.carbon.device.mgt.extensions.device.type.template.config.Feature configFeature = new org + .wso2.carbon.device.mgt.extensions.device.type.template.config.Feature(); + if (feature.getCode() != null && feature.getName() != null) { + configFeature.setCode(feature.getCode()); + configFeature.setDescription(feature.getDescription()); + configFeature.setName(feature.getName()); + if (feature.getMetadataEntries() != null && feature.getMetadataEntries().size() > 0) { + List metaValues = new ArrayList<>(); + for (Feature.MetadataEntry metadataEntry : feature.getMetadataEntries()) { + metaValues.add(metadataEntry.getValue().toString()); + } + configFeature.setMetaData(metaValues); + } + featureList.add(configFeature); + } + } + features.addFeatures(featureList); + deviceTypeConfiguration.setFeatures(features); + } + + deviceTypeConfiguration.setName(deviceTypeName); + //TODO: Add it to the license management service. +// if (deviceTypeMetaDefinition.getLicense() != null) { +// License license = new License(); +// license.setLanguage(deviceTypeMetaDefinition.getLicense().getLanguage()); +// license.setText(deviceTypeMetaDefinition.getLicense().getText()); +// license.setVersion(deviceTypeMetaDefinition.getLicense().getVersion()); +// deviceTypeConfiguration.setLicense(license); +// } + PolicyMonitoring policyMonitoring = new PolicyMonitoring(); + policyMonitoring.setEnabled(deviceTypeMetaDefinition.isPolicyMonitoringEnabled()); + deviceTypeConfiguration.setPolicyMonitoring(policyMonitoring); + + ProvisioningConfig provisioningConfig = new ProvisioningConfig(); + provisioningConfig.setSharedWithAllTenants(false); + deviceTypeConfiguration.setProvisioningConfig(provisioningConfig); + + PushNotificationConfig pushNotificationConfig = deviceTypeMetaDefinition.getPushNotificationConfig(); + if (pushNotificationConfig != null) { + PushNotificationProvider pushNotificationProvider = new PushNotificationProvider(); + pushNotificationProvider.setType(pushNotificationConfig.getType()); + //default schedule value will be true. + pushNotificationProvider.setScheduled(true); + if (pushNotificationConfig.getProperties() != null && + pushNotificationConfig.getProperties().size() > 0) { + ConfigProperties configProperties = new ConfigProperties(); + List properties = new ArrayList<>(); + for (Map.Entry entry : pushNotificationConfig.getProperties().entrySet()) { + Property property = new Property(); + property.setName(entry.getKey()); + property.setValue(entry.getValue()); + properties.add(property); + } + configProperties.addProperties(properties); + pushNotificationProvider.setConfigProperties(configProperties); + } + pushNotificationProvider.setFileBasedProperties(true); + deviceTypeConfiguration.setPushNotificationProvider(pushNotificationProvider); + } + +// This is commented until the task registration handling issue is solved +// OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceTypeMetaDefinition.getTaskConfig(); +// if (operationMonitoringTaskConfig != null) { +// TaskConfiguration taskConfiguration = new TaskConfiguration(); +// taskConfiguration.setEnabled(operationMonitoringTaskConfig.isEnabled()); +// taskConfiguration.setFrequency(operationMonitoringTaskConfig.getFrequency()); +// if (operationMonitoringTaskConfig.getMonitoringOperation() != null) { +// List operations = new ArrayList<>(); +// for (MonitoringOperation monitoringOperation : operationMonitoringTaskConfig +// .getMonitoringOperation()) { +// TaskConfiguration.Operation operation = new TaskConfiguration.Operation(); +// operation.setOperationName(monitoringOperation.getTaskName()); +// operation.setRecurrency(monitoringOperation.getRecurrentTimes()); +// operations.add(operation); +// } +// taskConfiguration.setOperations(operations); +// } +// deviceTypeConfiguration.setTaskConfiguration(taskConfiguration); +// } + + if (deviceTypeMetaDefinition.getInitialOperationConfig() != null) { + InitialOperationConfig initialOperationConfig = deviceTypeMetaDefinition.getInitialOperationConfig(); + deviceTypeConfiguration.setOperations(initialOperationConfig.getOperations()); + } + } + PullNotificationSubscriberConfig pullNotificationSubscriber = new PullNotificationSubscriberConfig(); + pullNotificationSubscriber.setClassName(DEFAULT_PULL_NOTIFICATION_CLASS_NAME); + deviceTypeConfiguration.setPullNotificationSubscriberConfig(pullNotificationSubscriber); + return deviceTypeConfiguration; + } + + private static DeviceTypeConfigIdentifier getDeviceTypeConfigIdentifier(String deviceType) { + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + return new DeviceTypeConfigIdentifier(deviceType, tenantDomain); + } + + @Override + public DeviceTypeMetaDefinition getDeviceTypeMetaDefinition() { + return deviceTypeMetaDefinition; + } +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Attributes.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Attributes.java similarity index 97% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Attributes.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Attributes.java index c52b1419de..43d84bfd3f 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Attributes.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Attributes.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Claimable.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Claimable.java similarity index 97% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Claimable.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Claimable.java index 661778e62d..fdd3039597 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Claimable.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Claimable.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/ConfigProperties.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/ConfigProperties.java similarity index 93% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/ConfigProperties.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/ConfigProperties.java index 1280d8165c..8df38ca0e5 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/ConfigProperties.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/ConfigProperties.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import java.util.ArrayList; import java.util.List; @@ -83,4 +83,8 @@ public class ConfigProperties { return this.property; } + public void addProperties(List property) { + this.property = property; + } + } diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/DataSource.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DataSource.java similarity index 97% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/DataSource.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DataSource.java index f416facc4a..4e5cc80f81 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/DataSource.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DataSource.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/DeviceAuthorizationConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceAuthorizationConfig.java similarity index 96% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/DeviceAuthorizationConfig.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceAuthorizationConfig.java index 833719ba2a..9d8cf1162f 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/DeviceAuthorizationConfig.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceAuthorizationConfig.java @@ -17,7 +17,7 @@ * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/DeviceDetails.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceDetails.java similarity index 79% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/DeviceDetails.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceDetails.java index 6428bf097f..b25c93f51a 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/DeviceDetails.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceDetails.java @@ -16,13 +16,13 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlValue; /** @@ -44,61 +44,61 @@ import javax.xml.bind.annotation.XmlValue; */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DeviceDetails", propOrder = { - "value" + "properties" }) public class DeviceDetails { - @XmlValue - protected String value; @XmlAttribute(name = "table-id") protected String tableId; + @XmlElement(name = "Properties", required = true) + protected Properties properties; /** - * Gets the value of the value property. + * Gets the value of the tableId property. * * @return * possible object is * {@link String } * */ - public String getValue() { - return value; + public String getTableId() { + return tableId; } /** - * Sets the value of the value property. + * Sets the value of the tableId property. * * @param value * allowed object is * {@link String } * */ - public void setValue(String value) { - this.value = value; + public void setTableId(String value) { + this.tableId = value; } /** - * Gets the value of the tableId property. - * + * Gets the value of the properties property. + * * @return * possible object is - * {@link String } - * + * {@link Properties } + * */ - public String getTableId() { - return tableId; + public Properties getProperties() { + return properties; } /** - * Sets the value of the tableId property. - * + * Sets the value of the properties property. + * * @param value * allowed object is - * {@link String } - * + * {@link Properties } + * */ - public void setTableId(String value) { - this.tableId = value; + public void setProperties(Properties value) { + this.properties = value; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceStatusTaskConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceStatusTaskConfiguration.java new file mode 100644 index 0000000000..588bd4a1ec --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceStatusTaskConfiguration.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "DeviceStatusTaskConfig") +public class DeviceStatusTaskConfiguration { + + private boolean enabled; + private int frequency; + private int idleTimeToMarkInactive; + private int idleTimeToMarkUnreachable; + + @XmlElement(name = "RequireStatusMonitoring", required = true) + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + @XmlElement(name = "Frequency", required = true) + public int getFrequency() { + return frequency; + } + + public void setFrequency(int frequency) { + this.frequency = frequency; + } + + @XmlElement(name = "IdleTimeToMarkInactive", required = true) + public int getIdleTimeToMarkInactive() { + return idleTimeToMarkInactive; + } + + public void setIdleTimeToMarkInactive(int idleTimeToMarkInactive) { + this.idleTimeToMarkInactive = idleTimeToMarkInactive; + } + + @XmlElement(name = "IdleTimeToMarkUnreachable", required = true) + public int getIdleTimeToMarkUnreachable() { + return idleTimeToMarkUnreachable; + } + + public void setIdleTimeToMarkUnreachable(int idleTimeToMarkUnreachable) { + this.idleTimeToMarkUnreachable = idleTimeToMarkUnreachable; + } +} \ No newline at end of file diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/DeviceTypeConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java similarity index 78% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/DeviceTypeConfiguration.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java index 00d20b4ebe..46f442e89d 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/DeviceTypeConfiguration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java @@ -16,9 +16,14 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; - -import javax.xml.bind.annotation.*; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlAccessType; import java.util.List; @@ -35,11 +40,12 @@ import java.util.List; * <element name="DeviceDetails" type="{}DeviceDetails"/> * <element name="Features" type="{}Features"/> * <element name="ProvisioningConfig" type="{}ProvisioningConfig"/> - * <element name="PushNotificationProvider" type="{}PushNotificationProvider"/> + * <element name="PushNotificationProviderConfig" type="{}PushNotificationProviderConfig"/> * <element name="License" type="{}License"/> * <element name="DataSource" type="{}DataSource"/> * <element name="PolicyMonitoring" type="{}PolicyMonitoring"/> * <element name="DeviceAuthorizationConfig" type="{}DeviceAuthorizationConfig"/> + * <element name="DeviceStatusTaskConfig" type="{}DeviceStatusTaskConfig"/> * </sequence> * <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> @@ -59,14 +65,18 @@ public class DeviceTypeConfiguration { protected Features features; @XmlElement(name = "ProvisioningConfig", required = true) protected ProvisioningConfig provisioningConfig; - @XmlElement(name = "PushNotificationProvider", required = true) + @XmlElement(name = "PushNotificationProviderConfig", required = true) protected PushNotificationProvider pushNotificationProvider; + @XmlElement(name = "PullNotificationSubscriberConfig", required = true) + protected PullNotificationSubscriberConfig pullNotificationSubscriberConfig; @XmlElement(name = "License", required = true) protected License license; @XmlElement(name = "DataSource", required = true) protected DataSource dataSource; @XmlElement(name = "TaskConfiguration", required = true) private TaskConfiguration taskConfiguration; + @XmlElement(name = "DeviceStatusTaskConfig") + private DeviceStatusTaskConfiguration deviceStatusTaskConfiguration; @XmlElement(name = "DeviceAuthorizationConfig", required = true) protected DeviceAuthorizationConfig deviceAuthorizationConfig; @XmlAttribute(name = "name") @@ -85,9 +95,29 @@ public class DeviceTypeConfiguration { this.operations = operations; } + /** + * Gets the value of the deviceStatusTaskConfiguration property. + * + * @return + * possible object is + * {@link DeviceStatusTaskConfiguration } + * + */ + public DeviceStatusTaskConfiguration getDeviceStatusTaskConfiguration() { + return deviceStatusTaskConfiguration; + } - - + /** + * Sets the value of the deviceStatusTaskConfiguration property. + * + * @param deviceStatusTaskConfiguration + * allowed object is + * {@link DeviceStatusTaskConfiguration } + * + */ + public void setDeviceStatusTaskConfiguration(DeviceStatusTaskConfiguration deviceStatusTaskConfiguration) { + this.deviceStatusTaskConfiguration = deviceStatusTaskConfiguration; + } /** * Gets the value of the taskConfiguration property. @@ -170,7 +200,7 @@ public class DeviceTypeConfiguration { * @param value allowed object is * {@link DeviceDetails } */ - public void setDeviceDetails(PolicyMonitoring value) { + public void setPolicyMonitoring(PolicyMonitoring value) { this.policyMonitoring = value; } @@ -234,6 +264,26 @@ public class DeviceTypeConfiguration { this.pushNotificationProvider = value; } + /** + * Gets the value of the PullNotificationSubscriberConfig property. + * + * @return possible object is + * {@link PullNotificationSubscriberConfig } + */ + public PullNotificationSubscriberConfig getPullNotificationSubscriberConfig() { + return pullNotificationSubscriberConfig; + } + + /** + * Sets the value of the PullNotificationSubscriberConfig property. + * + * @param value allowed object is + * {@link PullNotificationSubscriberConfig } + */ + public void setPullNotificationSubscriberConfig(PullNotificationSubscriberConfig value) { + this.pullNotificationSubscriberConfig = value; + } + /** * Gets the value of the license property. * @@ -313,5 +363,4 @@ public class DeviceTypeConfiguration { public void setDeviceAuthorizationConfig(DeviceAuthorizationConfig value) { this.deviceAuthorizationConfig = value; } - } diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Feature.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Feature.java similarity index 89% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Feature.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Feature.java index 0fd247cddc..800c4ff71f 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Feature.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Feature.java @@ -16,13 +16,15 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlType; +import java.util.List; /** @@ -51,7 +53,7 @@ import javax.xml.bind.annotation.XmlType; @XmlType(name = "Feature", propOrder = { "name", "description", - "operation" + "operation", "metaData" }) public class Feature { @@ -63,6 +65,9 @@ public class Feature { protected Operation operation; @XmlAttribute(name = "code") protected String code; + @XmlElementWrapper(name = "MetaData") + @XmlElement(name = "Property", required = true) + protected List metaData; /** * Gets the value of the name property. @@ -160,4 +165,11 @@ public class Feature { this.code = value; } + public List getMetaData() { + return metaData; + } + + public void setMetaData(List metaData) { + this.metaData = metaData; + } } diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Features.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Features.java similarity index 92% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Features.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Features.java index 7e00b18688..1904cac3ed 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Features.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Features.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -69,4 +69,8 @@ public class Features { return this.feature; } + public void addFeatures(List features) { + this.feature = features; + } + } diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/FormParameters.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/FormParameters.java similarity index 96% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/FormParameters.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/FormParameters.java index 6cdda89299..3cacabb3e4 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/FormParameters.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/FormParameters.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/InitialOperationConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/InitialOperationConfig.java similarity index 93% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/InitialOperationConfig.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/InitialOperationConfig.java index e172d7b009..cb45a1b212 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/InitialOperationConfig.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/InitialOperationConfig.java @@ -1,4 +1,4 @@ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.*; import java.util.List; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/JndiConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/JndiConfig.java similarity index 96% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/JndiConfig.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/JndiConfig.java index d28201d8a0..a07a3af080 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/JndiConfig.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/JndiConfig.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/License.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/License.java similarity index 97% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/License.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/License.java index 24d2feefc5..771f9f0574 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/License.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/License.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Operation.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Operation.java similarity index 98% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Operation.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Operation.java index 0a954c242d..06fe5cf1be 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Operation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Operation.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/PolicyMonitoring.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/PolicyMonitoring.java similarity index 97% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/PolicyMonitoring.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/PolicyMonitoring.java index 12947c161e..251c598666 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/PolicyMonitoring.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/PolicyMonitoring.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Properties.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Properties.java new file mode 100644 index 0000000000..287ccf4352 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Properties.java @@ -0,0 +1,80 @@ + +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; + +import java.util.ArrayList; +import java.util.List; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for Properties complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="Properties">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="Property" maxOccurs="unbounded" minOccurs="0">
+ *           <simpleType>
+ *             <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *               <enumeration value="attr1"/>
+ *               <enumeration value="attr2"/>
+ *             </restriction>
+ *           </simpleType>
+ *         </element>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "Properties", propOrder = { + "property" +}) +public class Properties { + + @XmlElement(name = "Property") + protected List property; + + /** + * Gets the value of the property property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the property property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getProperty().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * + */ + public List getProperty() { + if (property == null) { + property = new ArrayList(); + } + return this.property; + } + + public void addProperties(List property) { + this.property = property; + } + +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Property.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Property.java similarity index 97% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Property.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Property.java index 82408f3d18..e79037451c 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Property.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Property.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/ProvisioningConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/ProvisioningConfig.java similarity index 96% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/ProvisioningConfig.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/ProvisioningConfig.java index e6caf2f562..d54f698296 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/ProvisioningConfig.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/ProvisioningConfig.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/PullNotificationSubscriberConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/PullNotificationSubscriberConfig.java new file mode 100644 index 0000000000..e18896f4e4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/PullNotificationSubscriberConfig.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2017, 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. + * + */ +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for PullNotificationSubscriberConfig complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="PullNotificationSubscriberConfig">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="ConfigProperties" type="{}ConfigProperties"/>
+ *       </sequence>
+ *       <attribute name="type" type="{http://www.w3.org/2001/XMLSchema}string" />
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "PullNotificationSubscriberConfig", propOrder = { + "configProperties" +}) +public class PullNotificationSubscriberConfig { + @XmlElement(name = "ConfigProperties", required = true) + protected ConfigProperties configProperties; + @XmlAttribute(name = "className") + protected String className; + + /** + * Gets the value of the configProperties property. + * + * @return + * possible object is + * {@link ConfigProperties } + * + */ + public ConfigProperties getConfigProperties() { + return configProperties; + } + + /** + * Sets the value of the configProperties property. + * + * @param value + * allowed object is + * {@link ConfigProperties } + * + */ + public void setConfigProperties(ConfigProperties value) { + this.configProperties = value; + } + + /** + * Gets the value of the type property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getClassName() { + return className; + } + + /** + * Sets the value of the type property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setClassName(String value) { + this.className = value; + } + +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/PushNotificationProvider.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/PushNotificationProvider.java similarity index 98% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/PushNotificationProvider.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/PushNotificationProvider.java index 59e6e68b7b..2c6e4ca257 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/PushNotificationProvider.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/PushNotificationProvider.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/QueryParameters.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/QueryParameters.java similarity index 96% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/QueryParameters.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/QueryParameters.java index 0f37d49651..e79826134e 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/QueryParameters.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/QueryParameters.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Table.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Table.java similarity index 97% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Table.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Table.java index 9cb5a926b3..6338f22142 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/Table.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Table.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/TableConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/TableConfig.java similarity index 97% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/TableConfig.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/TableConfig.java index 4d912e2dd1..908046c649 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/TableConfig.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/TableConfig.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/TaskConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/TaskConfiguration.java similarity index 96% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/TaskConfiguration.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/TaskConfiguration.java index 6de303e557..fd31754a83 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/TaskConfiguration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/TaskConfiguration.java @@ -17,7 +17,7 @@ * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/exception/DeviceTypeConfigurationException.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/exception/DeviceTypeConfigurationException.java similarity index 94% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/exception/DeviceTypeConfigurationException.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/exception/DeviceTypeConfigurationException.java index 70378fad0f..d044e7ebeb 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/exception/DeviceTypeConfigurationException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/exception/DeviceTypeConfigurationException.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.exception; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config.exception; public class DeviceTypeConfigurationException extends Exception { diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/exception/InvalidConfigurationStateException.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/exception/InvalidConfigurationStateException.java similarity index 94% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/exception/InvalidConfigurationStateException.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/exception/InvalidConfigurationStateException.java index c3d7887b7d..3d39345327 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/config/exception/InvalidConfigurationStateException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/exception/InvalidConfigurationStateException.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.exception; +package org.wso2.carbon.device.mgt.extensions.device.type.template.config.exception; public class InvalidConfigurationStateException extends RuntimeException { diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/dao/DeviceDAODefinition.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceDAODefinition.java similarity index 74% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/dao/DeviceDAODefinition.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceDAODefinition.java index 4df77a9a2c..d8f77a64a6 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/dao/DeviceDAODefinition.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceDAODefinition.java @@ -16,10 +16,10 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.dao; +package org.wso2.carbon.device.mgt.extensions.device.type.template.dao; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.Table; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.exception.DeviceTypeDeployerFileException; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Table; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException; import java.util.ArrayList; import java.util.List; @@ -45,19 +45,19 @@ public class DeviceDAODefinition { primarykey = table.getPrimaryKey(); List attributes = table.getAttributes().getAttribute(); if (deviceTableName == null || deviceTableName.isEmpty()) { - throw new DeviceTypeDeployerFileException("Missing deviceTableName"); + throw new DeviceTypeDeployerPayloadException("Missing deviceTableName"); } if (primarykey == null || primarykey.isEmpty()) { - throw new DeviceTypeDeployerFileException("Missing primaryKey "); + throw new DeviceTypeDeployerPayloadException("Missing primaryKey "); } if (attributes == null || attributes.size() == 0) { - throw new DeviceTypeDeployerFileException("Missing Attributes "); + throw new DeviceTypeDeployerPayloadException("Missing Attributes "); } for (String attribute : attributes) { if (attribute.isEmpty()) { - throw new DeviceTypeDeployerFileException("Unsupported attribute format for device definition"); + throw new DeviceTypeDeployerPayloadException("Unsupported attribute format for device definition"); } columnNames.add(attribute); } diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/dao/DeviceTypeDAOHandler.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceTypeDAOHandler.java similarity index 89% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/dao/DeviceTypeDAOHandler.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceTypeDAOHandler.java index ce3f90c7ea..e31149fafe 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/dao/DeviceTypeDAOHandler.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceTypeDAOHandler.java @@ -1,9 +1,9 @@ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.dao; +package org.wso2.carbon.device.mgt.extensions.device.type.template.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.exception.DeviceTypeDeployerFileException; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.exception.DeviceTypeMgtPluginException; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; import javax.naming.Context; import javax.naming.InitialContext; @@ -31,7 +31,7 @@ public class DeviceTypeDAOHandler { Context ctx = new InitialContext(); dataSource = (DataSource) ctx.lookup(datasourceName); } catch (NamingException e) { - throw new DeviceTypeDeployerFileException("Error while looking up the data source: " + datasourceName, e); + throw new DeviceTypeDeployerPayloadException("Error while looking up the data source: " + datasourceName, e); } } diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/dao/DeviceTypePluginDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOImpl.java similarity index 93% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/dao/DeviceTypePluginDAO.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOImpl.java index 163ac64711..a8f9141904 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/dao/DeviceTypePluginDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOImpl.java @@ -16,14 +16,14 @@ * under the License. */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.dao; +package org.wso2.carbon.device.mgt.extensions.device.type.template.dao; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.exception.DeviceTypeMgtPluginException; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.util.DeviceTypeUtils; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; +import org.wso2.carbon.device.mgt.extensions.device.type.template.util.DeviceTypeUtils; import java.sql.Connection; import java.sql.PreparedStatement; @@ -36,9 +36,9 @@ import java.util.List; * Implements CRUD for Devices. This holds the generic implementation. An instance of this will be created for * each device type. */ -public class DeviceTypePluginDAO { +public class DeviceTypePluginDAOImpl implements PluginDAO { - private static final Log log = LogFactory.getLog(DeviceTypePluginDAO.class); + private static final Log log = LogFactory.getLog(DeviceTypePluginDAOImpl.class); private DeviceTypeDAOHandler deviceTypeDAOHandler; private DeviceDAODefinition deviceDAODefinition; private String selectDBQueryForGetDevice; @@ -47,8 +47,8 @@ public class DeviceTypePluginDAO { private String deleteDBQueryToRemoveDevicd; private String selectDBQueryToGetAllDevice; - public DeviceTypePluginDAO(DeviceDAODefinition deviceDAODefinition, - DeviceTypeDAOHandler deviceTypeDAOHandler) { + public DeviceTypePluginDAOImpl(DeviceDAODefinition deviceDAODefinition, + DeviceTypeDAOHandler deviceTypeDAOHandler) { this.deviceTypeDAOHandler = deviceTypeDAOHandler; this.deviceDAODefinition = deviceDAODefinition; initializeDbQueries(); @@ -241,9 +241,11 @@ public class DeviceTypePluginDAO { } private String getPropertString(List properties, String propertyName) { - for (Device.Property property : properties) { - if (property.getName() != null && property.getName().equals(propertyName)) { - return property.getValue(); + if (properties != null) { + for (Device.Property property : properties) { + if (property.getName() != null && property.getName().equals(propertyName)) { + return property.getValue(); + } } } return null; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOManager.java new file mode 100644 index 0000000000..6a4f0e0126 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOManager.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016, 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. + * + */ + +package org.wso2.carbon.device.mgt.extensions.device.type.template.dao; + +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceDetails; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; + +public class DeviceTypePluginDAOManager { + + private PluginDAO deviceTypePluginDAO; + private DeviceTypeDAOHandler deviceTypeDAOHandler; + private static final String DEFAULT_DATASOURCE_NAME = "jdbc/DM_DS"; + + public DeviceTypePluginDAOManager(String datasourceName, DeviceDAODefinition deviceDAODefinition) { + deviceTypeDAOHandler = new DeviceTypeDAOHandler(datasourceName); + deviceTypePluginDAO = new DeviceTypePluginDAOImpl(deviceDAODefinition, deviceTypeDAOHandler); + } + + public DeviceTypePluginDAOManager(String deviceType, DeviceDetails deviceDetails) { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext() + .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); + try { + deviceTypeDAOHandler = new DeviceTypeDAOHandler(DEFAULT_DATASOURCE_NAME); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + deviceTypePluginDAO = new PropertyBasedPluginDAOImpl(deviceDetails, deviceTypeDAOHandler, deviceType); + } + + public PluginDAO getDeviceDAO() { + return deviceTypePluginDAO; + } + + public DeviceTypeDAOHandler getDeviceTypeDAOHandler() { + return deviceTypeDAOHandler; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/PluginDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/PluginDAO.java new file mode 100644 index 0000000000..2ffd37f8f4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/PluginDAO.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2017, 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. + */ + +package org.wso2.carbon.device.mgt.extensions.device.type.template.dao; + +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; +import java.util.List; + +public interface PluginDAO { + + Device getDevice(String deviceId) throws DeviceTypeMgtPluginException; + + boolean addDevice(Device device) throws DeviceTypeMgtPluginException; + + boolean updateDevice(Device device) throws DeviceTypeMgtPluginException; + + boolean deleteDevice(String deviceId) throws DeviceTypeMgtPluginException; + + List getAllDevices() throws DeviceTypeMgtPluginException; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/PropertyBasedPluginDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/PropertyBasedPluginDAOImpl.java new file mode 100644 index 0000000000..227c352a82 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/PropertyBasedPluginDAOImpl.java @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2015, 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. + */ + +package org.wso2.carbon.device.mgt.extensions.device.type.template.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceDetails; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; +import org.wso2.carbon.device.mgt.extensions.device.type.template.util.DeviceTypeUtils; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Implements CRUD for Devices. This holds the generic implementation. An instance of this will be created for + * each device type. + */ +public class PropertyBasedPluginDAOImpl implements PluginDAO { + + private static final Log log = LogFactory.getLog(PropertyBasedPluginDAOImpl.class); + private DeviceTypeDAOHandler deviceTypeDAOHandler; + private List deviceProps; + private String deviceType; + private static final String PROPERTY_KEY_COLUMN_NAME = "PROPERTY_NAME"; + private static final String PROPERTY_VALUE_COLUMN_NAME = "PROPERTY_VALUE"; + + public PropertyBasedPluginDAOImpl(DeviceDetails deviceDetails, + DeviceTypeDAOHandler deviceTypeDAOHandler, String deviceType) { + this.deviceTypeDAOHandler = deviceTypeDAOHandler; + this.deviceProps = deviceDetails.getProperties().getProperty(); + this.deviceType = deviceType; + } + + public Device getDevice(String deviceId) throws DeviceTypeMgtPluginException { + Connection conn = null; + PreparedStatement stmt = null; + Device device = null; + ResultSet resultSet = null; + try { + conn = deviceTypeDAOHandler.getConnection(); + stmt = conn.prepareStatement( + "SELECT * FROM DM_DEVICE_PROPERTIES WHERE DEVICE_TYPE_NAME = ? AND DEVICE_IDENTIFICATION = ? " + + "AND TENANT_ID = ?"); + stmt.setString(1, deviceType); + stmt.setString(2, deviceId); + stmt.setInt(3, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true)); + resultSet = stmt.executeQuery(); + List properties = new ArrayList<>(); + while (resultSet.next()) { + Device.Property property = new Device.Property(); + property.setName(resultSet.getString(PROPERTY_KEY_COLUMN_NAME)); + property.setValue(resultSet.getString(PROPERTY_VALUE_COLUMN_NAME)); + properties.add(property); + } + if (properties.size() > 0) { + device = new Device(); + device.setDeviceIdentifier(deviceId); + device.setType(deviceType); + device.setProperties(properties); + } + } catch (SQLException e) { + String msg = "Error occurred while fetching device : '" + deviceId + "' type " + deviceType; + log.error(msg, e); + throw new DeviceTypeMgtPluginException(msg, e); + } finally { + DeviceTypeUtils.cleanupResources(stmt, resultSet); + deviceTypeDAOHandler.closeConnection(); + } + + return device; + } + + public boolean addDevice(Device device) throws DeviceTypeMgtPluginException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = deviceTypeDAOHandler.getConnection(); + stmt = conn.prepareStatement( + "INSERT INTO DM_DEVICE_PROPERTIES(DEVICE_TYPE_NAME, DEVICE_IDENTIFICATION, PROPERTY_NAME, " + + "PROPERTY_VALUE, TENANT_ID) VALUES (?, ?, ?, ?, ?)"); + for (String propertyKey : deviceProps) { + stmt.setString(1, deviceType); + stmt.setString(2, device.getDeviceIdentifier()); + stmt.setString(3, propertyKey); + stmt.setString(4, getPropertyValue(device.getProperties(), propertyKey)); + stmt.setInt(5, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true)); + stmt.addBatch(); + } + stmt.executeBatch(); + status = true; + } catch (SQLException e) { + String msg = "Error occurred while adding the device '" + + device.getDeviceIdentifier() + "' to the type " + deviceType + " db."; + log.error(msg, e); + throw new DeviceTypeMgtPluginException(msg, e); + } finally { + DeviceTypeUtils.cleanupResources(stmt, null); + } + return status; + } + + public boolean updateDevice(Device device) throws DeviceTypeMgtPluginException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = deviceTypeDAOHandler.getConnection(); + stmt = conn.prepareStatement( + "UPDATE DM_DEVICE_PROPERTIES SET PROPERTY_VALUE = ? WHERE DEVICE_TYPE_NAME = ? AND " + + "DEVICE_IDENTIFICATION = ? AND PROPERTY_NAME = ? AND TENANT_ID= ?"); + + for (Device.Property property : device.getProperties()) { + if (!deviceProps.contains(property.getName())) { + continue; + } + stmt.setString(1, property.getValue()); + stmt.setString(1, deviceType); + stmt.setString(2, device.getDeviceIdentifier()); + stmt.setString(3, property.getName()); + stmt.setInt(4, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true)); + stmt.addBatch(); + } + stmt.executeBatch(); + return true; + } catch (SQLException e) { + String msg = "Error occurred while modifying the device '" + + device.getDeviceIdentifier() + "' data on" + deviceType; + log.error(msg, e); + throw new DeviceTypeMgtPluginException(msg, e); + } finally { + DeviceTypeUtils.cleanupResources(stmt, null); + } + } + + public boolean deleteDevice(String deviceId) throws DeviceTypeMgtPluginException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = deviceTypeDAOHandler.getConnection(); + stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_PROPERTIES WHERE DEVICE_TYPE_NAME = ? " + + "AND DEVICE_IDENTIFICATION = ? AND TENANT_ID = ?"); + stmt.setString(1, deviceType); + stmt.setString(2, deviceId); + stmt.setInt(3, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true)); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("device " + deviceId + " data has deleted from the " + + deviceType + " table."); + } + } + } catch (SQLException e) { + String msg = + "Error occurred while deleting " + deviceType + " device " + deviceId; + log.error(msg, e); + throw new DeviceTypeMgtPluginException(msg, e); + } finally { + DeviceTypeUtils.cleanupResources(stmt, null); + } + return status; + } + + public List getAllDevices() throws DeviceTypeMgtPluginException { + Connection conn; + PreparedStatement stmt = null; + ResultSet resultSet = null; + Map deviceMap = new HashMap<>(); + try { + conn = deviceTypeDAOHandler.getConnection(); + stmt = conn.prepareStatement("SELECT DEVICE_IDENTIFICATION, PROPERTY_NAME, PROPERTY_VALUE FROM " + + "DM_DEVICE_PROPERTIES WHERE DEVICE_TYPE_NAME = ? AND TENANT_ID = ?"); + stmt.setString(1, deviceType); + stmt.setInt(2, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true)); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + String deviceId = resultSet.getString("DEVICE_IDENTIFICATION"); + Device deviceInMap = deviceMap.get(deviceId); + if (deviceInMap == null) { + deviceInMap = new Device(); + deviceInMap.setDeviceIdentifier(deviceId); + deviceInMap.setType(deviceType); + List properties = new ArrayList<>(); + deviceInMap.setProperties(properties); + deviceMap.put(deviceId, deviceInMap); + } + Device.Property prop = new Device.Property(); + prop.setName(resultSet.getString(PROPERTY_KEY_COLUMN_NAME)); + prop.setName(resultSet.getString(PROPERTY_VALUE_COLUMN_NAME)); + deviceInMap.getProperties().add(prop); + } + if (log.isDebugEnabled()) { + log.debug( + "All device details have fetched from " + deviceType + " table."); + } + return Arrays.asList((Device[])deviceMap.values().toArray()); + } catch (SQLException e) { + String msg = + "Error occurred while fetching all " + deviceType + " device data'"; + log.error(msg, e); + throw new DeviceTypeMgtPluginException(msg, e); + } finally { + DeviceTypeUtils.cleanupResources(stmt, resultSet); + deviceTypeDAOHandler.closeConnection(); + } + } + + private String getPropertyValue(List properties, String propertyName) { + for (Device.Property property : properties) { + if (property.getName() != null && property.getName().equals(propertyName)) { + return property.getValue(); + } + } + return null; + } + +} \ No newline at end of file diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/exception/DeviceTypeDeployerFileException.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/exception/DeviceTypeDeployerPayloadException.java similarity index 65% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/exception/DeviceTypeDeployerFileException.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/exception/DeviceTypeDeployerPayloadException.java index 23b1f06c8b..b25547950e 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/exception/DeviceTypeDeployerFileException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/exception/DeviceTypeDeployerPayloadException.java @@ -15,30 +15,30 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.exception; +package org.wso2.carbon.device.mgt.extensions.device.type.template.exception; /** * This exception will be thrown if there are any issues with the content of the deployer. */ -public class DeviceTypeDeployerFileException extends RuntimeException { +public class DeviceTypeDeployerPayloadException extends RuntimeException { - public DeviceTypeDeployerFileException(String msg, Exception nestedEx) { + public DeviceTypeDeployerPayloadException(String msg, Exception nestedEx) { super(msg, nestedEx); } - public DeviceTypeDeployerFileException(String message, Throwable cause) { + public DeviceTypeDeployerPayloadException(String message, Throwable cause) { super(message, cause); } - public DeviceTypeDeployerFileException(String msg) { + public DeviceTypeDeployerPayloadException(String msg) { super(msg); } - public DeviceTypeDeployerFileException() { + public DeviceTypeDeployerPayloadException() { super(); } - public DeviceTypeDeployerFileException(Throwable cause) { + public DeviceTypeDeployerPayloadException(Throwable cause) { super(cause); } diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/exception/DeviceTypeMgtPluginException.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/exception/DeviceTypeMgtPluginException.java similarity index 94% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/exception/DeviceTypeMgtPluginException.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/exception/DeviceTypeMgtPluginException.java index f5a73dafbb..b1548eb65f 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/exception/DeviceTypeMgtPluginException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/exception/DeviceTypeMgtPluginException.java @@ -15,7 +15,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.exception; +package org.wso2.carbon.device.mgt.extensions.device.type.template.exception; /** * This exception will be thrown when there is an issues with the plugin generation. diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/feature/ConfigurationBasedFeatureManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/feature/ConfigurationBasedFeatureManager.java similarity index 82% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/feature/ConfigurationBasedFeatureManager.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/feature/ConfigurationBasedFeatureManager.java index 5d689fec5c..091123ab7d 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/feature/ConfigurationBasedFeatureManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/feature/ConfigurationBasedFeatureManager.java @@ -16,14 +16,13 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.feature; +package org.wso2.carbon.device.mgt.extensions.device.type.template.feature; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.FeatureManager; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.Operation; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Operation; -import javax.ws.rs.HttpMethod; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -45,13 +44,25 @@ public class ConfigurationBasedFeatureManager implements FeatureManager { private static final Pattern PATH_PARAM_REGEX = Pattern.compile("\\{(.*?)\\}"); public ConfigurationBasedFeatureManager( - List features) { - for (org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.Feature feature : features) { + List features) { + for (org.wso2.carbon.device.mgt.extensions.device.type.template.config.Feature feature : features) { Feature deviceFeature = new Feature(); deviceFeature.setCode(feature.getCode()); deviceFeature.setName(feature.getName()); deviceFeature.setDescription(feature.getDescription()); Operation operation = feature.getOperation(); + List metadataEntries = null; + if (feature.getMetaData() != null) { + metadataEntries = new ArrayList<>(); + int id = 0; + for (String metaData : feature.getMetaData()) { + Feature.MetadataEntry metadataEntry = new Feature.MetadataEntry(); + metadataEntry.setId(id); + metadataEntry.setValue(metaData); + metadataEntries.add(metadataEntry); + id++; + } + } if (operation != null) { Map apiParams = new HashMap<>(); apiParams.put(METHOD, operation.getMethod().toUpperCase()); @@ -70,7 +81,9 @@ public class ConfigurationBasedFeatureManager implements FeatureManager { formParams = operation.getFormParameters().getParameter(); } apiParams.put(FORM_PARAMS, formParams); - List metadataEntries = new ArrayList<>(); + if (metadataEntries == null) { + metadataEntries = new ArrayList<>(); + } Feature.MetadataEntry metadataEntry = new Feature.MetadataEntry(); metadataEntry.setId(-1); metadataEntry.setValue(apiParams); diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/policy/mgt/DefaultPolicyMonitoringManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java similarity index 84% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/policy/mgt/DefaultPolicyMonitoringManager.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java index 634482db4e..3486446343 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/policy/mgt/DefaultPolicyMonitoringManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java @@ -16,27 +16,19 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.policy.mgt; +package org.wso2.carbon.device.mgt.extensions.device.type.template.policy.mgt; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.Feature; -import org.wso2.carbon.device.mgt.common.FeatureManager; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.Operation; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; /** * This implementation policy monitoring manager. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/pull/notification/PullNotificationSubscriberLoader.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/pull/notification/PullNotificationSubscriberLoader.java new file mode 100644 index 0000000000..bdbe2d7d49 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/pull/notification/PullNotificationSubscriberLoader.java @@ -0,0 +1,43 @@ +package org.wso2.carbon.device.mgt.extensions.device.type.template.pull.notification; + +import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.ConfigProperties; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Property; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException; + +import java.util.HashMap; +import java.util.Map; + +/** + * This creates an instance of the pull notification executor strategy with the given class name. + * makes sure the class name starts with the package prefix org.wso2.carbon.device.mgt.pull.notification.* + */ +public class PullNotificationSubscriberLoader { + + private PullNotificationSubscriber pullNotificationSubscriber; + + public PullNotificationSubscriberLoader(String className, ConfigProperties configProperties) { + try { + Class pullNotificationExecutorClass + = Class.forName(className).asSubclass(PullNotificationSubscriber.class); + Map properties = new HashMap<>(); + if (configProperties != null) { + for (Property property : configProperties.getProperty()) { + properties.put(property.getName(), property.getValue()); + } + } + pullNotificationSubscriber = pullNotificationExecutorClass.newInstance(); + pullNotificationSubscriber.init(properties); + } catch (ClassNotFoundException e) { + throw new DeviceTypeDeployerPayloadException("Unable to find the class pull notification executor: " + className, e); + } catch (InstantiationException e) { + throw new DeviceTypeDeployerPayloadException("Unable to create an instance of :" + className, e); + } catch (IllegalAccessException e) { + throw new DeviceTypeDeployerPayloadException("Access of the instance in not allowed.", e); + } + } + + public PullNotificationSubscriber getPullNotificationSubscriber() { + return pullNotificationSubscriber; + } +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/util/DeviceSchemaInitializer.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceSchemaInitializer.java similarity index 96% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/util/DeviceSchemaInitializer.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceSchemaInitializer.java index c436fd544b..daf5722da8 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/util/DeviceSchemaInitializer.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceSchemaInitializer.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.util; +package org.wso2.carbon.device.mgt.extensions.device.type.template.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypePluginConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypePluginConstants.java new file mode 100644 index 0000000000..4ac7c2292c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypePluginConstants.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2016, 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. + * + */ +package org.wso2.carbon.device.mgt.extensions.device.type.template.util; + +/** + * This holds the constants used for this bundle. + */ +public class DeviceTypePluginConstants { + public static final String MEDIA_TYPE_XML = "application/xml"; + public static final String CHARSET_UTF8 = "UTF8"; + public static final String LANGUAGE_CODE_ENGLISH_US = "en_US"; +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/util/DeviceTypeUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypeUtils.java similarity index 81% rename from components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/util/DeviceTypeUtils.java rename to components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypeUtils.java index 466b3edcfe..d409d22b38 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/template/util/DeviceTypeUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypeUtils.java @@ -16,13 +16,14 @@ * under the License. */ -package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.util; +package org.wso2.carbon.device.mgt.extensions.device.type.template.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.exception.DeviceTypeMgtPluginException; -import org.wso2.carbon.device.mgt.extensions.device.type.deployer.internal.DeviceTypeManagementDataHolder; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; +import org.wso2.carbon.device.mgt.extensions.internal.DeviceTypeExtensionDataHolder; import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.registry.core.Registry; @@ -30,6 +31,10 @@ import org.wso2.carbon.registry.core.Registry; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -96,7 +101,7 @@ public class DeviceTypeUtils { public static Registry getConfigurationRegistry() throws DeviceTypeMgtPluginException { try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - return DeviceTypeManagementDataHolder.getInstance().getRegistryService() + return DeviceTypeExtensionDataHolder.getInstance().getRegistryService() .getConfigSystemRegistry(tenantId); } catch (RegistryException e) { throw new DeviceTypeMgtPluginException("Error in retrieving conf registry instance: " + e.getMessage(), e); @@ -128,4 +133,18 @@ public class DeviceTypeUtils { } } + public static Document convertToDocument(File file) throws DeviceTypeMgtPluginException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + try { + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + return docBuilder.parse(file); + } catch (Exception e) { + throw new DeviceTypeMgtPluginException("Error occurred while parsing file '" + file.getName() + "' to" + + " a org.w3c.dom.Document", e); + } + } + + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionDataHolder.java new file mode 100644 index 0000000000..69ac6b5d97 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionDataHolder.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2015, 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. + * + */ +package org.wso2.carbon.device.mgt.extensions.internal; + +import org.wso2.carbon.registry.core.service.RegistryService; + +/** + * This holds the necessary services required for the bundle. + */ +public class DeviceTypeExtensionDataHolder { + + private RegistryService registryService; + + private static DeviceTypeExtensionDataHolder thisInstance = new DeviceTypeExtensionDataHolder(); + + private DeviceTypeExtensionDataHolder() {} + + public static DeviceTypeExtensionDataHolder getInstance() { + return thisInstance; + } + + public RegistryService getRegistryService() { + return registryService; + } + + public void setRegistryService(RegistryService registryService) { + this.registryService = registryService; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java new file mode 100644 index 0000000000..180e9717e3 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2016, 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. + */ + +package org.wso2.carbon.device.mgt.extensions.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService; +import org.wso2.carbon.device.mgt.extensions.device.type.template.DeviceTypeGeneratorServiceImpl; +import org.wso2.carbon.ndatasource.core.DataSourceService; +import org.wso2.carbon.registry.core.service.RegistryService; + +/** + * @scr.component name="org.wso2.carbon.device.mgt.extensions.DeviceTypeExtensionServiceComponent" + * immediate="true" + * @scr.reference name="registry.service" + * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="0..1" + * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService" + * @scr.reference name="org.wso2.carbon.ndatasource" + * interface="org.wso2.carbon.ndatasource.core.DataSourceService" + * cardinality="1..1" + * policy="dynamic" + * bind="setDataSourceService" + * unbind="unsetDataSourceService" + */ +public class DeviceTypeExtensionServiceComponent { + + private static final Log log = LogFactory.getLog(DeviceTypeExtensionServiceComponent.class); + + protected void activate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("Activating DeviceType Deployer Service Component"); + } + ctx.getBundleContext().registerService(DeviceTypeGeneratorService.class, new DeviceTypeGeneratorServiceImpl() + , null); + } + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating DeviceType Deployer Service Component"); + } + } + + protected void setRegistryService(RegistryService registryService) { + if (log.isDebugEnabled()) { + log.debug("RegistryService acquired"); + } + DeviceTypeExtensionDataHolder.getInstance().setRegistryService(registryService); + } + + protected void unsetRegistryService(RegistryService registryService) { + DeviceTypeExtensionDataHolder.getInstance().setRegistryService(null); + } + + protected void setDataSourceService(DataSourceService dataSourceService) { + /* This is to avoid device management component getting initialized before the underlying datasources + are registered */ + if (log.isDebugEnabled()) { + log.debug("Data source service set to android mobile service component"); + } + } + + protected void unsetDataSourceService(DataSourceService dataSourceService) { + //do nothing + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/sample.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/sample.xml new file mode 100644 index 0000000000..96e6fecc46 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/sample.xml @@ -0,0 +1,168 @@ + + + + + + + + + + + attr1 + attr2 + + + + + + + abc + this is a feature + + + deviceId + + + test + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + false + + + + true + + + + true + + + sample.mqtt.adapter + tcp://localhost:1883 + admin + admin + 0 + + true + + + + + + admin + + + + + + + en_US + 1.0.0 + This is license text + + + + true + 600000 + + + DEVICE_INFO + 1 + + + APPLICATION_LIST + 5 + + + DEVICE_LOCATION + 1 + + + + + + + jdbc/SampleDM_DB + + + + SAMPLE_DEVICE_ID + + column1 + column2 + +
+
+
+ + + + DEVICE_INFO + APPLICATION_LIST + DEVICE_LOCATION + + + + + + false + 300 + 600 + 300 + + +
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml index 1277e14efd..35e6a27dc5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 2.0.63-SNAPSHOT + 3.0.46-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag index 3e4c75a337..df5d11d01b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag @@ -167,6 +167,19 @@ if (!user) { }else { response.sendError(403); } + } else if (uriMatcher.match("/{context}/api/devices/agent/{type}/{deviceId}/config")) { + elements = uriMatcher.elements(); + deviceId = elements.deviceId; + type = elements.type; + operation = elements.operation; + if (userModule.isAuthorized("/permission/admin/device-mgt/devices/owning-device")) { + result = deviceModule.getDeviceAgentConfig(type, deviceId); + if (!result) { + response.sendError(500); + } + } else { + response.sendError(403); + } } else if (uriMatcher.match("{context}/api/devices/{type}/{deviceId}/{operation}")) { elements = uriMatcher.elements(); deviceId = elements.deviceId; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/stats-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/stats-api.jag new file mode 100644 index 0000000000..6919a492a3 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/stats-api.jag @@ -0,0 +1,77 @@ +<% +/* + * Copyright (c) 2015, 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. + */ + +var uri = request.getRequestURI(); +var uriMatcher = new URIMatcher(String(uri)); + +var log = new Log("api/stats-api.jag"); + +var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; + +if (uriMatcher.match("/{context}/api/stats/paginate")) { + var deviceType = request.getParameter("deviceType"); + var deviceId = request.getParameter("deviceId"); + var from = request.getParameter("from"); + var to = request.getParameter("to"); + var index = request.getParameter("start"); + var length = request.getParameter("length"); + var keys = request.getParameter("attributes"); + keys = JSON.parse(keys); + var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/events/" + + deviceType + "/" + deviceId + "?offset=" + index +"&limit=" + length + "&from="+ from + "&to=" + to; + serviceInvokers.XMLHttp.get( + restAPIEndpoint, + function (restAPIResponse) { + if (restAPIResponse["status"] == 200 && restAPIResponse["responseText"]) { + var responsePayload = parse(restAPIResponse["responseText"]); + + var paginatedResult = {}; + paginatedResult["recordsTotal"] = responsePayload["count"]; + paginatedResult["recordsFiltered"] = responsePayload["count"]; + var records = responsePayload["records"]; + var dataSet = []; + for (var i = 0; i < records.length; i++){ + var record = records[i]; + var timestamp = record["timestamp"]; + var dataRow = []; + dataRow.push(timestamp); + for (var j = 0; j < keys.length; j++) { + var key = keys[j]; + dataRow.push(record.values[key]); + } + //dataSet.push(dataRow); + dataSet.push(dataRow); + } + paginatedResult["data"] = dataSet; + response["status"] = restAPIResponse["status"]; + response["content"] = paginatedResult; + } else { + response["status"] = 204; + var paginatedResult = {}; + var dataSet = []; + paginatedResult["recordsTotal"] = 0; + paginatedResult["recordsFiltered"] = 0; + paginatedResult["data"] = dataSet; + response["content"] = paginatedResult; + } + } + ); +} +%> \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/app-conf.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/app-conf.json index 58a741db8c..a81f661c99 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/app-conf.json +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/app-conf.json @@ -1,5 +1,5 @@ { - "appName": "WSO2 Device Cloud", + "appName": "WSO2 IoT Server", "cachingEnabled": false, "debuggingEnabled": false, "permissionRoot": "/", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json index 5caf20f31f..55d73af4f6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json @@ -1,8 +1,9 @@ { "appContext": "/devicemgt/", "isCloud": false, + "isDeviceOwnerEnabled": false, "httpsURL": "https://%iot.gateway.host%:%iot.gateway.https.port%", - "httpURL": "http://%iot.gateway.host%:%iot.gateway.http.port", + "httpURL": "http://%iot.gateway.host%:%iot.gateway.http.port%", "wssURL": "https://%iot.analytics.host%:%iot.analytics.https.port%", "portalURL": "https://%iot.analytics.host%:%iot.analytics.https.port%", "dashboardServerURL": "%https.ip%", @@ -142,41 +143,14 @@ "perm:admin:certificates:view", "perm:admin:certificates:add", "perm:admin:certificates:verify", - "perm:ios:enroll", - "perm:ios:view-device", - "perm:ios:apn", - "perm:ios:ldap", - "perm:ios:enterprise-app", - "perm:ios:store-application", - "perm:ios:remove-application", - "perm:ios:app-list", - "perm:ios:profile-list", - "perm:ios:lock", - "perm:ios:enterprise-wipe", - "perm:ios:device-info", - "perm:ios:restriction", - "perm:ios:email", - "perm:ios:cellular", - "perm:ios:applications", - "perm:ios:wifi", - "perm:ios:ring", - "perm:ios:location", - "perm:ios:notification", - "perm:ios:airplay", - "perm:ios:caldav", - "perm:ios:cal-subscription", - "perm:ios:passcode-policy", - "perm:ios:webclip", - "perm:ios:vpn", - "perm:ios:per-app-vpn", - "perm:ios:app-to-per-app-vpn", - "perm:ios:app-lock", - "perm:ios:clear-passcode", - "perm:ios:remove-profile", - "perm:ios:get-restrictions", - "perm:ios:wipe-data", "perm:admin", - "perm:devicetype:deployment" + "perm:devicetype:deployment", + "perm:device-types:events", + "perm:device-types:events:view", + "perm:admin:device-type", + "perm:device:enroll", + "perm:geo-service:analytics-view", + "perm:geo-service:alerts-manage" ], "isOAuthEnabled": true, "backendRestEndpoints": { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/toplink-menu.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/toplink-menu.json index 94966cc9f4..aaac58445a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/toplink-menu.json +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/toplink-menu.json @@ -1,112 +1,138 @@ { - "Logo": { - "name": "Cloud", - "url": "https://cloudmgt.cloud.wso2.com/cloudmgt", - "target": "_parent" - }, - "Main": { - "Domain": { - "url": "#", - "icon": "fw fw-organization", - "isAdminOnly": false, - "target": "_parent", - "dropDown": { - "Organization": { - "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/organization.jag", - "icon": "fw fw-organization", - "dropDown": "false", - "target": "_self" + "Logo": { + "name": "Cloud", + "url": "https://cloudmgt.cloud.wso2.com/cloudmgt", + "target": "_parent" + }, + "Main": { + "Domain": { + "url": "#", + "icon": "fw fw-organization", + "isAdminOnly": false, + "target": "_parent", + "dropDown": { + "Organization": { + "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/organization.jag", + "icon": "fw fw-organization", + "dropDown": "false", + "target": "_self" + }, + "Members": { + "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/user.jag", + "icon": "fa fa-users", + "dropDown": "false", + "target": "_self" + } + } + }, + "Account": { + "url": "#", + "icon": "fw fw-resource", + "isAdminOnly": false, + "billingEnabled": true, + "billingApi": { + "username": "admin", + "password": "admin" + }, + "cloudMgtHost" : "https://cloudmgt.cloudstaging.wso2.com", + "cloudMgtIndexPage": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/index.jag", + "dropDown": { + "Upgrade Now": { + "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/payment-plans.jag?cloud-type=device_cloud", + "icon": "fw fw-export", + "dropDown": "true", + "target": "_self" + }, + "Request Extension": { + "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/contact-us.jag?cloud-type=device_cloud&request-extension=true", + "icon": "fa fa-mail", + "dropDown": "true", + "target": "_self" + } + } + }, + "Support": { + "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/contact-us.jag?cloud-type=device_cloud", + "icon": "fw fw-mail", + "isAdminOnly": false, + "target": "_self", + "dropDown": "false" }, - "Members": { - "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/user.jag", - "icon": "fa fa-users", - "dropDown": "false", - "target": "_self" + "Documentation": { + "url": "#", + "icon": "fw fw-document", + "isAdminOnly": false, + "dropDown": { + "Device Cloud": { + "id": "device_cloud", + "url": "https://docs.wso2.com/display/DeviceCloud/WSO2+Device+Cloud+Documentation", + "icon": "fw fw-mobile", + "target": "_blank" + } + } } - } }, - "Support": { - "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/contact-us.jag", - "icon": "fw fw-mail", - "isAdminOnly": false, - "target": "_self", - "dropDown": "false" - }, - "Documentation": { - "url": "#", - "icon": "fw fw-document", - "isAdminOnly": false, - "dropDown": { - "Device Cloud": { - "id": "device_cloud", - "url": "https://docs.wso2.com/display/DeviceCloud/WSO2+Device+Cloud+Documentation", - "icon": "fw fw-mobile", - "target": "_self" - } - } - } - }, - "User": { - "url": "#", - "icon": "fw fw-user", - "dropDown": { - "Profile": { - "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/user-profile.jag", + "User": { + "url": "#", "icon": "fw fw-user", - "dropDown": "true", - "target": "_self" - }, - "Change Password": { - "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/change-password.jag", - "icon": "fw fw-lock", - "dropDown": "true", - "target": "_self" - }, - "Logout": { - "url": "https://api.cloud.wso2.com/publisher/site/pages/logout.jag", - "icon": "fw fw-sign-out", - "dropDown": "true", - "target": "_self" - } - } - }, - "Expand": { - "Clouds": { - "API Cloud": { - "id": "api_cloud", - "url": "https://api.cloud.wso2.com/publisher", - "icon": "fw fw-api fw-3x", - "dropDown": "true", - "target": "_self" - }, - "Integration Cloud": { - "id": "integration_cloud", - "url": "https://integration.cloud.wso2.com/appmgt", - "icon": "fw fw-service fw-3x", - "dropDown": "true", - "target": "_self" - }, - "Identity Cloud": { - "id": "integration_cloud", - "url": "https://identity.cloud.wso2.com/admin", - "icon": "fw fw-security fw-3x", - "dropDown": "true", - "target": "_self" - } + "dropDown": { + "Profile": { + "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/user-profile.jag", + "icon": "fw fw-user", + "dropDown": "true", + "target": "_self" + }, + "Change Password": { + "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/change-password.jag", + "icon": "fw fw-lock", + "dropDown": "true", + "target": "_self" + }, + "Logout": { + "url": "https://device.cloud.wso2.com/devicemgt/logout", + "icon": "fw fw-sign-out", + "dropDown": "true", + "target": "_self" + } + } }, - "Actions": { - "Organization": { - "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/organization.jag", - "icon": "fw fw-organization fw-3x", - "dropDown": "true", - "target": "_self" - }, - "Members": { - "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/user.jag", - "icon": "fa fa-users fa-3x", - "dropDown": "true", - "target": "_self" - } + "Expand": { + "Clouds": { + "API Cloud": { + "id": "api_cloud", + "url": "https://api.cloud.wso2.com/publisher", + "icon": "fw fw-api fw-3x", + "dropDown": "true", + "target": "_self" + }, + "Integration Cloud": { + "id": "integration_cloud", + "url": "https://integration.cloud.wso2.com/appmgt", + "icon": "fw fw-service fw-3x", + "dropDown": "true", + "target": "_self" + }, + "Identity Cloud": { + "id": "integration_cloud", + "url": "https://identity.cloud.wso2.com/admin", + "icon": "fw fw-security fw-3x", + "dropDown": "true", + "target": "_self" + } + }, + "Actions": { + "Organization": { + "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/organization.jag", + "icon": "fw fw-organization fw-3x", + "dropDown": "true", + "target": "_self" + }, + "Members": { + "url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/user.jag", + "icon": "fa fa-users fa-3x", + "dropDown": "true", + "target": "_self" + } + } } - } -} +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js index 0138c57897..5cca9bd307 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js @@ -25,7 +25,8 @@ deviceModule = function () { var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var batchProvider = require("/app/modules/batch-provider-api.js")["batchProviders"]; - + var process = require("process"); + var carbon = require("carbon"); var publicMethods = {}; var privateMethods = {}; @@ -66,38 +67,30 @@ deviceModule = function () { var carbonUser = session.get(constants["USER_SESSION_KEY"]); if (!carbonUser) { log.error("User object was not found in the session"); - throw constants["ERRORS"]["USER_NOT_FOUND"]; + userModule.logout(function () { + response.sendRedirect(devicemgtProps["appContext"] + "login"); + }); } var userName = carbonUser.username + "@" + carbonUser.domain; - - var locationDataSet = []; - switch (deviceType) { - case 'android': - locationDataSet = batchProvider.getData(userName, deviceId, deviceType); - break; - case 'android_sense': - locationDataSet = batchProvider.getData(userName, deviceId, deviceType); - break; - - } - var locationData = []; - var locationTimeData = []; - if (locationDataSet != null) { - - for (var i = 0; i < locationDataSet.length; i++) { - var gpsReading = {}; - var gpsReadingTimes = {}; - gpsReading.lat = locationDataSet[i].latitude; - gpsReading.lng = locationDataSet[i].longitude; - if (deviceType == "android") { - gpsReadingTimes.time = locationDataSet[i].timeStamp; - } else { - gpsReadingTimes.time = locationDataSet[i].meta_timestamp; - } - locationData.push(gpsReading); - locationTimeData.push(gpsReadingTimes); + var locationHistory = []; + var geoServicesEnabled = devicemgtProps.serverConfig.geoLocationConfiguration.isEnabled; + if (geoServicesEnabled) { + try { + var fromDate = new Date(); + fromDate.setHours(fromDate.getHours() - 2); + var toDate = new Date(); + var serviceUrl = devicemgtProps["httpsURL"] + '/api/device-mgt/v1.0/geo-services/stats/' + deviceType + '/' + deviceId + '?from=' + fromDate + '&to=' + toDate; + serviceInvokers.XMLHttp.get(serviceUrl, + function (backendResponse) { + if (backendResponse.status === 200 && backendResponse.responseText) { + locationHistory = JSON.parse(backendResponse.responseText); + } + }); + } catch (e) { + log.error(e.message, e); } } + var locationInfo = {}; try { var url = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0/devices/" + deviceType + "/" + deviceId + "/location"; @@ -110,14 +103,12 @@ deviceModule = function () { locationInfo.latitude = device.latitude; locationInfo.longitude = device.longitude; locationInfo.updatedOn = device.updatedTime; - } }); } catch (e) { log.error(e.message, e); } - var utility = require('/app/modules/utility.js')["utility"]; try { utility.startTenantFlow(carbonUser); @@ -192,27 +183,45 @@ deviceModule = function () { } } } + if (device["deviceInfo"]) { filteredDeviceData["latestDeviceInfo"] = device["deviceInfo"]; + } else { + filteredDeviceData["latestDeviceInfo"] = {}; + filteredDeviceData["latestDeviceInfo"]["location"] = {}; + } - //location related verification and modifications - // adding the location histry for the movement path. - var locationHistory = {}; - locationHistory.locations = locationData; - locationHistory.times = locationTimeData; - filteredDeviceData["locationHistory"] = locationHistory; + //location related verification and modifications + // adding the location histry for the movement path. + filteredDeviceData["locationHistory"] = locationHistory; - //checking for the latest location information. - if (filteredDeviceData.latestDeviceInfo.location && locationInfo) { - var infoDate = new Date(filteredDeviceData.latestDeviceInfo.location.updatedTime); - var locationDate = new Date(locationInfo.updatedOn); - if (infoDate < locationDate) { - filteredDeviceData.latestDeviceInfo.location.longitude = locationInfo.longitude; - filteredDeviceData.latestDeviceInfo.location.latitude = locationInfo.latitude; - } + //checking for the latest location information based on historical data. + if (locationHistory) { + var infoDate; + var locationDate; + var historicalLatestLoc = locationHistory[locationHistory.length - 1]; + if (historicalLatestLoc && filteredDeviceData.latestDeviceInfo && filteredDeviceData.latestDeviceInfo.location) { + infoDate = new Date(filteredDeviceData.latestDeviceInfo.location.updatedTime); + locationDate = new Date(historicalLatestLoc.values.timeStamp); + } + if (infoDate < locationDate || filteredDeviceData.latestDeviceInfo.length === 0) { + filteredDeviceData.latestDeviceInfo.location = {}; + filteredDeviceData.latestDeviceInfo.location.longitude = historicalLatestLoc.values.longitude; + filteredDeviceData.latestDeviceInfo.location.latitude = historicalLatestLoc.values.latitude; + filteredDeviceData.latestDeviceInfo.location.updatedTime = historicalLatestLoc.values.timeStamp; } } + //checking for the latest location information. + if (filteredDeviceData.latestDeviceInfo.location && locationInfo) { + var infoDate = new Date(filteredDeviceData.latestDeviceInfo.location.updatedTime); + var locationDate = new Date(locationInfo.updatedOn); + if (infoDate < locationDate) { + filteredDeviceData.latestDeviceInfo.location.longitude = locationInfo.longitude; + filteredDeviceData.latestDeviceInfo.location.latitude = locationInfo.latitude; + filteredDeviceData.latestDeviceInfo.location.updatedTime = locationInfo.updatedOn; + } + } response["content"] = filteredDeviceData; response["status"] = "success"; @@ -245,16 +254,22 @@ deviceModule = function () { var url; if (uiPermissions.LIST_DEVICES) { url = devicemgtProps["httpsURL"] + - devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/devices?offset=0&limit=1"; + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/devices?offset=0&limit=1"; } else if (uiPermissions.LIST_OWN_DEVICES) { url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + - "/devices?offset=0&limit=1&user=" + carbonUser.username; + "/devices?offset=0&limit=1&user=" + carbonUser.username; } else { log.error("Access denied for user: " + carbonUser.username); return -1; } return serviceInvokers.XMLHttp.get( url, function (responsePayload) { + if(!responsePayload["responseText"]){ + log.error("Error while fetching device count. API `" + url + "` returns HTTP: " + responsePayload["status"]); + userModule.logout(function () { + response.sendRedirect(devicemgtProps["appContext"] + "login"); + }); + } return parse(responsePayload["responseText"])["count"]; }, function (responsePayload) { @@ -264,10 +279,42 @@ deviceModule = function () { ); } else { log.error("User object was not found in the session"); - throw constants["ERRORS"]["USER_NOT_FOUND"]; + userModule.logout(function () { + response.sendRedirect(devicemgtProps["appContext"] + "login"); + }); } }; + publicMethods.getDeviceTypeCount = function () { + var carbonUser = session.get(constants.USER_SESSION_KEY); + if (carbonUser) { + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; + var uiPermissions = userModule.getUIPermissions(); + var url; + if (uiPermissions.LIST_OWN_DEVICES) { + url = devicemgtProps["httpsURL"] + + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/device-types"; + } else { + log.error("Access denied for user: " + carbonUser.username); + return -1; + } + return serviceInvokers.XMLHttp.get( + url, function (responsePayload) { + return parse(responsePayload["responseText"])["count"]; + }, + function (responsePayload) { + log.error(responsePayload["responseText"]); + return -1; + } + ); + } else { + log.error("User object was not found in the session"); + userModule.logout(function () { + response.sendRedirect(devicemgtProps["appContext"] + "login"); + }); + } + }; + publicMethods.getDeviceTypes = function () { var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/device-types"; var response = privateMethods.callBackend(url, constants["HTTP_GET"]); @@ -277,6 +324,15 @@ deviceModule = function () { return response; }; + publicMethods.getDeviceTypesConfig = function () { + var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/device-types/config"; + var response = privateMethods.callBackend(url, constants["HTTP_GET"]); + if (response.status == "success") { + response.content = parse(response.content); + } + return response; + }; + /* @Updated */ @@ -302,6 +358,9 @@ deviceModule = function () { publicMethods.getDevices = function (userName) { var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/devices"; + if (userName && userName !== "") { + url = url + "?user=" + userName; + } return serviceInvokers.XMLHttp.get( url, function (responsePayload) { var devices = JSON.parse(responsePayload.responseText).devices; @@ -316,5 +375,66 @@ deviceModule = function () { } ); }; + + publicMethods.getDeviceAgentConfig = function (type, deviceId) { + var carbonUser = session.get(constants["USER_SESSION_KEY"]); + if (!carbonUser) { + log.error("User object was not found in the session"); + userModule.logout(function () { + response.sendRedirect(devicemgtProps["appContext"] + "login"); + }); + } + var userName = carbonUser.username + "@" + carbonUser.domain; + var config = {}; + config.type = type; + config.deviceId = deviceId; + // register a tenant based app at API Manager + var applicationName = type.replace(" ", "") + "_" + carbonUser.domain; + var requestURL = (devicemgtProps["oauthProvider"]["appRegistration"] + ["apiManagerClientAppRegistrationServiceURL"]).replace("/tenants",""); + var payload = {applicationName:applicationName, tags:["device_agent"], + isAllowedToAllDomains:false, validityPeriod: 3600}; + + serviceInvokers.XMLHttp.post( + requestURL, payload, function (responsePayload) { + var app = JSON.parse(responsePayload.responseText); + + config.clientId = app["client_id"]; + config.clientSecret = app["client_secret"]; + if (config.clientId && config.clientSecret) { + var JWTClientManagerServicePackagePath = + "org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService"; + //noinspection JSUnresolvedFunction, JSUnresolvedVariable + var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath); + //noinspection JSUnresolvedFunction + var jwtClient = JWTClientManagerService.getJWTClient(); + // returning access token by JWT grant type + var deviceScope = "device_" + type.replace(" ", "") + "_" + deviceId + " perm:device:enroll " + + "perm:device:disenroll perm:device:modify perm:devices:operations perm:device:publish-event"; + var tokenInfo = jwtClient.getAccessToken(config.clientId, config.clientSecret, + userName, deviceScope); + config.accessToken = tokenInfo.getAccessToken(); + config.refreshToken = tokenInfo.getRefreshToken(); + if (config.accessToken == null) { + return null; + } + config.mqttGateway = "tcp://" + process.getProperty("mqtt.broker.host") + ":" + process.getProperty("mqtt.broker.port"); + config.httpsGateway = "https://" + process.getProperty("iot.gateway.host") + ":" + process.getProperty("iot.gateway.https.port"); + config.httpGateway = "http://" + process.getProperty("iot.gateway.host") + ":" + process.getProperty("iot.gateway.http.port"); + return config; + } else { + return null; + } + return config; + }, + function (responsePayload) { + log.error(responsePayload); + return null; + } + ); + return config; + + }; + return publicMethods; }(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js index 82ecb1ae3d..348251622f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js @@ -41,7 +41,9 @@ var groupModule = {}; } else { if (!user) { log.error("User object was not found in the session"); - throw constants["ERRORS"]["USER_NOT_FOUND"]; + userModule.logout(function () { + response.sendRedirect(devicemgtProps["appContext"] + "login"); + }); } log.error("Access denied for user: " + user.username); return -1; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js index 666b1b571d..1d18e05fe9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js @@ -79,13 +79,22 @@ var operationModule = function () { return featuresList; }; - publicMethods.getControlOperations = function (deviceType) { + publicMethods.getControlOperations = function (device) { + var deviceType = device.type; var operations = privateMethods.getOperationsFromFeatures(deviceType, "operation"); var features = utility.getDeviceTypeConfig(deviceType).deviceType.features; for (var op in operations) { var iconIdentifier = operations[op].operation; if (features && features[iconIdentifier]) { var icon = features[iconIdentifier].icon; + //TODO: need improve this check to get feature availability from agent side + var filter = features[iconIdentifier].filter; + if (device && filter && filter.property && device[filter.property] !== filter.value) { + operations[op]["isDisabled"] = true; + operations[op]["disabledText"] = filter.text; + } else { + operations[op]["isDisabled"] = false; + } if (icon) { operations[op]["iconFont"] = icon; } else if (iconPath) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js index 792d1243ff..73f539562c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js @@ -127,7 +127,9 @@ policyModule = function () { var carbonUser = session.get(constants["USER_SESSION_KEY"]); if (!carbonUser) { log.error("User object was not found in the session"); - throw constants["ERRORS"]["USER_NOT_FOUND"]; + userModule.logout(function () { + response.sendRedirect(devicemgtProps["appContext"] + "login"); + }); } try { var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + @@ -145,7 +147,9 @@ policyModule = function () { var carbonUser = session.get(constants["USER_SESSION_KEY"]); if (!carbonUser) { log.error("User object was not found in the session"); - throw constants["ERRORS"]["USER_NOT_FOUND"]; + userModule.logout(function () { + response.sendRedirect(devicemgtProps["appContext"] + "login"); + }); } try { var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js index f8c420d58c..24e7cc696d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js @@ -115,7 +115,6 @@ var userModule = function () { var url = carbon.server.address('https') + "/admin/services"; var server = new carbon.server.Server(url); var userManager = new carbon.user.UserManager(server, tenantId); - try { if (userManager.userExists(username)) { if (log.isDebugEnabled()) { @@ -632,11 +631,17 @@ var userModule = function () { var url = carbon.server.address('https') + "/admin/services"; var server = new carbon.server.Server(url); var userManager = new carbon.user.UserManager(server, tenantId); + try { if (!userManager.roleExists(roleName)) { userManager.addRole(roleName, users, permissions); } else { - log.info("Role exist with name: " + roleName); + var array = Object.keys(permissions); + var i, permission; + for (i = 0; i < array.length; i++) { + permission = array[i]; + userManager.authorizeRole(roleName, permission, "ui.execute"); + } } } catch (e) { throw e; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js index ce57a85980..ba61809f7d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js @@ -56,6 +56,8 @@ var conf = function () { } } ); + var DeviceConfigurationManager = Packages.org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; + conf["serverConfig"] = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); application.put("CONF", conf); } return conf; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js index 56d03a6ce9..f499da1c99 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js @@ -47,7 +47,8 @@ var LANGUAGE_US = "en_US"; var VENDOR_APPLE = "Apple"; var ERRORS = { - "USER_NOT_FOUND": "USER_NOT_FOUND" + "USER_NOT_FOUND": "USER_NOT_FOUND", + "UNKNOWN_ERROR": "Unknown Error" }; var USER_STORES_NOISY_CHAR = "\""; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js index f6ee8587ec..9fc55c0f63 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js @@ -30,6 +30,7 @@ application.put("carbonServer", carbonServer); var permissions = { "/permission/admin/Login": ["ui.execute"], + "/permission/admin/manage/api/subscribe": ["ui.execute"], "/permission/admin/device-mgt/device/api/subscribe": ["ui.execute"], "/permission/admin/device-mgt/devices/enroll": ["ui.execute"], "/permission/admin/device-mgt/devices/disenroll": ["ui.execute"], diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js index 109e67f7ac..7a0eeba191 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js @@ -23,6 +23,7 @@ var utils = function () { var constants = require("/app/modules/constants.js"); var carbon = require("carbon"); var authModule = require("/lib/modules/auth/auth.js").module; + var utility = require('/app/modules/utility.js').utility; //noinspection JSUnresolvedVariable var Base64 = Packages.org.apache.commons.codec.binary.Base64; @@ -297,11 +298,17 @@ var utils = function () { // returning access token by JWT grant type var tokenInfo = jwtClient.getAccessToken(encodedClientAppCredentials, endUsername, scopes); - var tokenData = {}; - tokenData["accessToken"] = tokenInfo.getAccessToken(); - tokenData["refreshToken"] = tokenInfo.getRefreshToken(); - tokenData["scopes"] = tokenInfo.getScopes(); - return tokenData; + if (tokenInfo) { + var tokenData = {}; + tokenData["accessToken"] = tokenInfo.getAccessToken(); + tokenData["refreshToken"] = tokenInfo.getRefreshToken(); + tokenData["scopes"] = tokenInfo.getScopes(); + return tokenData; + } else { + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token " + + "by jwt grant type - getTokenPairAndScopesByJWTGrantType()"); + return null; + } } }; @@ -378,5 +385,22 @@ var utils = function () { } }; + publicMethods["removeClientAppCredentials"] = function (tenantDomain) { + var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]); + if (cachedTenantBasedClientAppCredentialsMap) { + if (cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { + delete cachedTenantBasedClientAppCredentialsMap[tenantDomain]; + } + } + }; + + publicMethods["getUniqueBrowserScope"] = function () { + var deviceScope = "device_" + utility.md5(request.getHeader("User-Agent") + "::" + request.getRemoteAddr()); + deviceScope = deviceScope + " "; + return deviceScope; + }; + + + return publicMethods; }(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js index 0fa1fbb0dc..921d708c60 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js @@ -51,7 +51,7 @@ var handlers = function () { // tokenPair will include current access token as well as current refresh token var arrayOfScopes = devicemgtProps["scopes"]; arrayOfScopes = arrayOfScopes.concat(utility.getDeviceTypesScopesList()); - var stringOfScopes = ""; + var stringOfScopes = tokenUtil.getUniqueBrowserScope(); arrayOfScopes.forEach(function (entry) { stringOfScopes += entry + " "; }); @@ -94,7 +94,7 @@ var handlers = function () { var tokenData; var arrayOfScopes = devicemgtProps["scopes"]; arrayOfScopes = arrayOfScopes.concat(utility.getDeviceTypesScopesList()); - var stringOfScopes = ""; + var stringOfScopes = tokenUtil.getUniqueBrowserScope(); arrayOfScopes.forEach(function (entry) { stringOfScopes += entry + " "; }); @@ -139,7 +139,7 @@ var handlers = function () { var tokenData; var arrayOfScopes = devicemgtProps["scopes"]; arrayOfScopes = arrayOfScopes.concat(utility.getDeviceTypesScopesList()); - var stringOfScopes = ""; + var stringOfScopes = tokenUtil.getUniqueBrowserScope(); arrayOfScopes.forEach(function (entry) { stringOfScopes += entry + " "; }); @@ -148,8 +148,7 @@ var handlers = function () { tokenData = tokenUtil. getTokenPairAndScopesByJWTGrantType(samlToken, encodedClientAppCredentials, stringOfScopes); if (!tokenData) { - throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up token " + - "pair by password grant type. Error in token " + + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up token. Error in token " + "retrieval - setupTokenPairBySamlGrantType(x, y)"); } else { var tokenPair = {}; @@ -180,6 +179,9 @@ var handlers = function () { if (!newTokenPair) { log.error("{/app/modules/oauth/token-handlers.js} Error in refreshing token pair. " + "Unable to update session context with new access token pair - refreshTokenPair()"); + userModule.logout(function () { + response.sendRedirect(devicemgtProps["appContext"] + "login"); + }); } else { session.put(constants["TOKEN_PAIR"], stringify(newTokenPair)); } @@ -263,5 +265,18 @@ var handlers = function () { } }; + publicMethods["removeClientDetails"] = function () { + var user = session.get(constants.USER_SESSION_KEY); + if (!user) { + log.error("User object was not found in the session"); + throw constants.ERRORS.USER_NOT_FOUND; + } + tokenUtil.removeClientAppCredentials(user.domain); + session.remove(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"]); + session.remove(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]); + session.remove(constants["TOKEN_PAIR"]); + session.remove(constants["ALLOWED_SCOPES"]); + }; + return publicMethods; }(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js index ed40ee7de8..efcb3c6cae 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js @@ -122,7 +122,12 @@ var invokers = function () { xmlHttpRequest.responseText == TOKEN_INVALID ) && count < 5) { tokenUtil.refreshTokenPair(); return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, ++count, headers); - } else if (privateMethods.isInvalidCredential(xmlHttpRequest.responseText)) { + } else if (privateMethods.isInvalidClientCredential(xmlHttpRequest.responseText)) { + log.error("API application has been removed."); + tokenUtil.removeClientDetails(); + session.invalidate(); + response.sendRedirect(devicemgtProps["appContext"] + "login"); + } else if (privateMethods.isInvalidCredential(xmlHttpRequest.responseText)) { tokenUtil.refreshTokenPair(); return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, ++count, headers); } @@ -143,11 +148,11 @@ var invokers = function () { if (responsePayload) { try { payload = parse(responsePayload); - if (payload["fault"]["code"] == 900901) { - log.debug("Access token is invalid: " + payload["fault"]["code"]); - log.debug(payload["fault"]["description"]); - return true; - } + if (payload["fault"]["code"] == 900901) { + log.debug("Access token is invalid: " + payload["fault"]["code"]); + log.debug(payload["fault"]["description"]); + return true; + } } catch (err) { // do nothing } @@ -155,6 +160,27 @@ var invokers = function () { return false; }; + /** + * This method verify whether the client credential is removed/blocked using response payload. + * This is required when using API gateway. + * @param responsePayload response payload. + * return true if it is invalid otherwise false. + */ + privateMethods["isInvalidClientCredential"] = + function (responsePayload) { + if (responsePayload) { + try { + payload = parse(responsePayload); + if (payload["fault"]["message"] == "Invalid Credentials") { + return true; + } + } catch (err) { + // do nothing + } + } + return false; + }; + /** * This method add Oauth authentication header to outgoing XML-HTTP Requests if Oauth authentication is enabled. * @param httpMethod HTTP request type. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js index 5505219181..cc8a20f552 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js @@ -67,6 +67,9 @@ utility = function () { publicMethods.getDeviceTypeConfig = function (deviceType) { var unitName = publicMethods.getTenantedDeviceUnitName(deviceType, "type-view"); + if (!unitName) { + return null; + } if (deviceType in deviceTypeConfigMap) { return deviceTypeConfigMap[deviceType]; @@ -103,6 +106,9 @@ utility = function () { publicMethods.getDeviceThumb = function (deviceType) { var unitName = publicMethods.getTenantedDeviceUnitName(deviceType, "type-view"); + if (!unitName) { + unitName = "cdmf.unit.default.device.type.type-view"; + } var iconPath = "/app/units/" + unitName + "/public/images/thumb.png"; var icon = new File(iconPath); if (icon.isExists()) { @@ -180,5 +186,211 @@ utility = function () { } }; + publicMethods.md5 = function (s) { + function L(k, d) { + return (k << d) | (k >>> (32 - d)) + } + + function K(G, k) { + var I, d, F, H, x; + F = (G & 2147483648); + H = (k & 2147483648); + I = (G & 1073741824); + d = (k & 1073741824); + x = (G & 1073741823) + (k & 1073741823); + if (I & d) { + return (x ^ 2147483648 ^ F ^ H) + } + if (I | d) { + if (x & 1073741824) { + return (x ^ 3221225472 ^ F ^ H) + } else { + return (x ^ 1073741824 ^ F ^ H) + } + } else { + return (x ^ F ^ H) + } + } + + function r(d, F, k) { + return (d & F) | ((~d) & k) + } + + function q(d, F, k) { + return (d & k) | (F & (~k)) + } + + function p(d, F, k) { + return (d ^ F ^ k) + } + + function n(d, F, k) { + return (F ^ (d | (~k))) + } + + function u(G, F, aa, Z, k, H, I) { + G = K(G, K(K(r(F, aa, Z), k), I)); + return K(L(G, H), F) + } + + function f(G, F, aa, Z, k, H, I) { + G = K(G, K(K(q(F, aa, Z), k), I)); + return K(L(G, H), F) + } + + function D(G, F, aa, Z, k, H, I) { + G = K(G, K(K(p(F, aa, Z), k), I)); + return K(L(G, H), F) + } + + function t(G, F, aa, Z, k, H, I) { + G = K(G, K(K(n(F, aa, Z), k), I)); + return K(L(G, H), F) + } + + function e(G) { + var Z; + var F = G.length; + var x = F + 8; + var k = (x - (x % 64)) / 64; + var I = (k + 1) * 16; + var aa = Array(I - 1); + var d = 0; + var H = 0; + while (H < F) { + Z = (H - (H % 4)) / 4; + d = (H % 4) * 8; + aa[Z] = (aa[Z] | (G.charCodeAt(H) << d)); + H++ + } + Z = (H - (H % 4)) / 4; + d = (H % 4) * 8; + aa[Z] = aa[Z] | (128 << d); + aa[I - 2] = F << 3; + aa[I - 1] = F >>> 29; + return aa + } + + function B(x) { + var k = "", F = "", G, d; + for (d = 0; d <= 3; d++) { + G = (x >>> (d * 8)) & 255; + F = "0" + G.toString(16); + k = k + F.substr(F.length - 2, 2) + } + return k + } + + function J(k) { + k = k.replace(/rn/g, "n"); + var d = ""; + for (var F = 0; F < k.length; F++) { + var x = k.charCodeAt(F); + if (x < 128) { + d += String.fromCharCode(x) + } else { + if ((x > 127) && (x < 2048)) { + d += String.fromCharCode((x >> 6) | 192); + d += String.fromCharCode((x & 63) | 128) + } else { + d += String.fromCharCode((x >> 12) | 224); + d += String.fromCharCode(((x >> 6) & 63) | 128); + d += String.fromCharCode((x & 63) | 128) + } + } + } + return d + } + + var C = Array(); + var P, h, E, v, g, Y, X, W, V; + var S = 7, Q = 12, N = 17, M = 22; + var A = 5, z = 9, y = 14, w = 20; + var o = 4, m = 11, l = 16, j = 23; + var U = 6, T = 10, R = 15, O = 21; + s = J(s); + C = e(s); + Y = 1732584193; + X = 4023233417; + W = 2562383102; + V = 271733878; + for (P = 0; P < C.length; P += 16) { + h = Y; + E = X; + v = W; + g = V; + Y = u(Y, X, W, V, C[P + 0], S, 3614090360); + V = u(V, Y, X, W, C[P + 1], Q, 3905402710); + W = u(W, V, Y, X, C[P + 2], N, 606105819); + X = u(X, W, V, Y, C[P + 3], M, 3250441966); + Y = u(Y, X, W, V, C[P + 4], S, 4118548399); + V = u(V, Y, X, W, C[P + 5], Q, 1200080426); + W = u(W, V, Y, X, C[P + 6], N, 2821735955); + X = u(X, W, V, Y, C[P + 7], M, 4249261313); + Y = u(Y, X, W, V, C[P + 8], S, 1770035416); + V = u(V, Y, X, W, C[P + 9], Q, 2336552879); + W = u(W, V, Y, X, C[P + 10], N, 4294925233); + X = u(X, W, V, Y, C[P + 11], M, 2304563134); + Y = u(Y, X, W, V, C[P + 12], S, 1804603682); + V = u(V, Y, X, W, C[P + 13], Q, 4254626195); + W = u(W, V, Y, X, C[P + 14], N, 2792965006); + X = u(X, W, V, Y, C[P + 15], M, 1236535329); + Y = f(Y, X, W, V, C[P + 1], A, 4129170786); + V = f(V, Y, X, W, C[P + 6], z, 3225465664); + W = f(W, V, Y, X, C[P + 11], y, 643717713); + X = f(X, W, V, Y, C[P + 0], w, 3921069994); + Y = f(Y, X, W, V, C[P + 5], A, 3593408605); + V = f(V, Y, X, W, C[P + 10], z, 38016083); + W = f(W, V, Y, X, C[P + 15], y, 3634488961); + X = f(X, W, V, Y, C[P + 4], w, 3889429448); + Y = f(Y, X, W, V, C[P + 9], A, 568446438); + V = f(V, Y, X, W, C[P + 14], z, 3275163606); + W = f(W, V, Y, X, C[P + 3], y, 4107603335); + X = f(X, W, V, Y, C[P + 8], w, 1163531501); + Y = f(Y, X, W, V, C[P + 13], A, 2850285829); + V = f(V, Y, X, W, C[P + 2], z, 4243563512); + W = f(W, V, Y, X, C[P + 7], y, 1735328473); + X = f(X, W, V, Y, C[P + 12], w, 2368359562); + Y = D(Y, X, W, V, C[P + 5], o, 4294588738); + V = D(V, Y, X, W, C[P + 8], m, 2272392833); + W = D(W, V, Y, X, C[P + 11], l, 1839030562); + X = D(X, W, V, Y, C[P + 14], j, 4259657740); + Y = D(Y, X, W, V, C[P + 1], o, 2763975236); + V = D(V, Y, X, W, C[P + 4], m, 1272893353); + W = D(W, V, Y, X, C[P + 7], l, 4139469664); + X = D(X, W, V, Y, C[P + 10], j, 3200236656); + Y = D(Y, X, W, V, C[P + 13], o, 681279174); + V = D(V, Y, X, W, C[P + 0], m, 3936430074); + W = D(W, V, Y, X, C[P + 3], l, 3572445317); + X = D(X, W, V, Y, C[P + 6], j, 76029189); + Y = D(Y, X, W, V, C[P + 9], o, 3654602809); + V = D(V, Y, X, W, C[P + 12], m, 3873151461); + W = D(W, V, Y, X, C[P + 15], l, 530742520); + X = D(X, W, V, Y, C[P + 2], j, 3299628645); + Y = t(Y, X, W, V, C[P + 0], U, 4096336452); + V = t(V, Y, X, W, C[P + 7], T, 1126891415); + W = t(W, V, Y, X, C[P + 14], R, 2878612391); + X = t(X, W, V, Y, C[P + 5], O, 4237533241); + Y = t(Y, X, W, V, C[P + 12], U, 1700485571); + V = t(V, Y, X, W, C[P + 3], T, 2399980690); + W = t(W, V, Y, X, C[P + 10], R, 4293915773); + X = t(X, W, V, Y, C[P + 1], O, 2240044497); + Y = t(Y, X, W, V, C[P + 8], U, 1873313359); + V = t(V, Y, X, W, C[P + 15], T, 4264355552); + W = t(W, V, Y, X, C[P + 6], R, 2734768916); + X = t(X, W, V, Y, C[P + 13], O, 1309151649); + Y = t(Y, X, W, V, C[P + 4], U, 4149444226); + V = t(V, Y, X, W, C[P + 11], T, 3174756917); + W = t(W, V, Y, X, C[P + 2], R, 718787259); + X = t(X, W, V, Y, C[P + 9], O, 3951481745); + Y = K(Y, h); + X = K(X, E); + W = K(W, v); + V = K(V, g) + } + var i = B(Y) + B(X) + B(W) + B(V); + return i.toLowerCase() + }; + return publicMethods; }(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.hbs index f526cc03a3..689312a441 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.hbs @@ -191,6 +191,40 @@ + {{#if permissions.IS_ADMIN}} +
+
+
Device Types
+
+
+
+ {{deviceTypeCount}} + + + {{#if deviceTypeCount}} + + + + + + View + + {{/if}} + + + + + + + Add + + +
+
+
+
+ {{/if}} + {{else}}

Permitted None diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js index 4e0c9aafa1..bc1460153c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js @@ -44,6 +44,7 @@ function onRequest(context) { viewModel.groupCount = groupModule.getGroupCount(); viewModel.userCount = userModule.getUsersCount(); viewModel.policyCount = policyModule.getPoliciesCount(); + viewModel.deviceTypeCount = deviceModule.getDeviceTypeCount(); viewModel.isCloud = devicemgtProps.isCloud; if (devicemgtProps.isCloud) { viewModel.roleCount = userModule.getFilteredRoles("devicemgt").content.count; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/analytics.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/analytics.js index f77e3d14ce..54234b86db 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/analytics.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/analytics.js @@ -21,8 +21,12 @@ function onRequest(context) { var deviceType = context.uriParams.deviceType; var deviceName = request.getParameter("deviceName"); var deviceId = request.getParameter("deviceId"); + var unitName = utility.getTenantedDeviceUnitName(deviceType, "analytics-view"); + if (!unitName) { + unitName = "cdmf.unit.default.device.type.analytics-view"; + } return { - "deviceAnalyticsViewUnitName": utility.getTenantedDeviceUnitName(deviceType, "analytics-view"), + "deviceAnalyticsViewUnitName": unitName, "deviceType": deviceType, "deviceName": deviceName, "deviceId": deviceId diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.type.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.type.view/view.js index 693769dd11..6810da2496 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.type.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.type.view/view.js @@ -32,15 +32,18 @@ function onRequest(context) { var utility = require("/app/modules/utility.js").utility; var deviceType = context.uriParams.deviceType; - var configs = utility.getDeviceTypeConfig(deviceType); - if(!configs["deviceType"]){ - throw new Error("Invalid Device Type Configurations Found!",""); - } - + var label = deviceType; + if (configs) { + label = configs["deviceType"]["label"]; + } + var unitName = utility.getTenantedDeviceUnitName(deviceType, "type-view"); + if (!unitName) { + unitName = "cdmf.unit.default.device.type.type-view"; + } return { - "deviceTypeViewUnitName": utility.getTenantedDeviceUnitName(deviceType, "type-view"), + "deviceTypeViewUnitName": unitName, "deviceType": deviceType, - "label" : configs["deviceType"]["label"] + "label" : label }; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.view/view.js index 21ce993020..754cef4fa8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.view/view.js @@ -29,5 +29,9 @@ function onRequest(context){ }); var deviceType = context.uriParams.deviceType; - return {"deviceViewUnitName": utility.getTenantedDeviceUnitName(deviceType, "device-view")}; + var unitName = utility.getTenantedDeviceUnitName(deviceType, "device-view"); + if (!unitName) { + unitName = "cdmf.unit.default.device.type.device-view"; + } + return {"deviceViewUnitName": unitName}; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs index bacf924066..e515e2df35 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs @@ -313,7 +313,7 @@ @@ -374,7 +374,7 @@
+
+ + + +
+
+
+
+ +
+ +
+
+
+
+
+
+
+
+ +
+ +
+
+
+
+ + + + + + + + +
+
+
+
+ +
+ +
+
+
+
+
+
+
+
+ +
+ +
+
+
+
+ + + + + + +
+ + + + + + + + + + + + + + {{else}} +

+ Permission Denied +

+
+ You not authorized to create device type. +
+ {{/if}} +{{/zone}} + +{{#zone "bottomJs"}} + {{js "js/bottomJs.js"}} +{{/zone}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.create/create.js new file mode 100644 index 0000000000..f67504684b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.create/create.js @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2016, 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. + */ + +function onRequest(context) { + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; + var displayData = {}; + + if (userModule.isAuthorized("/permission/admin/device-mgt/admin/device-type")) { + displayData.canManage = true; + } + + return displayData; +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.create/create.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.create/create.json new file mode 100644 index 0000000000..0de47dfc78 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.create/create.json @@ -0,0 +1,5 @@ +{ + "version": "1.0.0", + "uri": "/device-type/add", + "layout": "cdmf.layout.default" +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.create/public/css/devicetype.css b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.create/public/css/devicetype.css new file mode 100644 index 0000000000..28d691e6b0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.create/public/css/devicetype.css @@ -0,0 +1,19 @@ +.wr-btn-horizontal{ + padding: 7px 10px; +} + +.dontfloat { + clear:both; +} + +.hidden-div { + display: none; +} + +.feature-wrapper{ + margin-top: 10px; +} + +.wr-btn-secondary{ + background-color: #617d8b; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.create/public/js/bottomJs.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.create/public/js/bottomJs.js new file mode 100644 index 0000000000..ca750b6907 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.create/public/js/bottomJs.js @@ -0,0 +1,243 @@ +/* + * Copyright (c) 2016, 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. + */ + +/** + * Checks if provided input is valid against RegEx input. + * + * @param regExp Regular expression + * @param inputString Input string to check + * @returns {boolean} Returns true if input matches RegEx + */ +function inputIsValid(regExp, inputString) { + regExp = new RegExp(regExp); + return regExp.test(inputString); +} + +var validateInline = {}; +var clearInline = {}; + +var apiBasePath = "/api/device-mgt/v1.0"; + + +var enableInlineError = function (inputField, errorMsg, errorSign) { + var fieldIdentifier = "#" + inputField; + var errorMsgIdentifier = "#" + inputField + " ." + errorMsg; + var errorSignIdentifier = "#" + inputField + " ." + errorSign; + + if (inputField) { + $(fieldIdentifier).addClass(" has-error has-feedback"); + } + + if (errorMsg) { + $(errorMsgIdentifier).removeClass(" hidden"); + } + + if (errorSign) { + $(errorSignIdentifier).removeClass(" hidden"); + } +}; + +var disableInlineError = function (inputField, errorMsg, errorSign) { + var fieldIdentifier = "#" + inputField; + var errorMsgIdentifier = "#" + inputField + " ." + errorMsg; + var errorSignIdentifier = "#" + inputField + " ." + errorSign; + + if (inputField) { + $(fieldIdentifier).removeClass(" has-error has-feedback"); + } + + if (errorMsg) { + $(errorMsgIdentifier).addClass(" hidden"); + } + + if (errorSign) { + $(errorSignIdentifier).addClass(" hidden"); + } +}; + + +function formatRepo(user) { + if (user.loading) { + return user.text + } + if (!user.username) { + return; + } + var markup = '
' + + '
' + + '
' + + '
' + user.username + '
'; + if (user.name || user.name != undefined) { + markup += '
( ' + user.name + ' )
'; + } + markup += '
'; + return markup; +} + +function formatRepoSelection(user) { + return user.username || user.text; +} + + + +$(document).ready(function () { + + $('[data-toggle="tooltip"]').tooltip(); + var appContext = $("#app-context").data("app-context"); + + var maxField = 100; //Input fields increment limitation + var addButton = $('.add_button'); //Add button selector + var wrapper = $('.attribute_field_wrapper'); //Input field wrapper + var fieldHTML = $('#add-attribute-field').html(); //New input field html + $(addButton).click(function(){ //Once add button is clicked + $(wrapper).append(fieldHTML); // Add field html + }); + $(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked + e.preventDefault(); + $(this).parent('div').remove(); + }); + + var addOperationButton = $('.add_operation_button'); //Add button selector + var operationWrapper = $('.operation_field_wrapper'); //Input field wrapper + var operationFieldHTML = $('#add-operation-field').html(); //New input field html + $(addOperationButton).click(function(){ //Once add button is clicked + $(operationWrapper).append(operationFieldHTML); // Add field html + }); + $(operationWrapper).on('click', '.remove_operation_button', function(e){ //Once remove button is clicked + e.preventDefault(); + $(this).parent('div').remove(); + }); + + + var addFeatureButton = $('.add_feature_button'); //Add button selector + var featureWrapper = $('.feature_field_wrapper'); //Input field wrapper + $(addFeatureButton).click(function(){ //Once add button is clicked + var featureFieldHtml = '
' + + '
' + + '
' + + '
' + $(featureWrapper).append(featureFieldHtml); // Add field html + }); + $(featureWrapper).on('click', '.remove_feature_button', function(e){ //Once remove button is clicked + e.preventDefault(); + $(this).parent('div').remove(); //Remove field html + }); + + /** + * Following click function would execute + * when a user clicks on "Add Device type" button. + */ + $("button#add-devicetype-btn").click(function () { + + var errorMsgWrapper = "#devicetype-create-error-msg"; + var errorMsg = "#devicetype-create-error-msg span"; + var deviceType = {}; + var deviceTypeName = $("#deviceTypeName").val(); + var deviceTypeDescription = $("#deviceTypeDescription").val(); + if (!deviceTypeName || deviceTypeName.trim() == "" ) { + $(errorMsg).text("Device Type Name Cannot be empty."); + $(errorMsgWrapper).removeClass("hidden"); + return; + } + + if (!deviceTypeDescription || deviceTypeDescription.trim() == "" ) { + $(errorMsg).text("Device Type Description Cannot be empty."); + $(errorMsgWrapper).removeClass("hidden"); + return + } + + deviceType.name = deviceTypeName.trim(); + deviceType.deviceTypeMetaDefinition = {} + deviceType.deviceTypeMetaDefinition.description = deviceTypeDescription.trim(); + + var pushNotification = $("#pushNotification").val(); + if (pushNotification != "NONE") { + deviceType.deviceTypeMetaDefinition.pushNotificationConfig = {}; + deviceType.deviceTypeMetaDefinition.pushNotificationConfig.scheduled = true; + deviceType.deviceTypeMetaDefinition.pushNotificationConfig.type = pushNotification; + } + + var propertyValues = []; + $('input[name^="attribute"]').each(function() { + var propertyValue = $(this).val(); + if (propertyValue.trim() != "") { + propertyValues.push(propertyValue.trim()); + } + }); + deviceType.deviceTypeMetaDefinition.properties = propertyValues; + + var operationValues = []; + $('input[name^="operation"]').each(function() { + var operationValue = $(this).val(); + if (operationValue.trim() != "") { + operationValues.push(operationValue.trim()); + } + }); + if (operationValues.length > 0) { + deviceType.deviceTypeMetaDefinition.initialOperationConfig = {}; + deviceType.deviceTypeMetaDefinition.initialOperationConfig.operations = operationValues; + } + + var features = []; + $('div[name^="deviceFeature"]').each(function() { + var featureName = $(this).find("#feature-name").val(); + var featureCode = $(this).find("#feature-code").val(); + var featureDescription = $(this).find("#feature-description").val(); + if (featureName && featureName.trim() != "" && featureCode && featureCode.trim() != "") { + var feature = {}; + feature.name = featureName.trim(); + feature.code = featureCode.trim(); + feature.description = featureDescription.trim(); + features.push(feature); + } + }); + deviceType.deviceTypeMetaDefinition.features = features; + + var addRoleAPI = apiBasePath + "/admin/device-types"; + + invokerUtil.post( + addRoleAPI, + deviceType, + function (data, textStatus, jqXHR) { + if (jqXHR.status == 200) { + window.location.href = appContext + "/device-type/edit-event?type=" + + encodeURIComponent(deviceTypeName); + } + }, + function (jqXHR) { + if (jqXHR.status == 500) { + $(errorMsg).text("Unexpected error."); + $(errorMsgWrapper).removeClass("hidden"); + } + if (jqXHR.status == 400) { + $(errorMsg).text("Device type name should not contain whitespaces."); + $(errorMsgWrapper).removeClass("hidden"); + } + + if (jqXHR.status == 409) { + $(errorMsg).text("Device type already exists"); + $(errorMsgWrapper).removeClass("hidden"); + } + } + ); + }); + +}); \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.hbs new file mode 100644 index 0000000000..599ffcec4e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.hbs @@ -0,0 +1,271 @@ +{{! + Copyright (c) 2017, 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. +}} +{{unit "cdmf.unit.ui.title" pageTitle="Device Type Management"}} + +{{#zone "topCss"}} + {{css "css/devicetype.css"}} +{{/zone}} + +{{#zone "breadcrumbs"}} +
  • + + + +
  • +
  • + + + Device Types + +
  • +
  • + + + Edit + +
  • +{{/zone}} + +{{#zone "content"}} + {{#if canManage}} + +
    +
    + +
    +
    +

    {{name}}

    +
    +
    +
    + +
    + + +
    + +
    + +
    + +
    + +
    + + +
    +
    + + +
    +
    + {{#if type.deviceTypeMetaDefinition.features}} + {{#each type.deviceTypeMetaDefinition.features}} +
    +
    +
    + +
    +
    + +
    +
    + +
    + +
    +
    + {{/each}} + {{/if}} +
    +
    +
    + +
    +
    + +
    +
    + +
    + +
    +
    +
    + +
    + +
    +
    + {{#if type.deviceTypeMetaDefinition.properties}} + {{#each type.deviceTypeMetaDefinition.properties}} +
    +
    +
    + +
    + +
    +
    + {{/each}} + {{/if}} +
    +
    +
    + +
    + +
    +
    +
    +
    +
    +
    +
    +
    + +
    + +
    +
    +
    +
    + + + + + + +
    + {{#if type.deviceTypeMetaDefinition.initialOperationConfig}} + {{#each type.deviceTypeMetaDefinition.initialOperationConfig.operations}} +
    +
    +
    + +
    + +
    +
    + {{/each}} + {{/if}} +
    +
    +
    + +
    + +
    +
    +
    +
    +
    +
    +
    +
    + +
    + +
    +
    +
    +
    + + + + +
    + +
    +
    + + +
    +
    + + + + +
    +
    + + {{else}} +

    + Permission Denied +

    +
    + You not authorized to edit device type. +
    + {{/if}} +{{/zone}} + +{{#zone "bottomJs"}} + {{js "js/bottomJs.js"}} +{{/zone}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.js new file mode 100644 index 0000000000..94284ac016 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.js @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2016, 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. + */ + +function onRequest(context) { + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; + var displayData = {}; + + + if (userModule.isAuthorized("/permission/admin/device-mgt/admin/device-type")) { + displayData.canManage = true; + } + context.handlebars.registerHelper('if_eq', function(a, b, opts) { + if(a == b) // Or === depending on your needs + return opts.fn(this); + else + return opts.inverse(this); + }); + + var deviceType = request.getParameter("type"); + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; + var restAPIEndpoint = deviceMgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + + "/device-types/config/" + deviceType; + displayData.name = deviceType; + serviceInvokers.XMLHttp.get( + restAPIEndpoint, + function (restAPIResponse) { + if (restAPIResponse["status"] == 200 && restAPIResponse["responseText"]) { + var typeData = parse(restAPIResponse["responseText"]); + displayData.type = typeData; + + } + } + ); + + return displayData; +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.json new file mode 100644 index 0000000000..26088b9d86 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.json @@ -0,0 +1,5 @@ +{ + "version": "1.0.0", + "uri": "/device-type/edit", + "layout": "cdmf.layout.default" +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/public/css/devicetype.css b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/public/css/devicetype.css new file mode 100644 index 0000000000..19307c1c79 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/public/css/devicetype.css @@ -0,0 +1,25 @@ +.wr-btn-horizontal{ + padding: 7px 10px; +} + +.dontfloat { + clear:both; +} + +.hidden-div { + display: none; +} + +.hidden-input { + display: none; +} + +.feature-wrapper{ + margin-top: 10px; +} +.wr-btn-secondary{ + background-color: #617d8b; +} +.wr-btn-secondary{ + background-color: #617d8b; +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/public/js/bottomJs.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/public/js/bottomJs.js new file mode 100644 index 0000000000..3fd2548a6f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/public/js/bottomJs.js @@ -0,0 +1,237 @@ +/* + * Copyright (c) 2016, 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. + */ + +/** + * Checks if provided input is valid against RegEx input. + * + * @param regExp Regular expression + * @param inputString Input string to check + * @returns {boolean} Returns true if input matches RegEx + */ +function inputIsValid(regExp, inputString) { + regExp = new RegExp(regExp); + return regExp.test(inputString); +} + +var validateInline = {}; +var clearInline = {}; + +var apiBasePath = "/api/device-mgt/v1.0"; +var domain = $("#domain").val(); + + +var enableInlineError = function (inputField, errorMsg, errorSign) { + var fieldIdentifier = "#" + inputField; + var errorMsgIdentifier = "#" + inputField + " ." + errorMsg; + var errorSignIdentifier = "#" + inputField + " ." + errorSign; + + if (inputField) { + $(fieldIdentifier).addClass(" has-error has-feedback"); + } + + if (errorMsg) { + $(errorMsgIdentifier).removeClass(" hidden"); + } + + if (errorSign) { + $(errorSignIdentifier).removeClass(" hidden"); + } +}; + +var disableInlineError = function (inputField, errorMsg, errorSign) { + var fieldIdentifier = "#" + inputField; + var errorMsgIdentifier = "#" + inputField + " ." + errorMsg; + var errorSignIdentifier = "#" + inputField + " ." + errorSign; + + if (inputField) { + $(fieldIdentifier).removeClass(" has-error has-feedback"); + } + + if (errorMsg) { + $(errorMsgIdentifier).addClass(" hidden"); + } + + if (errorSign) { + $(errorSignIdentifier).addClass(" hidden"); + } +}; + +function formatRepo(user) { + if (user.loading) { + return user.text + } + if (!user.username) { + return; + } + var markup = '
    ' + + '
    ' + + '
    ' + + '
    ' + user.username + '
    '; + if (user.name || user.name != undefined) { + markup += '
    ( ' + user.name + ' )
    '; + } + markup += '
    '; + return markup; +} + +function formatRepoSelection(user) { + return user.username || user.text; +} + +$(document).ready(function () { + + var appContext = $("#app-context").data("app-context"); + + var addButton = $('.add_button'); //Add button selector + var wrapper = $('.attribute_field_wrapper'); //Input field wrapper + var fieldHTML = $('#add-attribute-field').html(); //New input field html + $(addButton).click(function(){ //Once add button is clicked + $(wrapper).append(fieldHTML); // Add field html + }); + $(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked + e.preventDefault(); + $(this).parent('div').remove(); //Remove field html + }); + + var addOperationButton = $('.add_operation_button'); //Add button selector + var operationWrapper = $('.operation_field_wrapper'); //Input field wrapper + var operationFieldHTML = $('#add-operation-field').html(); //New input field html + $(addOperationButton).click(function(){ //Once add button is clicked + $(operationWrapper).append(operationFieldHTML); // Add field html + }); + $(operationWrapper).on('click', '.remove_operation_button', function(e){ //Once remove button is clicked + e.preventDefault(); + $(this).parent('div').remove(); + }); + + + var addFeatureButton = $('.add_feature_button'); //Add button selector + var featureWrapper = $('.feature_field_wrapper'); //Input field wrapper + $(addFeatureButton).click(function(){ //Once add button is clicked + var featureFieldHtml = '
    ' + + '
    ' + + '
    ' + + '
    ' + $(featureWrapper).append(featureFieldHtml); // Add field html + + }); + $(featureWrapper).on('click', '.remove_feature_button', function(e){ //Once remove button is clicked + e.preventDefault(); + $(this).parent('div').remove(); //Remove field html + op--; //Decrement field counter + }); + + /** + * Following click function would execute + * when a user clicks on "Add Device type" button. + */ + $("button#add-devicetype-btn").click(function () { + + var errorMsgWrapper = "#devicetype-create-error-msg"; + var errorMsg = "#devicetype-create-error-msg span"; + var successMsgWrapper = "#devicetype-create-success-msg"; + var successMsg = "#devicetype-create-success-msg span"; + var deviceType = {}; + var deviceTypeName = $("#deviceTypeName").val(); + var deviceTypeDescription = $("#deviceTypeDescription").val(); + if (!deviceTypeName || deviceTypeName.trim() == "" ) { + $(errorMsg).text("Device Type Name Cannot be empty."); + $(errorMsgWrapper).removeClass("hidden"); + return; + } + + if (!deviceTypeDescription || deviceTypeDescription.trim() == "" ) { + $(errorMsg).text("Device Type Description Cannot be empty."); + $(errorMsgWrapper).removeClass("hidden"); + return + } + + deviceType.name = deviceTypeName.trim(); + deviceType.deviceTypeMetaDefinition = {} + deviceType.deviceTypeMetaDefinition.description = deviceTypeDescription.trim(); + + var pushNotification = $("#pushNotification").val(); + if (pushNotification != "NONE") { + deviceType.deviceTypeMetaDefinition.pushNotificationConfig = {}; + deviceType.deviceTypeMetaDefinition.pushNotificationConfig.scheduled = true; + deviceType.deviceTypeMetaDefinition.pushNotificationConfig.type = pushNotification; + } + + var propertyValues = []; + $('input[name^="attribute"]').each(function() { + var propertyValue = $(this).val(); + if (propertyValue.trim() != "") { + propertyValues.push(propertyValue.trim()); + } + }); + deviceType.deviceTypeMetaDefinition.properties = propertyValues; + + var operationValues = []; + $('input[name^="operation"]').each(function() { + var operationValue = $(this).val(); + if (operationValue.trim() != "") { + operationValues.push(operationValue.trim()); + } + }); + if (operationValues.length > 0) { + deviceType.deviceTypeMetaDefinition.initialOperationConfig = {}; + deviceType.deviceTypeMetaDefinition.initialOperationConfig.operations = operationValues; + } + + var features = []; + $('div[name^="deviceFeature"]').each(function() { + var featureName = $(this).find("#feature-name").val(); + var featureCode = $(this).find("#feature-code").val(); + if (featureName && featureName.trim() != "" && featureCode && featureCode.trim() != "") { + var feature = {}; + feature.name = featureName.trim(); + feature.code = featureCode.trim(); + feature.description = $("#feature-description").val(); + features.push(feature); + } + }); + deviceType.deviceTypeMetaDefinition.features = features; + + var addRoleAPI = apiBasePath + "/admin/device-types"; + + invokerUtil.put( + addRoleAPI, + deviceType, + function (data, textStatus, jqXHR) { + if (jqXHR.status == 200) { + $("#modalDevice").modal('show'); + } + }, + function (jqXHR) { + if (jqXHR.status == 500) { + $(errorMsg).text("Unexpected error."); + $(errorMsgWrapper).removeClass("hidden"); + } + + if (jqXHR.status == 409) { + $(errorMsg).text("Device type already exists"); + $(errorMsgWrapper).removeClass("hidden"); + } + } + ); + }); + +}); \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/edit.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/edit.hbs new file mode 100644 index 0000000000..f9707c27b8 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/edit.hbs @@ -0,0 +1,179 @@ +{{! + Copyright (c) 2017, 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. +}} +{{unit "cdmf.unit.ui.title" pageTitle="Device Type Management"}} + +{{#zone "topCss"}} + {{css "css/devicetype.css"}} +{{/zone}} + +{{#zone "breadcrumbs"}} +
  • + + + +
  • +
  • + + + Device Types + +
  • +
  • + + + Event + +
  • +{{/zone}} + +{{#zone "content"}} + {{#if canManage}} + +
    +
    + +
    +
    +

    {{name}}

    +
    +
    +
    + +
    + + + +
    + + +
    + + +
    +
    + {{#if event.eventAttributes}} + {{#each event.eventAttributes.attributes}} +
    +
    +
    + +
    +
    + +
    + +
    +
    + {{/each}} + {{/if}} +
    +
    +
    + +
    +
    + +
    + +
    +
    +
    + +
    + {{#if event}} + + {{else}} + + {{/if}} + + +
    +
    + + + +
    +
    + + + + {{else}} +

    + Permission Denied +

    +
    + You not authorized to edit device type. +
    + {{/if}} +{{/zone}} + +{{#zone "bottomJs"}} + {{js "js/bottomJs.js"}} +{{/zone}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/edit.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/edit.js new file mode 100644 index 0000000000..d18ee388b1 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/edit.js @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2016, 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. + */ + +function onRequest(context) { + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; + var displayData = {}; + + + if (userModule.isAuthorized("/permission/admin/device-mgt/admin/device-type")) { + displayData.canManage = true; + } + context.handlebars.registerHelper('selected', function(a, b, opts) { + if(a == b) // Or === depending on your needs + return "selected"; + else + return ""; + }); + + var deviceType = request.getParameter("type"); + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; + var restAPIEndpoint = deviceMgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + + "/events/" + deviceType; + displayData.name = deviceType; + serviceInvokers.XMLHttp.get( + restAPIEndpoint, + function (restAPIResponse) { + if (restAPIResponse["status"] == 200 && restAPIResponse["responseText"]) { + var typeData = parse(restAPIResponse["responseText"]); + displayData.event = typeData; + } + } + ); + + return displayData; +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/edit.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/edit.json new file mode 100644 index 0000000000..9e773121e5 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/edit.json @@ -0,0 +1,5 @@ +{ + "version": "1.0.0", + "uri": "/device-type/edit-event", + "layout": "cdmf.layout.default" +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/public/css/devicetype.css b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/public/css/devicetype.css new file mode 100644 index 0000000000..d915490351 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/public/css/devicetype.css @@ -0,0 +1,29 @@ + + +.dontfloat { + clear:both; +} + +.hidden-div { + display: none; +} + +.hidden-input { + display: none; +} + +.event-wrapper{ + margin-top: 10px; +} + +.wr-btn-horizontal{ + padding: 7px 10px; +} + +.wr-btn-secondary{ + background-color: #617d8b; +} + +.page-content-wrapper{ + height: calc(100vh - 50px); +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/public/js/bottomJs.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/public/js/bottomJs.js new file mode 100644 index 0000000000..25f94e8705 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.event.edit/public/js/bottomJs.js @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2016, 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. + */ + +/** + * Checks if provided input is valid against RegEx input. + * + * @param regExp Regular expression + * @param inputString Input string to check + * @returns {boolean} Returns true if input matches RegEx + */ +function inputIsValid(regExp, inputString) { + regExp = new RegExp(regExp); + return regExp.test(inputString); +} + +var validateInline = {}; +var clearInline = {}; + +var apiBasePath = "/api/device-mgt/v1.0"; +var domain = $("#domain").val(); + + +var enableInlineError = function (inputField, errorMsg, errorSign) { + var fieldIdentifier = "#" + inputField; + var errorMsgIdentifier = "#" + inputField + " ." + errorMsg; + var errorSignIdentifier = "#" + inputField + " ." + errorSign; + + if (inputField) { + $(fieldIdentifier).addClass(" has-error has-feedback"); + } + + if (errorMsg) { + $(errorMsgIdentifier).removeClass(" hidden"); + } + + if (errorSign) { + $(errorSignIdentifier).removeClass(" hidden"); + } +}; + +var disableInlineError = function (inputField, errorMsg, errorSign) { + var fieldIdentifier = "#" + inputField; + var errorMsgIdentifier = "#" + inputField + " ." + errorMsg; + var errorSignIdentifier = "#" + inputField + " ." + errorSign; + + if (inputField) { + $(fieldIdentifier).removeClass(" has-error has-feedback"); + } + + if (errorMsg) { + $(errorMsgIdentifier).addClass(" hidden"); + } + + if (errorSign) { + $(errorSignIdentifier).addClass(" hidden"); + } +}; + +function formatRepo(user) { + if (user.loading) { + return user.text + } + if (!user.username) { + return; + } + var markup = '
    ' + + '
    ' + + '
    ' + + '
    ' + user.username + '
    '; + if (user.name || user.name != undefined) { + markup += '
    ( ' + user.name + ' )
    '; + } + markup += '
    '; + return markup; +} + +function formatRepoSelection(user) { + return user.username || user.text; +} + + + +$(document).ready(function () { + + var appContext = $("#app-context").data("app-context"); + var addEventButton = $('.add_event_button'); //Add button selector + var eventWrapper = $('.event_field_wrapper'); //Input field wrapper + $(addEventButton).click(function(){ //Once add button is clicked + var eventFieldHtml = '
    ' + + '
    ' + + '
    ' + + '
    ' + $(eventWrapper).append(eventFieldHtml); // Add field html + + }); + $(eventWrapper).on('click', '.remove_event_button', function(e){ //Once remove button is clicked + e.preventDefault(); + $(this).parent('div').remove(); + }); + + /** + * Following click function would execute + * when a user clicks on "Add Device type" button. + */ + $("button#add-event-btn").click(function () { + + var errorMsgWrapper = "#devicetype-create-error-msg"; + var errorMsg = "#devicetype-create-error-msg span"; + var successMsgWrapper = "#devicetype-create-success-msg"; + var successMsg = "#devicetype-create-success-msg span"; + var deviceTypeEvent = {}; + var deviceTypeName = $("#deviceTypeName").val(); + var deviceTypeDescription = $("#deviceTypeDescription").val(); + if (!deviceTypeName || deviceTypeName.trim() == "" ) { + $(errorMsg).text("Device Type Name Cannot be empty."); + $(errorMsgWrapper).removeClass("hidden"); + return; + } + + + deviceTypeEvent.eventAttributes = {}; + + deviceTypeEvent.transport = $("#transport").val(); + + var attributes = []; + $('div[name^="deviceEvent"]').each(function() { + var eventName = $(this).find("#event-name").val(); + var eventType = $(this).find("#event-type").val(); + if (eventName && eventName.trim() != "" && eventType && eventType.trim() != "" && eventName != "deviceId") { + var attribute = {}; + attribute.name = eventName.trim(); + attribute.type = eventType.trim(); + attributes.push(attribute); + } + }); + deviceTypeEvent.eventAttributes.attributes = attributes; + + var addEventsAPI = apiBasePath + "/events/" + deviceTypeName; + + invokerUtil.post( + addEventsAPI, + deviceTypeEvent, + function (data, textStatus, jqXHR) { + if (jqXHR.status == 200) { + $("#modalDevice").modal('show'); + } + }, + function (jqXHR) { + if (jqXHR.status == 500) { + $(errorMsg).text("Failed to deploy event definition, Please Contact Administrator"); + $(errorMsgWrapper).removeClass("hidden"); + } + + if (jqXHR.status == 409) { + $(errorMsg).text("Device type definition cannot be updated"); + $(errorMsgWrapper).removeClass("hidden"); + } + } + ); + }); + + + +}); \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/devicetypes.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/devicetypes.hbs new file mode 100644 index 0000000000..e59b248e4f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/devicetypes.hbs @@ -0,0 +1,114 @@ +{{! + Copyright (c) 2016, 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. +}} + +{{unit "cdmf.unit.ui.title" pageTitle="Device Type Management"}} +{{unit "cdmf.unit.data-tables-extended"}} +{{unit "cdmf.unit.ui.modal"}} + +{{#zone "topCss"}} + {{css "css/custom.css"}} +{{/zone}} + +{{#zone "breadcrumbs"}} +
  • + + + +
  • +
  • + + + Device Types + +
  • +{{/zone}} + +{{#zone "navbarActions"}} + {{#unless isCloud}} +
  • + + + + + + + Create Device Type + +
  • + {{/unless}} +{{/zone}} + +{{#zone "content"}} + {{#if hasDeviceTypes}} +
    + + + Loading device types . . . +
    +
    + +
    + + + + + + + + + + +
    By Device Type Name
    +
    + + + + {{else}} + +
    +
    +

    You Haven't created device types yet.

    +
    Please click "Create a Device Type", if you wish to create a device type. +
    + + + + + + + Create Device Type + +
    +
    + + {{/if}} +{{/zone}} + +{{#zone "bottomJs"}} + + + {{js "js/devicetype-listing.js"}} +{{/zone}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/devicetypes.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/devicetypes.js new file mode 100644 index 0000000000..4fb1980df5 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/devicetypes.js @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2016, 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. + */ + +function onRequest(context) { + var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; + + context["permissions"] = userModule.getUIPermissions(); + if (userModule.isAuthorized("/permission/admin/device-mgt/admin/device-type")) { + context["editPermitted"] = true; + } + var deviceTypeCount = deviceModule.getDeviceTypeCount(); + + if (deviceTypeCount > 0) { + context["hasDeviceTypes"] = true; + } else { + context["hasDeviceTypes"] = false; + } + + return context; +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/devicetypes.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/devicetypes.json new file mode 100644 index 0000000000..4dfd684380 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/devicetypes.json @@ -0,0 +1,5 @@ +{ + "version": "1.0.0", + "uri": "/device-types", + "layout": "cdmf.layout.default" +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/public/css/custom.css b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/public/css/custom.css new file mode 100644 index 0000000000..094068472f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/public/css/custom.css @@ -0,0 +1,3 @@ +#devicetype-table .dataTablesTop{ + Display : none; +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/public/js/devicetype-listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/public/js/devicetype-listing.js new file mode 100644 index 0000000000..6dfe99b268 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/public/js/devicetype-listing.js @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2015, 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. + */ + +var loadDeviceTypeBasedActionURL = function (action, deviceTypeName) { + href = $("#ast-container").data("app-context") + "device-type/" + action + "?type=" + encodeURIComponent(deviceTypeName); + $(location).attr('href', href); +}; + +$(function () { + var sortableElem = '.wr-sortable'; + $(sortableElem).sortable({ + beforeStop: function () { + $(this).sortable('toArray'); + } + }); + $(sortableElem).disableSelection(); +}); + +var apiBasePath = "/api/device-mgt/v1.0"; +var modalPopup = ".modal"; +var modalPopupContainer = modalPopup + " .modal-content"; +var modalPopupContent = modalPopup + " .modal-content"; +var body = "body"; +var isInit = true; +var isCloud = false; + + +/** + * + * Fires the res_text when ever a data table redraw occurs making + * the font icons change the size to respective screen resolution. + * + */ +$(document).on('draw.dt', function () { + $(".icon .text").res_text(0.2); +}); + + +/* + * set popup maximum height function. + */ +function setPopupMaxHeight() { + $(modalPopupContent).css('max-height', ($(body).height() - ($(body).height() / 100 * 30))); + $(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height() / 2))); +} + +/* + * show popup function. + */ +function showPopup() { + $(modalPopup).modal('show'); + //setPopupMaxHeight(); +} + +/* + * hide popup function. + */ +function hidePopup() { + $(modalPopupContent).html(''); + $(modalPopup).modal('hide'); + $('body').removeClass('modal-open').css('padding-right', '0px'); + $('.modal-backdrop').remove(); +} + + +/** + * Following function would execute + * when a user clicks on the list item + * initial mode and with out select mode. + */ +function InitiateViewOption() { + // $(location).attr('href', $(this).data("url")); +} + +function htmlspecialchars(text) { + return jQuery('
    ').text(text).html(); +} + +function loadDeviceTypes() { + var loadingContent = $("#loading-content"); + loadingContent.show(); + + var dataFilter = function (data) { + data = JSON.parse(data); + var objects = []; + $(data).each(function (index) { + objects.push( + { + name: htmlspecialchars(data[index].name), + DT_RowId: "devicetype-" + htmlspecialchars(data[index].name), + metaDefinition: (data[index].deviceTypeMetaDefinition ? true : false) + } + ) + }); + + var json = { + "recordsTotal": data.length, + "recordsFiltered": data.length, + "data": objects + }; + + return JSON.stringify(json); + }; + + //noinspection JSUnusedLocalSymbols + var fnCreatedRow = function (nRow, aData, iDataIndex) { + $(nRow).attr('data-type', 'selectable'); + }; + + //noinspection JSUnusedLocalSymbols + var columns = [ + { + class: "remove-padding content-fill", + data: null, + defaultContent: "
    " + + "" + + "
    " + }, + { + class: "", + data: "name", + render: function (name, type, row, meta) { + return '

    ' + name.replace("devicemgt", "") + '

    '; + } + }, + { + class: "text-right content-fill text-left-on-grid-view no-wrap", + data: null, + render: function (data, type, row, meta) { + var isCloud = false; + if ($('#is-cloud').length > 0) { + isCloud = true; + } + + var innerhtml = ''; + if (data.metaDefinition) { + + var editLink = '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + ''; + + var editEventLink = '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + ''; + + innerhtml = editLink + editEventLink; + } + return innerhtml; + } + } + ]; + + var options = { + "placeholder": "Search By Device Type Name", + "searchKey": "filter", + "searching": false + }; + var settings = { + "sorting": false + }; + var deviceTypeApiUrl = '/api/device-mgt/v1.0/admin/device-types'; + + $('#devicetype-grid').datatables_extended_serverside_paging(settings, deviceTypeApiUrl, dataFilter, columns, fnCreatedRow, null, options); + loadingContent.hide(); + +} + +$(document).ready(function () { + loadDeviceTypes(); +}); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/public/templates/devicetype-listing.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/public/templates/devicetype-listing.hbs new file mode 100644 index 0000000000..6835f28e9c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetypes/public/templates/devicetype-listing.hbs @@ -0,0 +1,44 @@ +{{#each deviceTypes}} + + +
    + +
    + + {{deviceTypeName}} + + + {{#if canEdit}} + + + + + + + + + + + + + + + + + + + + + + + + + {{/if}} + + +{{/each}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.hbs index 94581d56fc..9e6ee54a71 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.hbs @@ -41,7 +41,9 @@