mirror of
https://repository.entgra.net/community/device-mgt-core.git
synced 2025-10-06 02:01:45 +00:00
Merge branch 'master' of https://github.com/wso2/carbon-device-mgt into remote-control
This commit is contained in:
commit
719dd24d57
@ -22,13 +22,13 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Management Annotations</name>
|
||||
<description>WSO2 Carbon - API Management Custom Annotation Module</description>
|
||||
|
||||
@ -21,12 +21,12 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<artifactId>org.wso2.carbon.apimgt.application.extension.api</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<name>WSO2 Carbon - API Application Management API</name>
|
||||
@ -197,6 +197,32 @@
|
||||
<warName>${project.artifactId}</warName>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -22,12 +22,12 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Application Management</name>
|
||||
@ -119,6 +119,32 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
||||
@ -21,13 +21,13 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.apimgt.handlers</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Security Handler Component</name>
|
||||
<description>WSO2 Carbon - API Management Security Handler Module</description>
|
||||
@ -97,6 +97,32 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -13,13 +13,13 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.apimgt.integration.client</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Management Integration Client</name>
|
||||
<description>WSO2 Carbon - API Management Integration Client</description>
|
||||
@ -80,6 +80,32 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -22,22 +22,35 @@ import feign.RequestInterceptor;
|
||||
import org.wso2.carbon.apimgt.integration.client.publisher.PublisherClient;
|
||||
import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService;
|
||||
import org.wso2.carbon.apimgt.integration.client.store.StoreClient;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class IntegrationClientServiceImpl implements IntegrationClientService {
|
||||
|
||||
private static StoreClient storeClient;
|
||||
private static PublisherClient publisherClient;
|
||||
private static Map<String, AccessTokenInfo> tenantUserTokenMap = new HashMap<>();
|
||||
private static IntegrationClientServiceImpl instance;
|
||||
private StoreClient storeClient;
|
||||
private PublisherClient publisherClient;
|
||||
private OAuthRequestInterceptor oAuthRequestInterceptor;
|
||||
|
||||
public IntegrationClientServiceImpl() {
|
||||
RequestInterceptor oAuthRequestInterceptor = new OAuthRequestInterceptor();
|
||||
private IntegrationClientServiceImpl() {
|
||||
oAuthRequestInterceptor = new OAuthRequestInterceptor();
|
||||
storeClient = new StoreClient(oAuthRequestInterceptor);
|
||||
publisherClient = new PublisherClient(oAuthRequestInterceptor);
|
||||
}
|
||||
|
||||
public static IntegrationClientServiceImpl getInstance() {
|
||||
if (instance == null) {
|
||||
synchronized (IntegrationClientService.class) {
|
||||
if (instance == null) {
|
||||
instance = new IntegrationClientServiceImpl();
|
||||
}
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
public void resetUserInfo(String userName, String tenantDomain) {
|
||||
oAuthRequestInterceptor.removeToken(userName, tenantDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public StoreClient getStoreClient() {
|
||||
return storeClient;
|
||||
@ -47,8 +60,4 @@ public class IntegrationClientServiceImpl implements IntegrationClientService {
|
||||
public PublisherClient getPublisherClient() {
|
||||
return publisherClient;
|
||||
}
|
||||
|
||||
public static Map<String, AccessTokenInfo> getTenantUserTokenMap() {
|
||||
return tenantUserTokenMap;
|
||||
}
|
||||
}
|
||||
|
||||
@ -40,6 +40,7 @@ import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientExceptio
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* This is a request interceptor to add oauth token header.
|
||||
@ -55,6 +56,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
|
||||
private static final long DEFAULT_REFRESH_TIME_OFFSET_IN_MILLIS = 100000;
|
||||
private DCRClient dcrClient;
|
||||
private static OAuthApplication oAuthApplication;
|
||||
private static Map<String, AccessTokenInfo> tenantUserTokenMap = new ConcurrentHashMap<>();
|
||||
private static final Log log = LogFactory.getLog(OAuthRequestInterceptor.class);
|
||||
|
||||
/**
|
||||
@ -88,7 +90,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
|
||||
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
|
||||
username = username + "@" + tenantDomain;
|
||||
}
|
||||
AccessTokenInfo tenantBasedAccessTokenInfo = IntegrationClientServiceImpl.getTenantUserTokenMap().get(username);
|
||||
AccessTokenInfo tenantBasedAccessTokenInfo = tenantUserTokenMap.get(username);
|
||||
if ((tenantBasedAccessTokenInfo == null ||
|
||||
((System.currentTimeMillis() + DEFAULT_REFRESH_TIME_OFFSET_IN_MILLIS) >
|
||||
tenantBasedAccessTokenInfo.getExpiresIn()))) {
|
||||
@ -105,7 +107,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
|
||||
}
|
||||
|
||||
if (tenantBasedAccessTokenInfo.getScopes().contains(APIM_SUBSCRIBE_SCOPE)) {
|
||||
IntegrationClientServiceImpl.getTenantUserTokenMap().put(username, tenantBasedAccessTokenInfo);
|
||||
tenantUserTokenMap.put(username, tenantBasedAccessTokenInfo);
|
||||
}
|
||||
|
||||
}
|
||||
@ -118,4 +120,11 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
|
||||
}
|
||||
}
|
||||
|
||||
public void removeToken(String username, String tenantDomain) {
|
||||
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
|
||||
username = username + "@" + tenantDomain;
|
||||
}
|
||||
tenantUserTokenMap.remove(username);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -49,7 +49,7 @@ public class APIIntegrationClientServiceComponent {
|
||||
/* Initializing webapp publisher configuration */
|
||||
APIMConfigReader.init();
|
||||
BundleContext bundleContext = componentContext.getBundleContext();
|
||||
bundleContext.registerService(IntegrationClientService.class.getName(), new IntegrationClientServiceImpl(), null);
|
||||
bundleContext.registerService(IntegrationClientService.class.getName(), IntegrationClientServiceImpl.getInstance(), null);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("apimgt client bundle has been successfully initialized");
|
||||
|
||||
@ -26,6 +26,9 @@ import org.wso2.carbon.apimgt.integration.client.store.StoreClient;
|
||||
*/
|
||||
public interface IntegrationClientService {
|
||||
|
||||
|
||||
void resetUserInfo(String username, String tenantDomain);
|
||||
|
||||
/**
|
||||
*
|
||||
* @return API Store Client.
|
||||
|
||||
@ -13,13 +13,13 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.apimgt.integration.generated.client</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Management Integration Generated Client</name>
|
||||
<description>WSO2 Carbon - API Management Integration Client</description>
|
||||
|
||||
@ -22,13 +22,13 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Management Webapp Publisher</name>
|
||||
<description>WSO2 Carbon - API Management Webapp Publisher</description>
|
||||
@ -172,6 +172,32 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -22,13 +22,13 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>carbon-devicemgt</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>WSO2 Carbon - API Management Extensions Component</name>
|
||||
<url>http://wso2.org</url>
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>certificate-mgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -49,6 +49,32 @@
|
||||
<warName>api#scep-mgt#v1.0</warName>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>certificate-mgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -49,6 +49,32 @@
|
||||
<warName>api#certificate-mgt#v1.0</warName>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -21,13 +21,13 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>certificate-mgt</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - Certificate Management Core</name>
|
||||
<description>WSO2 Carbon - Certificate Management Core</description>
|
||||
@ -94,6 +94,7 @@
|
||||
io.swagger.annotations.*;resolution:=optional,
|
||||
org.wso2.carbon.device.mgt.core.*,
|
||||
org.wso2.carbon.registry.indexing.*,
|
||||
javax.cache.*
|
||||
<!--org.bouncycastle.pkcs.jcajce-->
|
||||
</Import-Package>
|
||||
<Export-Package>
|
||||
@ -118,6 +119,32 @@
|
||||
</suiteXmlFiles>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
@ -0,0 +1,39 @@
|
||||
/*
|
||||
* 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.certificate.mgt.core.cache;
|
||||
|
||||
import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
|
||||
|
||||
/**
|
||||
* This interface for caching the certificates.
|
||||
*/
|
||||
|
||||
public interface CertificateCacheManager {
|
||||
|
||||
void addCertificateBySerial(String serialNumber, CertificateResponse certificate) ;
|
||||
|
||||
void addCertificateByCN(String commonName, CertificateResponse certificate) ;
|
||||
|
||||
CertificateResponse getCertificateBySerial(String serialNumber) ;
|
||||
|
||||
CertificateResponse getCertificateByCN(String commonName) ;
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,132 @@
|
||||
/*
|
||||
* 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.certificate.mgt.core.cache.impl;
|
||||
|
||||
import org.wso2.carbon.certificate.mgt.core.cache.CertificateCacheManager;
|
||||
import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
|
||||
|
||||
import javax.cache.Cache;
|
||||
import javax.cache.CacheConfiguration;
|
||||
import javax.cache.CacheManager;
|
||||
import javax.cache.Caching;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class CertificateCacheManagerImpl implements CertificateCacheManager {
|
||||
|
||||
public static final String CERTIFICATE_CACHE_MANAGER = "CERTIFICATE_CACHE_MANAGER";
|
||||
public static final String CERTIFICATE_CACHE = "CERTIFICATE_CACHE";
|
||||
private static boolean isCertificateCacheInitialized = false;
|
||||
private static String SERIAL_PRE = "S_";
|
||||
private static String COMMON_NAME_PRE = "C_";
|
||||
|
||||
private static CertificateCacheManager certificateCacheManager;
|
||||
|
||||
|
||||
private CertificateCacheManagerImpl() {
|
||||
}
|
||||
|
||||
public static CertificateCacheManager getInstance() {
|
||||
if (certificateCacheManager == null) {
|
||||
synchronized (CertificateCacheManagerImpl.class) {
|
||||
if (certificateCacheManager == null) {
|
||||
certificateCacheManager = new CertificateCacheManagerImpl();
|
||||
}
|
||||
}
|
||||
}
|
||||
return certificateCacheManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCertificateBySerial(String serialNumber, CertificateResponse certificate) {
|
||||
CertificateCacheManagerImpl.getCertificateCache().put(SERIAL_PRE + serialNumber, certificate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCertificateByCN(String commonName, CertificateResponse certificate) {
|
||||
CertificateCacheManagerImpl.getCertificateCache().put(COMMON_NAME_PRE + commonName, certificate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CertificateResponse getCertificateBySerial(String serialNumber) {
|
||||
return CertificateCacheManagerImpl.getCertificateCache().get(SERIAL_PRE + serialNumber);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CertificateResponse getCertificateByCN(String commonName) {
|
||||
return CertificateCacheManagerImpl.getCertificateCache().get(COMMON_NAME_PRE + commonName);
|
||||
}
|
||||
|
||||
|
||||
private static CacheManager getCacheManager() {
|
||||
return Caching.getCacheManagerFactory().getCacheManager(CertificateCacheManagerImpl.CERTIFICATE_CACHE_MANAGER);
|
||||
}
|
||||
|
||||
public static Cache<String, CertificateResponse> getCertificateCache() {
|
||||
DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
|
||||
CacheManager manager = getCacheManager();
|
||||
Cache<String, CertificateResponse> certificateCache = null;
|
||||
if (config.getDeviceCacheConfiguration().isEnabled()) {
|
||||
if (!isCertificateCacheInitialized) {
|
||||
initializeCertificateCache();
|
||||
}
|
||||
if (manager != null) {
|
||||
certificateCache = manager.<String, CertificateResponse>getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
|
||||
} else {
|
||||
certificateCache = Caching.getCacheManager(CertificateCacheManagerImpl.CERTIFICATE_CACHE_MANAGER).
|
||||
<String, CertificateResponse>getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
|
||||
}
|
||||
}
|
||||
return certificateCache;
|
||||
}
|
||||
|
||||
public static void initializeCertificateCache() {
|
||||
DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
|
||||
int certificateCacheExpiry = config.getCertificateCacheConfiguration().getExpiryTime();
|
||||
CacheManager manager = getCacheManager();
|
||||
if (config.getCertificateCacheConfiguration().isEnabled()) {
|
||||
if (!isCertificateCacheInitialized) {
|
||||
isCertificateCacheInitialized = true;
|
||||
if (manager != null) {
|
||||
if (certificateCacheExpiry > 0) {
|
||||
manager.<String, CertificateResponse>createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE).
|
||||
setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
|
||||
certificateCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
|
||||
Duration(TimeUnit.SECONDS, certificateCacheExpiry)).setStoreByValue(true).build();
|
||||
} else {
|
||||
manager.<String, CertificateResponse>getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
|
||||
}
|
||||
} else {
|
||||
if (certificateCacheExpiry > 0) {
|
||||
Caching.getCacheManager().
|
||||
<String, CertificateResponse>createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE).
|
||||
setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
|
||||
certificateCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
|
||||
Duration(TimeUnit.SECONDS, certificateCacheExpiry)).setStoreByValue(true).build();
|
||||
} else {
|
||||
Caching.getCacheManager().<String, CertificateResponse>getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -19,6 +19,8 @@ package org.wso2.carbon.certificate.mgt.core.impl;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.certificate.mgt.core.cache.CertificateCacheManager;
|
||||
import org.wso2.carbon.certificate.mgt.core.cache.impl.CertificateCacheManagerImpl;
|
||||
import org.wso2.carbon.certificate.mgt.core.config.CertificateConfigurationManager;
|
||||
import org.wso2.carbon.certificate.mgt.core.config.CertificateKeystoreConfig;
|
||||
import org.wso2.carbon.certificate.mgt.core.dao.CertificateDAO;
|
||||
@ -275,29 +277,37 @@ public class KeyStoreReader {
|
||||
|
||||
public CertificateResponse getCertificateBySerial(String serialNumber) throws KeystoreException {
|
||||
CertificateResponse certificateResponse = null;
|
||||
try {
|
||||
CertificateCacheManager cacheManager = CertificateCacheManagerImpl.getInstance();
|
||||
certificateResponse = cacheManager.getCertificateBySerial(serialNumber);
|
||||
if (certificateResponse == null) {
|
||||
try {
|
||||
CertificateManagementDAOFactory.openConnection();
|
||||
certificateResponse = certDao.retrieveCertificate(serialNumber);
|
||||
} catch (SQLException e) {
|
||||
String errorMsg = "Error when making a connection to the database.";
|
||||
throw new KeystoreException(errorMsg, e);
|
||||
} finally {
|
||||
CertificateManagementDAOFactory.closeConnection();
|
||||
}
|
||||
if (certificateResponse != null && certificateResponse.getCertificate() != null) {
|
||||
Certificate certificate = (Certificate) Serializer.deserialize(certificateResponse.getCertificate());
|
||||
if (certificate instanceof X509Certificate) {
|
||||
X509Certificate x509cert = (X509Certificate) certificate;
|
||||
String commonName = CertificateGenerator.getCommonName(x509cert);
|
||||
certificateResponse.setCommonName(commonName);
|
||||
cacheManager.addCertificateBySerial(serialNumber, certificateResponse);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (CertificateManagementDAOException e) {
|
||||
String errorMsg = "Error when retrieving certificate from the the database for the serial number: " +
|
||||
serialNumber;
|
||||
throw new KeystoreException(errorMsg, e);
|
||||
} catch (SQLException e) {
|
||||
String errorMsg = "Error when making a connection to the database.";
|
||||
throw new KeystoreException(errorMsg, e);
|
||||
|
||||
} catch (ClassNotFoundException | IOException e) {
|
||||
String errorMsg = "Error when de-serializing saved certificate.";
|
||||
throw new KeystoreException(errorMsg, e);
|
||||
} finally {
|
||||
CertificateManagementDAOFactory.closeConnection();
|
||||
}
|
||||
return certificateResponse;
|
||||
}
|
||||
|
||||
@ -22,14 +22,14 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>carbon-devicemgt</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>certificate-mgt</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>WSO2 Carbon - Certificate Management Component</name>
|
||||
<url>http://wso2.org</url>
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -128,6 +128,32 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -50,10 +50,6 @@
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi.services</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi.services</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.policy.mgt.core</artifactId>
|
||||
@ -94,6 +90,32 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -145,6 +145,32 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -141,6 +141,32 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -150,6 +150,32 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -149,6 +149,32 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>carbon-devicemgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>device-mgt</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -79,6 +79,32 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>device-mgt</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -131,6 +131,33 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -49,6 +49,32 @@
|
||||
<warName>api#device-mgt#v1.0</warName>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
@ -326,16 +352,6 @@
|
||||
<artifactId>org.wso2.carbon.identity.user.store.count</artifactId>
|
||||
<version>${carbon.identity.framework.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics</groupId>
|
||||
<artifactId>org.wso2.carbon.analytics.datasource.commons</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics</groupId>
|
||||
<artifactId>org.wso2.carbon.analytics.api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics</groupId>
|
||||
|
||||
@ -0,0 +1,54 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
@ApiModel(value = "BasicUserInfoWrapper", description = "This contains basic details of a set of users that matches " +
|
||||
"a given criteria as a collection and a message if there's any.")
|
||||
public class BasicUserInfoWrapper {
|
||||
|
||||
@ApiModelProperty(
|
||||
name = "basicUserInfo",
|
||||
value = "Details of the User.",
|
||||
required = true)
|
||||
private BasicUserInfo basicUserInfo;
|
||||
|
||||
@ApiModelProperty(
|
||||
name = "message",
|
||||
value = "Response message if there's any.")
|
||||
private String message;
|
||||
|
||||
public BasicUserInfo getBasicUserInfo() {
|
||||
return basicUserInfo;
|
||||
}
|
||||
|
||||
public void setBasicUserInfo(BasicUserInfo basicUserInfo) {
|
||||
this.basicUserInfo = basicUserInfo;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
@ -32,10 +32,10 @@ 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.device.details.DeviceInfo;
|
||||
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;
|
||||
@ -43,7 +43,6 @@ 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;
|
||||
|
||||
@ -61,7 +60,6 @@ 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.
|
||||
@ -380,7 +378,8 @@ public interface DeviceManagementService {
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Getting Details of a Device",
|
||||
notes = "Get the details of a device by specifying the device type and device identifier.",
|
||||
notes = "Get the details of a device by specifying the device type and device identifier and optionally " +
|
||||
"the owner.",
|
||||
tags = "Device Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ -440,6 +439,13 @@ public interface DeviceManagementService {
|
||||
@PathParam("id")
|
||||
@Size(max = 45)
|
||||
String id,
|
||||
@ApiParam(
|
||||
name = "owner",
|
||||
value = "The owner of the device you want ot get details.",
|
||||
required = false)
|
||||
@QueryParam("owner")
|
||||
@Size(max = 100)
|
||||
String owner,
|
||||
@ApiParam(
|
||||
name = "If-Modified-Since",
|
||||
value = "Checks if the requested variant was modified, since the specified date-time. \n" +
|
||||
@ -523,7 +529,7 @@ public interface DeviceManagementService {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully fetched the location details of the device.",
|
||||
response = Device.class,
|
||||
response = Device.class, //TODO, This should be DeviceLocation.class
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
@ -580,6 +586,82 @@ public interface DeviceManagementService {
|
||||
String ifModifiedSince);
|
||||
|
||||
|
||||
|
||||
@GET
|
||||
@Path("/{type}/{id}/info")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Getting the information of a Device",
|
||||
notes = "Get the information of a device by specifying the device type and device identifier.",
|
||||
tags = "Device Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully fetched the information of the device.",
|
||||
response = DeviceInfo.class,
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@ResponseHeader(
|
||||
name = "Last-Modified",
|
||||
description = "Date and time the resource was last modified.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. Empty body because the client already has the latest version" +
|
||||
" of the requested resource.\n"),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid request or validation error.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found. \n Location data for the specified device was not found.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n " +
|
||||
"Server error occurred while retrieving the device details.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response getDeviceInformation(
|
||||
@ApiParam(
|
||||
name = "type",
|
||||
value = "The device type name, such as ios, android, windows or fire-alarm.",
|
||||
required = true)
|
||||
@PathParam("type")
|
||||
@Size(max = 45)
|
||||
String type,
|
||||
@ApiParam(
|
||||
name = "id",
|
||||
value = "The device identifier of the device you want ot get details.",
|
||||
required = true)
|
||||
@PathParam("id")
|
||||
@Size(max = 45)
|
||||
String id,
|
||||
@ApiParam(
|
||||
name = "If-Modified-Since",
|
||||
value = "Checks if the requested variant was modified, since the specified date-time. \n" +
|
||||
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z. \n" +
|
||||
"Example: Mon, 05 Jan 2014 15:10:00 +0200",
|
||||
required = false)
|
||||
@HeaderParam("If-Modified-Since")
|
||||
String ifModifiedSince);
|
||||
|
||||
//device rename request would looks like follows
|
||||
//POST devices/type/virtual_firealarm/id/us06ww93auzp/rename
|
||||
@POST
|
||||
|
||||
@ -29,6 +29,7 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.api.ActivityInfoProviderService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
|
||||
import javax.validation.constraints.Size;
|
||||
import javax.ws.rs.*;
|
||||
@ -54,6 +55,8 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
|
||||
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
|
||||
Activity activity;
|
||||
DeviceManagementProviderService dmService;
|
||||
Response response = validateAdminUser();
|
||||
if (response == null) {
|
||||
try {
|
||||
RequestValidationUtil.validateActivityId(id);
|
||||
|
||||
@ -71,6 +74,9 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
|
||||
return Response.serverError().entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
|
||||
}
|
||||
} else {
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -120,7 +126,6 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
|
||||
long sinceTimestamp;
|
||||
long timestamp = 0;
|
||||
boolean isIfModifiedSinceSet = false;
|
||||
boolean isSinceSet = false;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("getActivities since: " + since + " , offset: " + offset + " ,limit: " + limit + " ," +
|
||||
"ifModifiedSince: " + ifModifiedSince);
|
||||
@ -150,7 +155,6 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
|
||||
"Invalid date string is provided in 'since' filter").build()).build();
|
||||
}
|
||||
sinceTimestamp = sinceDate.getTime();
|
||||
isSinceSet = true;
|
||||
timestamp = sinceTimestamp / 1000;
|
||||
}
|
||||
|
||||
@ -162,7 +166,8 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("getActivities final timestamp " + timestamp);
|
||||
}
|
||||
|
||||
Response response = validateAdminUser();
|
||||
if (response == null) {
|
||||
List<Activity> activities;
|
||||
ActivityList activityList = new ActivityList();
|
||||
DeviceManagementProviderService dmService;
|
||||
@ -194,6 +199,24 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
|
||||
return Response.serverError().entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
|
||||
}
|
||||
} else {
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
private Response validateAdminUser(){
|
||||
try {
|
||||
if (!DeviceMgtAPIUtils.isAdmin()) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED).entity("Unauthorized operation! Only admin role can perform " +
|
||||
"this operation.").build();
|
||||
}
|
||||
return null;
|
||||
} catch (UserStoreException e) {
|
||||
String msg
|
||||
= "Error occurred while validating the user have admin role!";
|
||||
log.error(msg, e);
|
||||
return Response.serverError().entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -36,6 +36,7 @@ import org.wso2.carbon.device.mgt.common.app.mgt.Application;
|
||||
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
|
||||
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
|
||||
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
|
||||
@ -354,6 +355,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
public Response getDevice(
|
||||
@PathParam("type") @Size(max = 45) String type,
|
||||
@PathParam("id") @Size(max = 45) String id,
|
||||
@QueryParam("owner") @Size(max = 100) String owner,
|
||||
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
|
||||
Device device = null;
|
||||
try {
|
||||
@ -367,14 +369,14 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, type);
|
||||
// check whether the user is authorized
|
||||
if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, authorizedUser)) {
|
||||
String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" + id;
|
||||
String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" + id + "'";
|
||||
log.error(msg);
|
||||
return Response.status(Response.Status.UNAUTHORIZED).entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage(msg).build()).build();
|
||||
}
|
||||
|
||||
Date sinceDate = null;
|
||||
if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
|
||||
Date sinceDate;
|
||||
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
|
||||
try {
|
||||
sinceDate = format.parse(ifModifiedSince);
|
||||
@ -383,6 +385,28 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage("Invalid date " +
|
||||
"string is provided in 'If-Modified-Since' header").build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
if (!StringUtils.isEmpty(owner)) {
|
||||
if (authorizedUser.equalsIgnoreCase(owner) || deviceAccessAuthorizationService.isDeviceAdminUser()) {
|
||||
if (sinceDate != null) {
|
||||
device = dms.getDevice(new DeviceIdentifier(id, type), owner, sinceDate, true);
|
||||
if (device == null) {
|
||||
return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " +
|
||||
"after the timestamp provided in 'If-Modified-Since' header").build();
|
||||
}
|
||||
} else {
|
||||
device = dms.getDevice(new DeviceIdentifier(id, type), owner, true);
|
||||
}
|
||||
} else {
|
||||
String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" + id +
|
||||
"' which belongs to user '" + owner + "'";
|
||||
log.error(msg);
|
||||
return Response.status(Response.Status.UNAUTHORIZED).entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage(msg).build()).build();
|
||||
}
|
||||
} else if (deviceAccessAuthorizationService.isDeviceAdminUser()) {
|
||||
if (sinceDate != null) {
|
||||
device = dms.getDevice(new DeviceIdentifier(id, type), sinceDate);
|
||||
if (device == null) {
|
||||
return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " +
|
||||
@ -391,6 +415,18 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
} else {
|
||||
device = dms.getDevice(new DeviceIdentifier(id, type));
|
||||
}
|
||||
} else {
|
||||
owner = authorizedUser;
|
||||
if (sinceDate != null) {
|
||||
device = dms.getDevice(new DeviceIdentifier(id, type), owner, sinceDate, true);
|
||||
if (device == null) {
|
||||
return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " +
|
||||
"after the timestamp provided in 'If-Modified-Since' header").build();
|
||||
}
|
||||
} else {
|
||||
device = dms.getDevice(new DeviceIdentifier(id, type), owner, true);
|
||||
}
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while fetching the device information.";
|
||||
log.error(msg, e);
|
||||
@ -436,6 +472,33 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
|
||||
}
|
||||
|
||||
|
||||
@GET
|
||||
@Path("/{type}/{id}/info")
|
||||
@Override
|
||||
public Response getDeviceInformation(
|
||||
@PathParam("type") @Size(max = 45) String type,
|
||||
@PathParam("id") @Size(max = 45) String id,
|
||||
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
|
||||
DeviceInformationManager informationManager;
|
||||
DeviceInfo deviceInfo;
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(id);
|
||||
deviceIdentifier.setType(type);
|
||||
informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
|
||||
deviceInfo = informationManager.getDeviceInfo(deviceIdentifier);
|
||||
|
||||
} catch (DeviceDetailsMgtException e) {
|
||||
String msg = "Error occurred while getting the device information of id : " + id + " type : " + type ;
|
||||
log.error(msg, e);
|
||||
return Response.serverError().entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
|
||||
}
|
||||
return Response.status(Response.Status.OK).entity(deviceInfo).build();
|
||||
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{type}/{id}/features")
|
||||
@Override
|
||||
|
||||
@ -33,6 +33,7 @@ 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.GroupNotExistException;
|
||||
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
|
||||
@ -109,7 +110,7 @@ public class GroupManagementServiceImpl implements GroupManagementService {
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
} catch (GroupAlreadyExistException e) {
|
||||
String msg = "Group already exists with name '" + group.getName() + "'.";
|
||||
String msg = "Group already exists with name " + group.getName() + ".";
|
||||
log.warn(msg);
|
||||
return Response.status(Response.Status.CONFLICT).entity(msg).build();
|
||||
}
|
||||
@ -144,7 +145,7 @@ public class GroupManagementServiceImpl implements GroupManagementService {
|
||||
String msg = "Error occurred while adding new group.";
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
} catch (GroupAlreadyExistException e) {
|
||||
} catch (GroupNotExistException e) {
|
||||
String msg = "There is another group already exists with name '" + deviceGroup.getName() + "'.";
|
||||
log.warn(msg);
|
||||
return Response.status(Response.Status.CONFLICT).entity(msg).build();
|
||||
|
||||
@ -30,6 +30,7 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.api.RoleManagementService;
|
||||
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.Constants;
|
||||
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;
|
||||
@ -68,6 +69,9 @@ public class RoleManagementServiceImpl implements RoleManagementService {
|
||||
@HeaderParam("If-Modified-Since") String ifModifiedSince,
|
||||
@QueryParam("offset") int offset, @QueryParam("limit") int limit) {
|
||||
RequestValidationUtil.validatePaginationParameters(offset, limit);
|
||||
if (limit == 0){
|
||||
limit = Constants.DEFAULT_PAGE_LIMIT;
|
||||
}
|
||||
List<String> filteredRoles;
|
||||
RoleList targetRoles = new RoleList();
|
||||
|
||||
|
||||
@ -25,11 +25,13 @@ 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.common.configuration.mgt.ConfigurationManagementException;
|
||||
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;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.BasicUserInfo;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.BasicUserInfoList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.BasicUserInfoWrapper;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentInvitation;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper;
|
||||
@ -155,10 +157,18 @@ public class UserManagementServiceImpl implements UserManagementService {
|
||||
props.setProperty("password", initialUserPassword);
|
||||
|
||||
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
|
||||
BasicUserInfoWrapper userInfoWrapper = new BasicUserInfoWrapper();
|
||||
String message;
|
||||
try {
|
||||
dms.sendRegistrationEmail(metaInfo);
|
||||
return Response.created(new URI(API_BASE_PATH + "/" + URIEncoder.encode(userInfo.getUsername(), "UTF-8")))
|
||||
.entity(
|
||||
createdUserInfo).build();
|
||||
message = "An invitation mail will be sent to this user to initiate device enrollment.";
|
||||
} catch (ConfigurationManagementException e) {
|
||||
message = "Mail Server is not configured. Email invitation will not be sent.";
|
||||
}
|
||||
userInfoWrapper.setBasicUserInfo(createdUserInfo);
|
||||
userInfoWrapper.setMessage(message);
|
||||
return Response.created(new URI(API_BASE_PATH + "/" + URIEncoder.encode(userInfo.getUsername(),
|
||||
"UTF-8"))).entity(userInfoWrapper).build();
|
||||
} catch (UserStoreException e) {
|
||||
String msg = "Error occurred while trying to add user '" + userInfo.getUsername() + "' to the " +
|
||||
"underlying user management system";
|
||||
@ -178,8 +188,7 @@ public class UserManagementServiceImpl implements UserManagementService {
|
||||
return Response.serverError().entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while sending registration email to the user " +
|
||||
userInfo.getUsername();
|
||||
String msg = "Error occurred while sending registration email to the user " + userInfo.getUsername();
|
||||
log.error(msg, e);
|
||||
return Response.serverError().entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
|
||||
@ -363,7 +372,9 @@ public class UserManagementServiceImpl implements UserManagementService {
|
||||
}
|
||||
|
||||
RequestValidationUtil.validatePaginationParameters(offset, limit);
|
||||
|
||||
if (limit == 0) {
|
||||
limit = Constants.DEFAULT_PAGE_LIMIT;
|
||||
}
|
||||
List<BasicUserInfo> userList, offsetList;
|
||||
String appliedFilter = ((filter == null) || filter.isEmpty() ? "*" : filter + "*");
|
||||
// to get whole set of users, appliedLimit is set to -1
|
||||
@ -473,7 +484,8 @@ public class UserManagementServiceImpl implements UserManagementService {
|
||||
|
||||
@GET
|
||||
@Path("/checkUser")
|
||||
@Override public Response isUserExists(@QueryParam("username") String userName) {
|
||||
@Override
|
||||
public Response isUserExists(@QueryParam("username") String userName) {
|
||||
try {
|
||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||
boolean userExists = false;
|
||||
@ -503,14 +515,17 @@ public class UserManagementServiceImpl implements UserManagementService {
|
||||
if (domain != null && !domain.isEmpty()) {
|
||||
userStoreDomain = domain;
|
||||
}
|
||||
if (limit == 0){
|
||||
//If there is no limit is passed, then return all.
|
||||
limit = -1;
|
||||
}
|
||||
List<UserInfo> userList;
|
||||
try {
|
||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||
String[] users = userStoreManager.listUsers(userStoreDomain + "/*", -1);
|
||||
String[] users = userStoreManager.listUsers(userStoreDomain + "/" + filter + "*", limit);
|
||||
userList = new ArrayList<>();
|
||||
UserInfo user;
|
||||
for (String username : users) {
|
||||
if (username.contains(filter)) {
|
||||
user = new UserInfo();
|
||||
user.setUsername(username);
|
||||
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
|
||||
@ -518,7 +533,6 @@ public class UserManagementServiceImpl implements UserManagementService {
|
||||
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
|
||||
userList.add(user);
|
||||
}
|
||||
}
|
||||
return Response.status(Response.Status.OK).entity(userList).build();
|
||||
} catch (UserStoreException e) {
|
||||
String msg = "Error occurred while retrieving the list of users using the filter : " + filter;
|
||||
@ -573,6 +587,10 @@ public class UserManagementServiceImpl implements UserManagementService {
|
||||
log.error(msg, e);
|
||||
return Response.serverError().entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
|
||||
} catch (ConfigurationManagementException e) {
|
||||
String msg = "Error occurred while sending the email invitations. Mail server not configured.";
|
||||
return Response.serverError().entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
|
||||
}
|
||||
return Response.status(Response.Status.OK).entity("Invitation mails have been sent.").build();
|
||||
}
|
||||
@ -608,6 +626,10 @@ public class UserManagementServiceImpl implements UserManagementService {
|
||||
log.error(msg, e);
|
||||
return Response.serverError().entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
|
||||
} catch (ConfigurationManagementException e) {
|
||||
String msg = "Error occurred while sending the email invitations. Mail server not configured.";
|
||||
return Response.serverError().entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
|
||||
}
|
||||
return Response.status(Response.Status.OK).entity("Invitation mails have been sent.").build();
|
||||
}
|
||||
|
||||
@ -21,11 +21,8 @@ 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.GroupPaginationRequest;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
|
||||
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.GroupManagementAdminService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
|
||||
@ -33,7 +30,6 @@ import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class GroupManagementAdminServiceImpl implements GroupManagementAdminService {
|
||||
|
||||
|
||||
@ -30,6 +30,7 @@ public class Constants {
|
||||
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 static final int DEFAULT_PAGE_LIMIT = 50;
|
||||
|
||||
|
||||
public final class ErrorMessages {
|
||||
|
||||
@ -20,8 +20,6 @@ package org.wso2.carbon.device.mgt.jaxrs.util;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.apimgt.integration.client.IntegrationClientServiceImpl;
|
||||
import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
@ -66,9 +64,8 @@ public class CredentialManagementResponseBuilder {
|
||||
username = CarbonContext.getThreadLocalCarbonContext().getUsername();
|
||||
userStoreManager.updateCredential(username, credentials.getNewPassword(),
|
||||
credentials.getOldPassword());
|
||||
IntegrationClientServiceImpl integrationClientService = (IntegrationClientServiceImpl) PrivilegedCarbonContext.
|
||||
getThreadLocalCarbonContext().getOSGiService(IntegrationClientService.class, null);
|
||||
integrationClientService.getTenantUserTokenMap().remove(username);
|
||||
DeviceMgtAPIUtils.getIntegrationClientService().resetUserInfo(username,
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
|
||||
return Response.status(Response.Status.OK).entity("UserImpl password by username: " +
|
||||
username + " was successfully changed.").build();
|
||||
} catch (UserStoreException e) {
|
||||
@ -111,6 +108,8 @@ public class CredentialManagementResponseBuilder {
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(errorMsg).build()).build();
|
||||
}
|
||||
userStoreManager.updateCredentialByAdmin(username, credentials.getNewPassword());
|
||||
DeviceMgtAPIUtils.getIntegrationClientService().resetUserInfo(username,
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
|
||||
return Response.status(Response.Status.OK).entity("UserImpl password by username: " +
|
||||
username + " was successfully changed.").build();
|
||||
} catch (UserStoreException e) {
|
||||
|
||||
@ -29,6 +29,7 @@ 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.apimgt.integration.client.service.IntegrationClientService;
|
||||
import org.wso2.carbon.base.ServerConfiguration;
|
||||
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
@ -128,6 +129,8 @@ public class DeviceMgtAPIUtils {
|
||||
private static KeyStore trustStore;
|
||||
private static char[] keyStorePassword;
|
||||
|
||||
private static IntegrationClientService integrationClientService;
|
||||
|
||||
static {
|
||||
String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
|
||||
String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty(
|
||||
@ -297,6 +300,23 @@ public class DeviceMgtAPIUtils {
|
||||
return realmService;
|
||||
}
|
||||
|
||||
public static IntegrationClientService getIntegrationClientService() {
|
||||
if (integrationClientService == null) {
|
||||
synchronized (DeviceMgtAPIUtils.class) {
|
||||
if (integrationClientService == null) {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
integrationClientService = (IntegrationClientService) ctx.getOSGiService(IntegrationClientService.class, null);
|
||||
if (integrationClientService == null) {
|
||||
String msg = "IntegrationClientService is not initialized";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return integrationClientService;
|
||||
}
|
||||
|
||||
public static RegistryService getRegistryService() {
|
||||
RegistryService registryService;
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
@ -617,6 +637,7 @@ public class DeviceMgtAPIUtils {
|
||||
|
||||
/**
|
||||
* This method is used to create the Cache that holds the event definition of the device type..
|
||||
*
|
||||
* @return Cachemanager
|
||||
*/
|
||||
public static synchronized Cache<String, EventAttributeList> getDynamicEventCache() {
|
||||
@ -681,4 +702,18 @@ public class DeviceMgtAPIUtils {
|
||||
SSLContext.setDefault(sslContext);
|
||||
}
|
||||
|
||||
|
||||
public static boolean isAdmin() throws UserStoreException {
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
|
||||
UserRealm realmService = DeviceMgtAPIUtils.getRealmService().getTenantUserRealm(tenantId);
|
||||
String adminRoleName = realmService.getRealmConfiguration().getAdminRoleName();
|
||||
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
|
||||
String[] roles = realmService.getUserStoreManager().getRoleListOfUser(userName);
|
||||
for (String role: roles){
|
||||
if (role != null && role.equals(adminRoleName)){
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@ -21,7 +21,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -56,6 +56,32 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -0,0 +1,55 @@
|
||||
/*
|
||||
* 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.group.mgt;
|
||||
|
||||
public class GroupNotExistException extends Exception{
|
||||
|
||||
private String errorMessage;
|
||||
|
||||
public GroupNotExistException(String msg, Exception nestedEx) {
|
||||
super(msg, nestedEx);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public GroupNotExistException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
setErrorMessage(message);
|
||||
}
|
||||
|
||||
public GroupNotExistException(String msg) {
|
||||
super(msg);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public GroupNotExistException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GroupNotExistException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
public void setErrorMessage(String errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
}
|
||||
@ -63,7 +63,8 @@ public interface OperationManager {
|
||||
* @throws OperationManagementException If some unusual behaviour is observed while fetching the
|
||||
* operation list.
|
||||
*/
|
||||
PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request) throws OperationManagementException;
|
||||
PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request)
|
||||
throws OperationManagementException;
|
||||
|
||||
/**
|
||||
* Method to retrieve the list of available operations to a device.
|
||||
@ -73,15 +74,12 @@ public interface OperationManager {
|
||||
* @throws OperationManagementException If some unusual behaviour is observed while fetching the
|
||||
* operation list.
|
||||
*/
|
||||
List<? extends Operation> getPendingOperations(
|
||||
DeviceIdentifier deviceId) throws OperationManagementException;
|
||||
List<? extends Operation> getPendingOperations(DeviceIdentifier deviceId) throws OperationManagementException;
|
||||
|
||||
Operation getNextPendingOperation(DeviceIdentifier deviceId) throws OperationManagementException;
|
||||
|
||||
void updateOperation(DeviceIdentifier deviceId, Operation operation) throws OperationManagementException;
|
||||
|
||||
void deleteOperation(int operationId) throws OperationManagementException;
|
||||
|
||||
Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId)
|
||||
throws OperationManagementException;
|
||||
|
||||
@ -93,22 +91,13 @@ public interface OperationManager {
|
||||
|
||||
Activity getOperationByActivityId(String activity) throws OperationManagementException;
|
||||
|
||||
Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) throws OperationManagementException;
|
||||
|
||||
List<Operation> getOperationUpdatedAfter(long timestamp) throws OperationManagementException;
|
||||
|
||||
List<Activity> getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException;
|
||||
Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId)
|
||||
throws OperationManagementException;
|
||||
|
||||
List<Activity> getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementException;
|
||||
|
||||
int getActivityCountUpdatedAfter(long timestamp) throws OperationManagementException;
|
||||
|
||||
/**
|
||||
* Operation manger implementation can have a push notification stratergy
|
||||
* @param notificationStrategy eg: mqtt/xmpp
|
||||
*/
|
||||
void setNotificationStrategy(NotificationStrategy notificationStrategy);
|
||||
|
||||
/**
|
||||
* retrive the push notification strategy.
|
||||
* @return NotificationStrategy
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>device-mgt</artifactId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -39,6 +39,32 @@
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
@ -137,6 +163,11 @@
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-api-mockito</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
|
||||
@ -195,6 +226,11 @@
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-module-testng</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.user.core</artifactId>
|
||||
|
||||
@ -350,7 +350,9 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
|
||||
if (deviceStatusTaskPluginConfig != null && deviceStatusTaskPluginConfig.isRequireStatusMonitoring()) {
|
||||
try {
|
||||
DeviceManagementDataHolder.getInstance().removeDeviceStatusTaskPluginConfig(deviceType);
|
||||
if (deviceStatusTaskManagerService != null) {
|
||||
deviceStatusTaskManagerService.stopTask(deviceType, deviceStatusTaskPluginConfig);
|
||||
}
|
||||
} catch (DeviceStatusTaskException e) {
|
||||
throw new DeviceManagementException("Error occurred while stopping Device Status task service for '" +
|
||||
deviceManagementService.getType() + "'", e);
|
||||
|
||||
@ -20,11 +20,10 @@ package org.wso2.carbon.device.mgt.core.authorization;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.CarbonConstants;
|
||||
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.authorization.DeviceAccessAuthorizationException;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAuthorizationResult;
|
||||
@ -36,11 +35,9 @@ import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils;
|
||||
import org.wso2.carbon.user.api.UserRealm;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* Implementation of DeviceAccessAuthorization service.
|
||||
@ -233,7 +230,7 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori
|
||||
return userRealm.getAuthorizationManager()
|
||||
.isUserAuthorized(removeTenantDomain(username),
|
||||
PermissionUtils.getAbsolutePermissionPath(CDM_ADMIN_PERMISSION),
|
||||
PermissionMethod.UI_EXECUTE);
|
||||
CarbonConstants.UI_PERMISSION_ACTION);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@ -265,22 +262,6 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori
|
||||
return PermissionUtils.putPermission(permission);
|
||||
}
|
||||
|
||||
private Map<String, String> getOwnershipOfDevices(List<Device> devices) {
|
||||
Map<String, String> ownershipData = new HashMap<>();
|
||||
EnrolmentInfo enrolmentInfo;
|
||||
String owner;
|
||||
for (Device device : devices) {
|
||||
enrolmentInfo = device.getEnrolmentInfo();
|
||||
if (enrolmentInfo != null) {
|
||||
owner = enrolmentInfo.getOwner();
|
||||
if (owner != null && !owner.isEmpty()) {
|
||||
ownershipData.put(device.getDeviceIdentifier(), owner);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ownershipData;
|
||||
}
|
||||
|
||||
public static final class PermissionMethod {
|
||||
public static final String READ = "read";
|
||||
public static final String WRITE = "write";
|
||||
|
||||
@ -57,9 +57,9 @@ public class DeviceConfigurationManager {
|
||||
return deviceConfigManager;
|
||||
}
|
||||
|
||||
public synchronized void initConfig() throws DeviceManagementException {
|
||||
public synchronized void initConfig(String configLocation) throws DeviceManagementException {
|
||||
try {
|
||||
File deviceMgtConfig = new File(DeviceConfigurationManager.DEVICE_MGT_CONFIG_PATH);
|
||||
File deviceMgtConfig = new File(configLocation);
|
||||
Document doc = DeviceManagerUtil.convertToDocument(deviceMgtConfig);
|
||||
|
||||
/* Un-marshaling Device Management configuration */
|
||||
@ -72,15 +72,8 @@ public class DeviceConfigurationManager {
|
||||
}
|
||||
}
|
||||
|
||||
private static Schema getSchema() throws DeviceManagementException {
|
||||
try {
|
||||
File deviceManagementSchemaConfig = new File(DeviceConfigurationManager.DEVICE_MGT_CONFIG_SCHEMA_PATH);
|
||||
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
|
||||
return factory.newSchema(deviceManagementSchemaConfig);
|
||||
} catch (SAXException e) {
|
||||
throw new DeviceManagementException("Error occurred while initializing the schema of " +
|
||||
"device-mgt-config.xml", e);
|
||||
}
|
||||
public void initConfig() throws DeviceManagementException {
|
||||
this.initConfig(DEVICE_MGT_CONFIG_PATH);
|
||||
}
|
||||
|
||||
public DeviceManagementConfig getDeviceManagementConfig() {
|
||||
|
||||
@ -17,6 +17,7 @@
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.core.config;
|
||||
|
||||
import org.wso2.carbon.device.mgt.core.config.cache.CertificateCacheConfiguration;
|
||||
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;
|
||||
@ -49,6 +50,7 @@ public final class DeviceManagementConfig {
|
||||
private PullNotificationConfiguration pullNotificationConfiguration;
|
||||
private DeviceStatusTaskConfig deviceStatusTaskConfig;
|
||||
private DeviceCacheConfiguration deviceCacheConfiguration;
|
||||
private CertificateCacheConfiguration certificateCacheConfiguration;
|
||||
private GeoLocationConfiguration geoLocationConfiguration;
|
||||
private String defaultGroupsConfiguration;
|
||||
private RemoteSessionConfiguration remoteSessionConfiguration;
|
||||
@ -145,6 +147,15 @@ public final class DeviceManagementConfig {
|
||||
this.deviceCacheConfiguration = deviceCacheConfiguration;
|
||||
}
|
||||
|
||||
@XmlElement(name = "CertificateCacheConfiguration", required = true)
|
||||
public CertificateCacheConfiguration getCertificateCacheConfiguration() {
|
||||
return certificateCacheConfiguration;
|
||||
}
|
||||
|
||||
public void setCertificateCacheConfiguration(CertificateCacheConfiguration certificateCacheConfiguration) {
|
||||
this.certificateCacheConfiguration = certificateCacheConfiguration;
|
||||
}
|
||||
|
||||
@XmlElement(name = "GeoLocationConfiguration", required = true)
|
||||
public GeoLocationConfiguration getGeoLocationConfiguration() {
|
||||
return geoLocationConfiguration;
|
||||
|
||||
@ -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 = "CertificateCacheConfiguration")
|
||||
public class CertificateCacheConfiguration {
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -26,6 +26,7 @@ public class DeviceCacheConfiguration {
|
||||
|
||||
private boolean isEnabled;
|
||||
private int expiryTime;
|
||||
private long capacity;
|
||||
|
||||
@XmlElement(name = "Enable", required = true)
|
||||
public boolean isEnabled() {
|
||||
@ -44,4 +45,13 @@ public class DeviceCacheConfiguration {
|
||||
public void setExpiryTime(int expiryTime) {
|
||||
this.expiryTime = expiryTime;
|
||||
}
|
||||
|
||||
@XmlElement(name = "Capacity", required = true)
|
||||
public long getCapacity() {
|
||||
return capacity;
|
||||
}
|
||||
|
||||
public void setCapacity(long capacity) {
|
||||
this.capacity = capacity;
|
||||
}
|
||||
}
|
||||
|
||||
@ -32,6 +32,7 @@ public class PaginationConfiguration {
|
||||
private int operationListPageSize;
|
||||
private int notificationListPageSize;
|
||||
private int activityListPageSize;
|
||||
private int topicListPageSize;
|
||||
|
||||
public int getDeviceListPageSize() {
|
||||
return deviceListPageSize;
|
||||
@ -78,4 +79,14 @@ public class PaginationConfiguration {
|
||||
this.activityListPageSize = activityListPageSize;
|
||||
}
|
||||
|
||||
public int getTopicListPageSize() {
|
||||
return deviceListPageSize;
|
||||
}
|
||||
|
||||
@XmlElement(name = "TopicListPageSize", required = true)
|
||||
public void setTopicListPageSize(int topicListPageSize) {
|
||||
this.topicListPageSize = topicListPageSize;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -126,7 +126,19 @@ public interface DeviceDAO {
|
||||
Device getDevice(DeviceIdentifier deviceIdentifier, int tenantId) throws DeviceManagementDAOException;
|
||||
|
||||
/**
|
||||
* This method is used to retrieve a device of a given device-identifier and tenant-id.
|
||||
* This method is used to retrieve a device of a given device-identifier and owner and tenant-id.
|
||||
*
|
||||
* @param deviceIdentifier device id.
|
||||
* @param owner username of the owner.
|
||||
* @param tenantId tenant id.
|
||||
* @return returns the device object.
|
||||
* @throws DeviceManagementDAOException
|
||||
*/
|
||||
Device getDevice(DeviceIdentifier deviceIdentifier, String owner, int tenantId) throws DeviceManagementDAOException;
|
||||
|
||||
/**
|
||||
* This method is used to retrieve a device of a given device-identifier and tenant-id which modified
|
||||
* later than the ifModifiedSince param.
|
||||
*
|
||||
* @param deviceIdentifier device id.
|
||||
* @param ifModifiedSince last modified time.
|
||||
@ -137,6 +149,20 @@ public interface DeviceDAO {
|
||||
Device getDevice(DeviceIdentifier deviceIdentifier, Date ifModifiedSince, int tenantId) throws
|
||||
DeviceManagementDAOException;
|
||||
|
||||
/**
|
||||
* This method is used to retrieve a device of a given device-identifier and owner and tenant-id which modified
|
||||
* later than the ifModifiedSince param.
|
||||
*
|
||||
* @param deviceIdentifier device id.
|
||||
* @param owner username of the owner.
|
||||
* @param ifModifiedSince last modified time.
|
||||
* @param tenantId tenant id.
|
||||
* @return returns the device object.
|
||||
* @throws DeviceManagementDAOException
|
||||
*/
|
||||
Device getDevice(DeviceIdentifier deviceIdentifier, String owner, Date ifModifiedSince, int tenantId) throws
|
||||
DeviceManagementDAOException;
|
||||
|
||||
/**
|
||||
* This method is used to retrieve a device of a given device-identifier, enrollment status and tenant-id.
|
||||
*
|
||||
|
||||
@ -122,7 +122,14 @@ 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, " +
|
||||
"t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " +
|
||||
"t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " +
|
||||
"AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC";
|
||||
"AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC, e.STATUS ASC";
|
||||
// Status adeed as an orderby clause to fix a bug : when an existing device is
|
||||
// re-enrolled, earlier enrollment is marked as removed and a new enrollment is added.
|
||||
// However, both enrollments share the same time stamp. When retrieving the device
|
||||
// due to same timestamp, enrollment information is incorrect, intermittently. Hence
|
||||
// status also should be taken into consideration when ordering. This should not present a
|
||||
// problem for other status transitions, as there would be an intermediary removed
|
||||
// state in between.
|
||||
stmt = conn.prepareStatement(sql);
|
||||
stmt.setString(1, deviceIdentifier.getType());
|
||||
stmt.setString(2, deviceIdentifier.getId());
|
||||
@ -141,6 +148,40 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
|
||||
return device;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Device getDevice(DeviceIdentifier deviceIdentifier, String owner, int tenantId)
|
||||
throws DeviceManagementDAOException {
|
||||
Connection conn;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
Device device = null;
|
||||
try {
|
||||
conn = this.getConnection();
|
||||
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
|
||||
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.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 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.OWNER = ?";
|
||||
stmt = conn.prepareStatement(sql);
|
||||
stmt.setString(1, deviceIdentifier.getType());
|
||||
stmt.setString(2, deviceIdentifier.getId());
|
||||
stmt.setInt(3, tenantId);
|
||||
stmt.setInt(4, tenantId);
|
||||
stmt.setString(5, owner);
|
||||
rs = stmt.executeQuery();
|
||||
if (rs.next()) {
|
||||
device = DeviceManagementDAOUtil.loadMatchingDevice(rs, false);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new DeviceManagementDAOException("Error occurred while listing devices for type " +
|
||||
"'" + deviceIdentifier.getType() + "'", e);
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return device;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Device getDevice(DeviceIdentifier deviceIdentifier, Date since, int tenantId)
|
||||
throws DeviceManagementDAOException {
|
||||
@ -176,6 +217,41 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
|
||||
return device;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Device getDevice(DeviceIdentifier deviceIdentifier, String owner, Date since, int tenantId)
|
||||
throws DeviceManagementDAOException {
|
||||
Connection conn;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
Device device = null;
|
||||
try {
|
||||
conn = this.getConnection();
|
||||
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
|
||||
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
|
||||
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " +
|
||||
"t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_DETAIL dt " +
|
||||
"WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " +
|
||||
"AND dt.UPDATE_TIMESTAMP > ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? AND e.OWNER = ?" ;
|
||||
stmt = conn.prepareStatement(sql);
|
||||
stmt.setString(1, deviceIdentifier.getType());
|
||||
stmt.setString(2, deviceIdentifier.getId());
|
||||
stmt.setInt(3, tenantId);
|
||||
stmt.setLong(4, since.getTime());
|
||||
stmt.setInt(5, tenantId);
|
||||
stmt.setString(6, owner);
|
||||
rs = stmt.executeQuery();
|
||||
if (rs.next()) {
|
||||
device = DeviceManagementDAOUtil.loadMatchingDevice(rs, false);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new DeviceManagementDAOException("Error occurred while listing device for type " +
|
||||
"'" + deviceIdentifier.getType() + "'", e);
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return device;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Device getDevice(DeviceIdentifier deviceIdentifier, EnrolmentInfo.Status status, int tenantId) throws
|
||||
DeviceManagementDAOException {
|
||||
|
||||
@ -50,11 +50,9 @@ public class NotificationManagementServiceImpl implements NotificationManagement
|
||||
private static final Log log = LogFactory.getLog(NotificationManagementServiceImpl.class);
|
||||
|
||||
private NotificationDAO notificationDAO;
|
||||
private DeviceDAO deviceDAO;
|
||||
|
||||
public NotificationManagementServiceImpl() {
|
||||
this.notificationDAO = NotificationManagementDAOFactory.getNotificationDAO();
|
||||
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@ -1,22 +0,0 @@
|
||||
/*
|
||||
* 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.operation.mgt;
|
||||
|
||||
public interface OperationManagementServiceProvider {
|
||||
}
|
||||
@ -105,10 +105,6 @@ public class OperationManagerImpl implements OperationManager {
|
||||
return notificationStrategy;
|
||||
}
|
||||
|
||||
public void setNotificationStrategy(NotificationStrategy notificationStrategy) {
|
||||
this.notificationStrategy = notificationStrategy;
|
||||
}
|
||||
|
||||
public OperationManagerImpl(String deviceType, NotificationStrategy notificationStrategy) {
|
||||
this(deviceType);
|
||||
this.notificationStrategy = notificationStrategy;
|
||||
@ -145,7 +141,7 @@ public class OperationManagerImpl implements OperationManager {
|
||||
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto =
|
||||
OperationDAOUtil.convertOperation(operation);
|
||||
int operationId = this.lookupOperationDAO(operation).addOperation(operationDto);
|
||||
boolean isScheduledOperation = this.isTaskScheduledOperation(operation, deviceIds);
|
||||
boolean isScheduledOperation = this.isTaskScheduledOperation(operation);
|
||||
boolean isNotRepeated = false;
|
||||
boolean isScheduled = false;
|
||||
|
||||
@ -348,18 +344,22 @@ public class OperationManagerImpl implements OperationManager {
|
||||
PaginationResult paginationResult = null;
|
||||
List<Operation> operations = new ArrayList<>();
|
||||
String owner = request.getOwner();
|
||||
try {
|
||||
if (!DeviceManagerUtil.isDeviceExists(deviceId)) {
|
||||
throw new OperationManagementException("Device not found for given device " +
|
||||
"Identifier:" + deviceId.getId() + " and given type : " +
|
||||
deviceId.getType());
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
throw new OperationManagementException("Error while checking the existence of the device identifier - "
|
||||
+ deviceId.getId() + " of the device type - " + deviceId.getType(), e);
|
||||
}
|
||||
if (!isActionAuthorized(deviceId)) {
|
||||
throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
|
||||
deviceId.getType() + "' device, which carries the identifier '" +
|
||||
deviceId.getId() + "' of owner '" + owner + "'");
|
||||
}
|
||||
|
||||
EnrolmentInfo enrolmentInfo = this.getEnrolmentInfo(deviceId, owner);
|
||||
if (enrolmentInfo == null) {
|
||||
throw new OperationManagementException("Device not found for given device " +
|
||||
"Identifier:" + deviceId.getId() + " and given type" +
|
||||
deviceId.getType());
|
||||
}
|
||||
int enrolmentId = enrolmentInfo.getId();
|
||||
try {
|
||||
OperationManagementDAOFactory.openConnection();
|
||||
@ -534,9 +534,8 @@ public class OperationManagerImpl implements OperationManager {
|
||||
try {
|
||||
int enrolmentId = enrolmentInfo.getId();
|
||||
OperationManagementDAOFactory.beginTransaction();
|
||||
boolean isUpdated = false;
|
||||
if (operation.getStatus() != null) {
|
||||
isUpdated = operationDAO.updateOperationStatus(enrolmentId, operationId,
|
||||
operationDAO.updateOperationStatus(enrolmentId, operationId,
|
||||
org.wso2.carbon.device.mgt.core.dto.operation.mgt.
|
||||
Operation.Status.valueOf(operation.getStatus().
|
||||
toString()));
|
||||
@ -557,27 +556,6 @@ public class OperationManagerImpl implements OperationManager {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteOperation(int operationId) throws OperationManagementException {
|
||||
try {
|
||||
OperationManagementDAOFactory.beginTransaction();
|
||||
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operation =
|
||||
operationDAO.getOperation(operationId);
|
||||
if (operation == null) {
|
||||
throw new OperationManagementException("Operation not found for operation id : " + operationId);
|
||||
}
|
||||
lookupOperationDAO(operation).deleteOperation(operationId);
|
||||
OperationManagementDAOFactory.commitTransaction();
|
||||
} catch (OperationManagementDAOException e) {
|
||||
OperationManagementDAOFactory.rollbackTransaction();
|
||||
throw new OperationManagementException("Error occurred while deleting the operation: " + operationId, e);
|
||||
} catch (TransactionManagementException e) {
|
||||
throw new OperationManagementException("Error occurred while initiating a transaction", e);
|
||||
} finally {
|
||||
OperationManagementDAOFactory.closeConnection();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId)
|
||||
throws OperationManagementException {
|
||||
@ -601,32 +579,33 @@ public class OperationManagerImpl implements OperationManager {
|
||||
|
||||
try {
|
||||
OperationManagementDAOFactory.openConnection();
|
||||
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO.
|
||||
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation deviceSpecificOperation = operationDAO.
|
||||
getOperationByDeviceAndId(enrolmentInfo.getId(),
|
||||
operationId);
|
||||
if (dtoOperation.getType().
|
||||
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = deviceSpecificOperation;
|
||||
if (deviceSpecificOperation.getType().
|
||||
equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) {
|
||||
org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation;
|
||||
commandOperation =
|
||||
(org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO.
|
||||
getOperation(dtoOperation.getId());
|
||||
getOperation(deviceSpecificOperation.getId());
|
||||
dtoOperation.setEnabled(commandOperation.isEnabled());
|
||||
} else if (dtoOperation.getType().
|
||||
} else if (deviceSpecificOperation.getType().
|
||||
equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) {
|
||||
dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
|
||||
} else if (dtoOperation.getType().equals(
|
||||
dtoOperation = configOperationDAO.getOperation(deviceSpecificOperation.getId());
|
||||
} else if (deviceSpecificOperation.getType().equals(
|
||||
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE)) {
|
||||
dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
|
||||
} else if (dtoOperation.getType().equals(
|
||||
dtoOperation = profileOperationDAO.getOperation(deviceSpecificOperation.getId());
|
||||
} else if (deviceSpecificOperation.getType().equals(
|
||||
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY)) {
|
||||
dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
|
||||
dtoOperation = policyOperationDAO.getOperation(deviceSpecificOperation.getId());
|
||||
}
|
||||
|
||||
if (dtoOperation == null) {
|
||||
throw new OperationManagementException("Operation not found for operation Id:" + operationId +
|
||||
" device id:" + deviceId.getId());
|
||||
}
|
||||
operation = OperationDAOUtil.convertOperation(dtoOperation);
|
||||
dtoOperation.setStatus(deviceSpecificOperation.getStatus());
|
||||
operation = OperationDAOUtil.convertOperation(deviceSpecificOperation);
|
||||
} catch (OperationManagementDAOException e) {
|
||||
throw new OperationManagementException("Error occurred while retrieving the list of " +
|
||||
"operations assigned for '" + deviceId.getType() +
|
||||
@ -737,62 +716,6 @@ public class OperationManagerImpl implements OperationManager {
|
||||
return operation;
|
||||
}
|
||||
|
||||
// @Override
|
||||
// public Operation getOperationByActivityId(String activity) throws OperationManagementException {
|
||||
// // This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer.
|
||||
// Operation operation;
|
||||
// int enrollmentOpMappingId = Integer.parseInt(
|
||||
// activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, ""));
|
||||
// if (enrollmentOpMappingId == 0) {
|
||||
// throw new IllegalArgumentException("Operation ID cannot be null or zero (0).");
|
||||
// }
|
||||
// try {
|
||||
// OperationManagementDAOFactory.openConnection();
|
||||
// org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation =
|
||||
// operationDAO.getOperationFromEnrollment(enrollmentOpMappingId);
|
||||
//
|
||||
// if (dtoOperation == null) {
|
||||
// throw new OperationManagementException("Operation not found for given activity Id:" + activity);
|
||||
// }
|
||||
// org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status status = dtoOperation.getStatus();
|
||||
// if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) {
|
||||
// org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation;
|
||||
// commandOperation =
|
||||
// (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO.
|
||||
// getOperation(dtoOperation.getId());
|
||||
// dtoOperation.setEnabled(commandOperation.isEnabled());
|
||||
// } else if (dtoOperation.getType().
|
||||
// equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) {
|
||||
// dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
|
||||
// } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.
|
||||
// PROFILE)) {
|
||||
// dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
|
||||
// } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.
|
||||
// POLICY)) {
|
||||
// dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
|
||||
// }
|
||||
// operation = OperationDAOUtil.convertOperation(dtoOperation);
|
||||
// int enrolmentId = operationDAO.getEnrolmentIdFromMappingId(enrollmentOpMappingId);
|
||||
// if (enrolmentId != 0) {
|
||||
// operation.setResponses(operationDAO.getOperationResponses(enrolmentId, operation.getId()));
|
||||
// }
|
||||
//
|
||||
// operation.setStatus(Operation.Status.valueOf(status.toString()));
|
||||
// operation.setActivityId(activity);
|
||||
//
|
||||
// } 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, e);
|
||||
// } finally {
|
||||
// OperationManagementDAOFactory.closeConnection();
|
||||
// }
|
||||
//
|
||||
// // return this.getOperation(operationId);
|
||||
// return operation;
|
||||
// }
|
||||
|
||||
@Override
|
||||
public Activity getOperationByActivityId(String activity) throws OperationManagementException {
|
||||
// This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer.
|
||||
@ -821,7 +744,11 @@ public class OperationManagerImpl implements OperationManager {
|
||||
if (operationId == 0) {
|
||||
throw new IllegalArgumentException("Operation ID cannot be null or zero (0).");
|
||||
}
|
||||
|
||||
if (!isActionAuthorized(deviceId)) {
|
||||
throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
|
||||
deviceId.getType() + "' device, which carries the identifier '" +
|
||||
deviceId.getId() + "'");
|
||||
}
|
||||
Device device = this.getDevice(deviceId);
|
||||
try {
|
||||
OperationManagementDAOFactory.openConnection();
|
||||
@ -836,26 +763,6 @@ public class OperationManagerImpl implements OperationManager {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Operation> getOperationUpdatedAfter(long timestamp) throws OperationManagementException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Activity> getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException {
|
||||
try {
|
||||
OperationManagementDAOFactory.openConnection();
|
||||
return operationDAO.getActivitiesUpdatedAfter(timestamp);
|
||||
} 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 getting the activity list changed after a " +
|
||||
"given time.", e);
|
||||
} finally {
|
||||
OperationManagementDAOFactory.closeConnection();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Activity> getActivitiesUpdatedAfter(long timestamp, int limit,
|
||||
int offset) throws OperationManagementException {
|
||||
@ -902,19 +809,6 @@ public class OperationManagerImpl implements OperationManager {
|
||||
}
|
||||
}
|
||||
|
||||
private OperationDAO lookupOperationDAO(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operation) {
|
||||
|
||||
if (operation instanceof org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) {
|
||||
return commandOperationDAO;
|
||||
} else if (operation instanceof org.wso2.carbon.device.mgt.core.dto.operation.mgt.ProfileOperation) {
|
||||
return profileOperationDAO;
|
||||
} else if (operation instanceof org.wso2.carbon.device.mgt.core.dto.operation.mgt.ConfigOperation) {
|
||||
return configOperationDAO;
|
||||
} else {
|
||||
return operationDAO;
|
||||
}
|
||||
}
|
||||
|
||||
private String getUser() {
|
||||
return CarbonContext.getThreadLocalCarbonContext().getUsername();
|
||||
}
|
||||
@ -957,26 +851,6 @@ public class OperationManagerImpl implements OperationManager {
|
||||
return isUserAuthorized;
|
||||
}
|
||||
|
||||
private int getEnrolmentByStatus(DeviceIdentifier deviceId,
|
||||
EnrolmentInfo.Status status) throws OperationManagementException {
|
||||
int enrolmentId;
|
||||
try {
|
||||
DeviceManagementDAOFactory.openConnection();
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, status, tenantId);
|
||||
} catch (DeviceManagementDAOException e) {
|
||||
throw new OperationManagementException("Error occurred while retrieving metadata of '" +
|
||||
deviceId.getType() + "' device carrying the identifier '" +
|
||||
deviceId.getId() + "'", e);
|
||||
} catch (SQLException e) {
|
||||
throw new OperationManagementException(
|
||||
"Error occurred while opening a connection to the data source", e);
|
||||
} finally {
|
||||
DeviceManagementDAOFactory.closeConnection();
|
||||
}
|
||||
return enrolmentId;
|
||||
}
|
||||
|
||||
private EnrolmentInfo getEnrolmentInfo(DeviceIdentifier deviceId, String owner) throws OperationManagementException {
|
||||
EnrolmentInfo enrolmentInfo = null;
|
||||
try {
|
||||
@ -1049,39 +923,15 @@ public class OperationManagerImpl implements OperationManager {
|
||||
return updateStatus;
|
||||
}
|
||||
|
||||
private boolean isTaskScheduledOperation(Operation operation, List<DeviceIdentifier> deviceIds) {
|
||||
private boolean isTaskScheduledOperation(Operation operation) {
|
||||
DeviceManagementProviderService deviceManagementProviderService = DeviceManagementDataHolder.getInstance().
|
||||
getDeviceManagementProvider();
|
||||
|
||||
List<MonitoringOperation> monitoringOperations = deviceManagementProviderService.getMonitoringOperationList(deviceType);//Get task list from each device type
|
||||
|
||||
for (MonitoringOperation op : monitoringOperations) {
|
||||
if (operation.getCode().equals(op.getTaskName())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// for(String dti : taskOperation){
|
||||
// if (dti.equals(deviceType)) {
|
||||
// monitoringOperations = deviceTypeSpecificTasks.get(dti);
|
||||
//
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// for(DeviceIdentifier deviceIdentifier : deviceIds){
|
||||
// String deviceType = deviceIdentifier.getType();
|
||||
//
|
||||
//
|
||||
//
|
||||
// }
|
||||
|
||||
// TaskConfiguration taskConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().
|
||||
// getTaskConfiguration();
|
||||
// for (TaskConfiguration.Operation op : taskConfiguration.getOperations()) {
|
||||
// if (operation.getCode().equals(op.getOperationName())) {
|
||||
// return true;
|
||||
// }
|
||||
// }
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@ -26,8 +26,6 @@ public class OperationMgtConstants {
|
||||
}
|
||||
|
||||
public static final String DEVICE_ID_NOT_FOUND = "Device not found for device id: %s";
|
||||
public static final String DEVICE_ID_SERVICE_NOT_FOUND =
|
||||
"Issue in retrieving device management service instance for device found at %s";
|
||||
}
|
||||
|
||||
public final class OperationCodes {
|
||||
|
||||
@ -33,12 +33,8 @@ public interface OperationDAO {
|
||||
|
||||
void updateOperation(Operation operation) throws OperationManagementDAOException;
|
||||
|
||||
void deleteOperation(int operationId) throws OperationManagementDAOException;
|
||||
|
||||
Operation getOperation(int operationId) throws OperationManagementDAOException;
|
||||
|
||||
Operation getOperationFromEnrollment(int enrollmentOpMappingId) throws OperationManagementDAOException;
|
||||
|
||||
Operation getOperationByDeviceAndId(int enrolmentId, int operationId) throws OperationManagementDAOException;
|
||||
|
||||
List<? extends Operation> getOperationsByDeviceAndStatus(int enrolmentId, Operation.Status status)
|
||||
@ -66,24 +62,16 @@ public interface OperationDAO {
|
||||
void addOperationResponse(int enrolmentId, int operationId, Object operationResponse)
|
||||
throws OperationManagementDAOException;
|
||||
|
||||
List<OperationResponse> getOperationResponses(int enrolmentId, int operationId) throws OperationManagementDAOException;
|
||||
|
||||
Activity getActivity(int operationId) throws OperationManagementDAOException;
|
||||
|
||||
Activity getActivityByDevice(int operationId, int deviceId) throws OperationManagementDAOException;
|
||||
|
||||
int getEnrolmentIdFromMappingId(int enrollmentOpMappingId) throws OperationManagementDAOException;
|
||||
|
||||
List<Operation> getOperationsUpdatedAfter(long timestamp) throws OperationManagementDAOException;
|
||||
|
||||
List<Activity> getActivitiesUpdatedAfter(long timestamp) throws OperationManagementDAOException;
|
||||
|
||||
List<Activity> getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementDAOException;
|
||||
|
||||
int getActivityCountUpdatedAfter(long timestamp) throws OperationManagementDAOException;
|
||||
|
||||
boolean resetAttemptCount(int enrolmentId) throws OperationManagementDAOException;
|
||||
|
||||
/**
|
||||
* This method provides operation mappings for given status
|
||||
* @param opStatus Operation status
|
||||
|
||||
@ -18,6 +18,7 @@
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.core.operation.mgt.dao;
|
||||
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
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;
|
||||
|
||||
@ -70,22 +70,6 @@ public class CommandOperationDAOImpl extends GenericOperationDAOImpl {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteOperation(int id) throws OperationManagementDAOException {
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
super.deleteOperation(id);
|
||||
Connection connection = OperationManagementDAOFactory.getConnection();
|
||||
stmt = connection.prepareStatement("DELETE FROM DM_COMMAND_OPERATION WHERE OPERATION_ID = ?");
|
||||
stmt.setInt(1, id);
|
||||
stmt.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
throw new OperationManagementDAOException("Error occurred while deleting operation metadata", e);
|
||||
} finally {
|
||||
OperationManagementDAOUtil.cleanupResources(stmt);
|
||||
}
|
||||
}
|
||||
|
||||
public CommandOperation getOperation(int id) throws OperationManagementDAOException {
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
|
||||
@ -60,22 +60,6 @@ public class ConfigOperationDAOImpl extends GenericOperationDAOImpl {
|
||||
return operationId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteOperation(int id) throws OperationManagementDAOException {
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
super.deleteOperation(id);
|
||||
Connection connection = OperationManagementDAOFactory.getConnection();
|
||||
stmt = connection.prepareStatement("DELETE FROM DM_CONFIG_OPERATION WHERE OPERATION_ID = ?") ;
|
||||
stmt.setInt(1, id);
|
||||
stmt.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
throw new OperationManagementDAOException("Error occurred while deleting operation metadata", e);
|
||||
} finally {
|
||||
OperationManagementDAOUtil.cleanupResources(stmt);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateOperation(Operation operation) throws OperationManagementDAOException {
|
||||
PreparedStatement stmt = null;
|
||||
@ -136,6 +120,8 @@ public class ConfigOperationDAOImpl extends GenericOperationDAOImpl {
|
||||
bais = new ByteArrayInputStream(operationDetails);
|
||||
ois = new ObjectInputStream(bais);
|
||||
configOperation = (ConfigOperation) ois.readObject();
|
||||
configOperation.setId(rs.getInt("OPERATION_ID"));
|
||||
configOperation.setEnabled(rs.getBoolean("ENABLED"));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new OperationManagementDAOException("IO Error occurred while de serialize the policy operation " +
|
||||
|
||||
@ -249,68 +249,6 @@ public class GenericOperationDAOImpl implements OperationDAO {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<OperationResponse> getOperationResponses(int enrolmentId, int operationId) throws
|
||||
OperationManagementDAOException {
|
||||
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
List<OperationResponse> responces = new ArrayList<>();
|
||||
try {
|
||||
Connection conn = OperationManagementDAOFactory.getConnection();
|
||||
String sql = "SELECT * FROM DM_DEVICE_OPERATION_RESPONSE WHERE ENROLMENT_ID = ? AND OPERATION_ID = ?";
|
||||
stmt = conn.prepareStatement(sql);
|
||||
stmt.setInt(1, enrolmentId);
|
||||
stmt.setInt(2, operationId);
|
||||
rs = stmt.executeQuery();
|
||||
|
||||
while (rs.next()) {
|
||||
OperationResponse response = new OperationResponse();
|
||||
response.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
|
||||
ByteArrayInputStream bais = null;
|
||||
ObjectInputStream ois = null;
|
||||
byte[] contentBytes;
|
||||
try {
|
||||
contentBytes = (byte[]) rs.getBytes("OPERATION_RESPONSE");
|
||||
bais = new ByteArrayInputStream(contentBytes);
|
||||
ois = new ObjectInputStream(bais);
|
||||
response.setResponse(ois.readObject().toString());
|
||||
|
||||
} finally {
|
||||
if (bais != null) {
|
||||
try {
|
||||
bais.close();
|
||||
} catch (IOException e) {
|
||||
log.warn("Error occurred while closing ByteArrayOutputStream", e);
|
||||
}
|
||||
}
|
||||
if (ois != null) {
|
||||
try {
|
||||
ois.close();
|
||||
} catch (IOException e) {
|
||||
log.warn("Error occurred while closing ObjectOutputStream", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
responces.add(response);
|
||||
}
|
||||
|
||||
} catch (SQLException e) {
|
||||
throw new OperationManagementDAOException("SQL Error occurred while retrieving the operation responses for " +
|
||||
"operation id " + operationId + " and enrolment id " + enrolmentId, e);
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new OperationManagementDAOException("Error occurred while converting the operation responses to string" +
|
||||
" for operation id " + operationId + " and enrolment id " + enrolmentId, e);
|
||||
} catch (IOException e) {
|
||||
throw new OperationManagementDAOException("Error occurred while converting the operation responses to string" +
|
||||
" for operation id " + operationId + " and enrolment id " + enrolmentId, e);
|
||||
} finally {
|
||||
OperationManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
|
||||
return responces;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Activity getActivity(int operationId) throws OperationManagementDAOException {
|
||||
|
||||
@ -674,80 +612,6 @@ public class GenericOperationDAOImpl implements OperationDAO {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEnrolmentIdFromMappingId(int enrollmentOpMappingId) throws OperationManagementDAOException {
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
Connection conn = OperationManagementDAOFactory.getConnection();
|
||||
String sql = "SELECT * FROM DM_ENROLMENT_OP_MAPPING WHERE ID = ?";
|
||||
stmt = conn.prepareStatement(sql);
|
||||
stmt.setInt(1, enrollmentOpMappingId);
|
||||
rs = stmt.executeQuery();
|
||||
|
||||
if (rs.next()) {
|
||||
return rs.getInt("ENROLMENT_ID");
|
||||
}
|
||||
|
||||
} catch (SQLException e) {
|
||||
throw new OperationManagementDAOException("SQL Error occurred while retrieving the enrolment id " +
|
||||
" for the mapping id '" + enrollmentOpMappingId, e);
|
||||
} finally {
|
||||
OperationManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Operation> getOperationsUpdatedAfter(long timestamp) throws OperationManagementDAOException {
|
||||
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
List<Operation> operations = new ArrayList<>();
|
||||
try {
|
||||
Connection conn = OperationManagementDAOFactory.getConnection();
|
||||
String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, OPERATION_CODE " +
|
||||
"FROM DM_OPERATION AS o \n" +
|
||||
"INNER JOIN DM_ENROLMENT_OP_MAPPING AS eom ON eom.OPERATION_ID=o.ID WHERE eom.UPDATED_TIMESTAMP = ?";
|
||||
stmt = conn.prepareStatement(sql);
|
||||
stmt.setLong(1, timestamp);
|
||||
rs = stmt.executeQuery();
|
||||
|
||||
if (rs.next()) {
|
||||
Operation operation = new Operation();
|
||||
operation.setId(rs.getInt("ID"));
|
||||
operation.setType(Operation.Type.valueOf(rs.getString("TYPE")));
|
||||
operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString());
|
||||
operation.setCode(rs.getString("OPERATION_CODE"));
|
||||
|
||||
operations.add(operation);
|
||||
}
|
||||
|
||||
} catch (SQLException e) {
|
||||
throw new OperationManagementDAOException("Error occurred while retrieving the operations updated " +
|
||||
"after a given time", e);
|
||||
} finally {
|
||||
OperationManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return operations;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void deleteOperation(int id) throws OperationManagementDAOException {
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
Connection connection = OperationManagementDAOFactory.getConnection();
|
||||
stmt = connection.prepareStatement("DELETE FROM DM_OPERATION WHERE ID = ?");
|
||||
stmt.setInt(1, id);
|
||||
stmt.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
throw new OperationManagementDAOException("Error occurred while deleting operation metadata", e);
|
||||
} finally {
|
||||
OperationManagementDAOUtil.cleanupResources(stmt);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Operation getOperation(int id) throws OperationManagementDAOException {
|
||||
PreparedStatement stmt = null;
|
||||
@ -783,49 +647,6 @@ public class GenericOperationDAOImpl implements OperationDAO {
|
||||
return operation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Operation getOperationFromEnrollment(int enrollmentOpMappingId) throws OperationManagementDAOException {
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
Operation operation = null;
|
||||
try {
|
||||
Connection conn = OperationManagementDAOFactory.getConnection();
|
||||
String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, OPERATION_CODE, \n" +
|
||||
" om.STATUS, om.UPDATED_TIMESTAMP FROM DM_OPERATION o \n" +
|
||||
"INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm WHERE dm.ID = ? ) om \n" +
|
||||
"ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC ";
|
||||
stmt = conn.prepareStatement(sql);
|
||||
stmt.setInt(1, enrollmentOpMappingId);
|
||||
rs = stmt.executeQuery();
|
||||
|
||||
if (rs.next()) {
|
||||
operation = new Operation();
|
||||
operation.setId(rs.getInt("ID"));
|
||||
operation.setType(Operation.Type.valueOf(rs.getString("TYPE")));
|
||||
operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString());
|
||||
// if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) {
|
||||
// operation.setReceivedTimeStamp("");
|
||||
// } else {
|
||||
// operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
|
||||
// }
|
||||
if (rs.getLong("UPDATED_TIMESTAMP") == 0) {
|
||||
operation.setReceivedTimeStamp("");
|
||||
} else {
|
||||
operation.setReceivedTimeStamp(
|
||||
new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString());
|
||||
}
|
||||
operation.setCode(rs.getString("OPERATION_CODE"));
|
||||
operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS")));
|
||||
OperationDAOUtil.setActivityId(operation, rs.getInt("ID"));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new OperationManagementDAOException("SQL error occurred while retrieving the operation .", e);
|
||||
} finally {
|
||||
OperationManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return operation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Operation getOperationByDeviceAndId(int enrolmentId, int operationId) throws OperationManagementDAOException {
|
||||
PreparedStatement stmt = null;
|
||||
@ -833,9 +654,9 @@ public class GenericOperationDAOImpl implements OperationDAO {
|
||||
Operation operation = null;
|
||||
try {
|
||||
Connection conn = OperationManagementDAOFactory.getConnection();
|
||||
String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, o.STATUS, o.OPERATION_CODE, " +
|
||||
String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, om.STATUS, o.OPERATION_CODE, " +
|
||||
"om.ID AS OM_MAPPING_ID, " +
|
||||
"om.UPDATED_TIMESTAMP FROM (SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, STATUS," +
|
||||
"om.UPDATED_TIMESTAMP FROM (SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP," +
|
||||
"OPERATION_CODE FROM DM_OPERATION WHERE id = ?) o INNER JOIN (SELECT * FROM " +
|
||||
"DM_ENROLMENT_OP_MAPPING dm where dm.OPERATION_ID = ? AND dm.ENROLMENT_ID = ?) om " +
|
||||
"ON o.ID = om.OPERATION_ID ";
|
||||
@ -850,6 +671,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
|
||||
operation.setId(rs.getInt("ID"));
|
||||
operation.setType(Operation.Type.valueOf(rs.getString("TYPE")));
|
||||
operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString());
|
||||
operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS")));
|
||||
// if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) {
|
||||
// operation.setReceivedTimeStamp("");
|
||||
// } else {
|
||||
@ -1176,31 +998,6 @@ public class GenericOperationDAOImpl implements OperationDAO {
|
||||
return operations;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean resetAttemptCount(int enrolmentId) throws OperationManagementDAOException {
|
||||
boolean status = false;
|
||||
Connection conn;
|
||||
PreparedStatement stmt = null;
|
||||
Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
try {
|
||||
conn = OperationManagementDAOFactory.getConnection();
|
||||
String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET ATTEMPTS = 0, LAST_REQUESTED_TIME = ? " +
|
||||
"WHERE ENROLMENT_ID = ? AND TENANT_ID = ?";
|
||||
stmt = conn.prepareStatement(query);
|
||||
stmt.setTimestamp(1, currentTimestamp);
|
||||
stmt.setInt(2, enrolmentId);
|
||||
stmt.setInt(3, tenantId);
|
||||
stmt.executeUpdate();
|
||||
status = true;
|
||||
} catch (SQLException e) {
|
||||
throw new OperationManagementDAOException("Unable to reset the attempt count in database.", e);
|
||||
} finally {
|
||||
OperationManagementDAOUtil.cleanupResources(stmt, null);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Integer, List<OperationMapping>> getOperationMappingsByStatus(Operation.Status opStatus, Operation.PushNotificationStatus pushNotificationStatus,
|
||||
int limit) throws OperationManagementDAOException {
|
||||
|
||||
@ -122,22 +122,6 @@ public class PolicyOperationDAOImpl extends GenericOperationDAOImpl {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteOperation(int operationId) throws OperationManagementDAOException {
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
super.deleteOperation(operationId);
|
||||
Connection connection = OperationManagementDAOFactory.getConnection();
|
||||
stmt = connection.prepareStatement("DELETE FROM DM_POLICY_OPERATION WHERE OPERATION_ID=?");
|
||||
stmt.setInt(1, operationId);
|
||||
stmt.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
throw new OperationManagementDAOException("Error occurred while deleting operation metadata", e);
|
||||
} finally {
|
||||
OperationManagementDAOUtil.cleanupResources(stmt);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Operation getOperation(int operationId) throws OperationManagementDAOException {
|
||||
PreparedStatement stmt = null;
|
||||
|
||||
@ -123,22 +123,6 @@ public class ProfileOperationDAOImpl extends GenericOperationDAOImpl {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteOperation(int id) throws OperationManagementDAOException {
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
super.deleteOperation(id);
|
||||
Connection connection = OperationManagementDAOFactory.getConnection();
|
||||
stmt = connection.prepareStatement("DELETE FROM DM_PROFILE_OPERATION WHERE OPERATION_ID=?");
|
||||
stmt.setInt(1, id);
|
||||
stmt.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
throw new OperationManagementDAOException("Error occurred while deleting operation metadata", e);
|
||||
} finally {
|
||||
OperationManagementDAOUtil.cleanupResources(stmt);
|
||||
}
|
||||
}
|
||||
|
||||
public Operation getOperation(int id) throws OperationManagementDAOException {
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
|
||||
@ -1,154 +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.core.push.notification.mgt;
|
||||
|
||||
import org.wso2.carbon.device.mgt.common.*;
|
||||
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.operation.mgt.OperationManager;
|
||||
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.PushNotificationExecutionFailedException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class PushNotificationBasedOperationManager implements OperationManager {
|
||||
|
||||
private OperationManager operationManager;
|
||||
private NotificationStrategy notificationProvider;
|
||||
|
||||
public PushNotificationBasedOperationManager(
|
||||
OperationManager operationManager, NotificationStrategy notificationProvider) {
|
||||
this.operationManager = operationManager;
|
||||
this.notificationProvider = notificationProvider;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Activity addOperation(Operation operation,
|
||||
List<DeviceIdentifier> devices) throws OperationManagementException, InvalidDeviceException {
|
||||
Activity activity = this.operationManager.addOperation(operation, devices);
|
||||
for (DeviceIdentifier deviceId : devices) {
|
||||
try {
|
||||
this.notificationProvider.execute(new NotificationContext(deviceId, operation));
|
||||
} catch (PushNotificationExecutionFailedException e) {
|
||||
throw new OperationManagementException("Error occurred while sending push notification to device", e);
|
||||
}
|
||||
}
|
||||
return activity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<? extends Operation> getOperations(
|
||||
DeviceIdentifier deviceId) throws OperationManagementException {
|
||||
return this.operationManager.getOperations(deviceId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PaginationResult getOperations(DeviceIdentifier deviceId,
|
||||
PaginationRequest request) throws OperationManagementException {
|
||||
return this.operationManager.getOperations(deviceId, request);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<? extends Operation> getPendingOperations(
|
||||
DeviceIdentifier deviceId) throws OperationManagementException {
|
||||
return this.operationManager.getPendingOperations(deviceId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Operation getNextPendingOperation(DeviceIdentifier deviceId) throws OperationManagementException {
|
||||
return this.operationManager.getNextPendingOperation(deviceId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateOperation(DeviceIdentifier deviceId,
|
||||
Operation operation) throws OperationManagementException {
|
||||
this.operationManager.updateOperation(deviceId, operation);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteOperation(int operationId) throws OperationManagementException {
|
||||
this.operationManager.deleteOperation(operationId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Operation getOperationByDeviceAndOperationId(
|
||||
DeviceIdentifier deviceId, int operationId) throws OperationManagementException {
|
||||
return this.operationManager.getOperationByDeviceAndOperationId(deviceId, operationId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<? extends Operation> getOperationsByDeviceAndStatus(
|
||||
DeviceIdentifier deviceId,
|
||||
Operation.Status status) throws OperationManagementException {
|
||||
try {
|
||||
return this.operationManager.getOperationsByDeviceAndStatus(deviceId, status);
|
||||
} catch (DeviceManagementException e) {
|
||||
throw new OperationManagementException("Error occurred while retrieving the list of operations by " +
|
||||
"device and status", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Operation getOperation(int operationId) throws OperationManagementException {
|
||||
return this.operationManager.getOperation(operationId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Activity getOperationByActivityId(String activity) throws OperationManagementException {
|
||||
return this.operationManager.getOperationByActivityId(activity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) throws OperationManagementException {
|
||||
return this.operationManager.getOperationByActivityIdAndDevice(activity, deviceId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Operation> getOperationUpdatedAfter(long timestamp) throws OperationManagementException {
|
||||
return this.operationManager.getOperationUpdatedAfter(timestamp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Activity> getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException {
|
||||
return this.operationManager.getActivitiesUpdatedAfter(timestamp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Activity> getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementException {
|
||||
return this.operationManager.getActivitiesUpdatedAfter(timestamp, limit, offset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getActivityCountUpdatedAfter(long timestamp) throws OperationManagementException {
|
||||
return this.operationManager.getActivityCountUpdatedAfter(timestamp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setNotificationStrategy(NotificationStrategy notificationStrategy) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public NotificationStrategy getNotificationStrategy() {
|
||||
return notificationProvider;
|
||||
}
|
||||
|
||||
}
|
||||
@ -26,6 +26,7 @@ import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
|
||||
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
|
||||
import org.wso2.carbon.device.mgt.common.license.mgt.License;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
|
||||
@ -183,6 +184,19 @@ public interface DeviceManagementProviderService {
|
||||
*/
|
||||
Device getDevice(DeviceIdentifier deviceId, boolean requireDeviceInfo) throws DeviceManagementException;
|
||||
|
||||
/**
|
||||
* Returns the device of specified id owned by user with given username.
|
||||
*
|
||||
* @param deviceId - Device Id
|
||||
* @param owner - Username of the owner
|
||||
* @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, String owner, boolean requireDeviceInfo) throws DeviceManagementException;
|
||||
|
||||
|
||||
/**
|
||||
* Returns the device of specified id.
|
||||
*
|
||||
@ -205,6 +219,20 @@ public interface DeviceManagementProviderService {
|
||||
*/
|
||||
Device getDevice(DeviceIdentifier deviceId, Date since, boolean requireDeviceInfo) throws DeviceManagementException;
|
||||
|
||||
/**
|
||||
* Returns the device of specified id and owned by user with given username.
|
||||
*
|
||||
* @param deviceId - Device Id
|
||||
* @param owner - Username of the owner
|
||||
* @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, String owner, Date since, boolean requireDeviceInfo)
|
||||
throws DeviceManagementException;
|
||||
|
||||
/**
|
||||
* Returns the device of specified id with the given status.
|
||||
*
|
||||
@ -436,9 +464,10 @@ public interface DeviceManagementProviderService {
|
||||
|
||||
HashMap<Integer, Device> getTenantedDevice(DeviceIdentifier deviceIdentifier) throws DeviceManagementException;
|
||||
|
||||
void sendEnrolmentInvitation(String templateName, EmailMetaInfo metaInfo) throws DeviceManagementException;
|
||||
void sendEnrolmentInvitation(String templateName, EmailMetaInfo metaInfo) throws DeviceManagementException,
|
||||
ConfigurationManagementException;
|
||||
|
||||
void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException;
|
||||
void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException, ConfigurationManagementException;
|
||||
|
||||
FeatureManager getFeatureManager(String deviceType) throws DeviceManagementException;
|
||||
|
||||
@ -452,8 +481,6 @@ public interface DeviceManagementProviderService {
|
||||
*/
|
||||
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.
|
||||
*
|
||||
@ -481,8 +508,6 @@ public interface DeviceManagementProviderService {
|
||||
|
||||
boolean enrollDevice(Device device) throws DeviceManagementException;
|
||||
|
||||
PlatformConfiguration getConfiguration() throws DeviceManagementException;
|
||||
|
||||
boolean saveConfiguration(PlatformConfiguration configuration) throws DeviceManagementException;
|
||||
|
||||
boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException;
|
||||
@ -524,8 +549,6 @@ public interface DeviceManagementProviderService {
|
||||
|
||||
void updateOperation(DeviceIdentifier deviceId, Operation operation) throws OperationManagementException;
|
||||
|
||||
void deleteOperation(String type, int operationId) throws OperationManagementException;
|
||||
|
||||
Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId)
|
||||
throws OperationManagementException;
|
||||
|
||||
@ -539,8 +562,6 @@ public interface DeviceManagementProviderService {
|
||||
|
||||
Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) throws OperationManagementException;
|
||||
|
||||
List<Activity> getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException;
|
||||
|
||||
List<Activity> getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementException;
|
||||
|
||||
int getActivityCountUpdatedAfter(long timestamp) throws OperationManagementException;
|
||||
|
||||
@ -28,9 +28,6 @@ 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.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;
|
||||
@ -41,6 +38,7 @@ import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||
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.configuration.mgt.ConfigurationManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
|
||||
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
|
||||
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
|
||||
@ -55,6 +53,8 @@ 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.operation.mgt.OperationManager;
|
||||
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.pull.notification.PullNotificationSubscriber;
|
||||
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;
|
||||
@ -69,6 +69,7 @@ import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO;
|
||||
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.dto.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier;
|
||||
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.PluginInitializationListener;
|
||||
@ -77,7 +78,9 @@ import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
|
||||
import org.wso2.carbon.email.sender.core.ContentProviderInfo;
|
||||
import org.wso2.carbon.email.sender.core.EmailContext;
|
||||
import org.wso2.carbon.email.sender.core.EmailSendingFailedException;
|
||||
import org.wso2.carbon.email.sender.core.EmailTransportNotConfiguredException;
|
||||
import org.wso2.carbon.email.sender.core.TypedValue;
|
||||
import org.wso2.carbon.email.sender.core.service.EmailSenderService;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
|
||||
import java.sql.SQLException;
|
||||
@ -126,11 +129,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
|
||||
return dms.saveConfiguration(configuration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformConfiguration getConfiguration() throws DeviceManagementException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformConfiguration getConfiguration(String deviceType) throws DeviceManagementException {
|
||||
DeviceManager dms =
|
||||
@ -769,7 +767,55 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendEnrolmentInvitation(String templateName, EmailMetaInfo metaInfo) throws DeviceManagementException {
|
||||
public Device getDevice(DeviceIdentifier deviceId, String owner, boolean requireDeviceInfo)
|
||||
throws DeviceManagementException {
|
||||
if (deviceId == null) {
|
||||
String msg = "Received null device identifier for method getDevice";
|
||||
log.error(msg);
|
||||
throw new DeviceManagementException(msg);
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Get device by device id :" + deviceId.getId() + " of type '" + deviceId.getType() +
|
||||
" and owner '" + owner + "' and requiredDeviceInfo: " + requireDeviceInfo);
|
||||
}
|
||||
int tenantId = this.getTenantId();
|
||||
Device device = null;
|
||||
try {
|
||||
DeviceManagementDAOFactory.openConnection();
|
||||
device = deviceDAO.getDevice(deviceId, owner, tenantId);
|
||||
if (device == null) {
|
||||
String msg = "No device is found upon the type '" + deviceId.getType() + "' and id '" +
|
||||
deviceId.getId() + "' and owner '" + owner + "'";
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(msg);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
} catch (DeviceManagementDAOException e) {
|
||||
String msg = "Error occurred while obtaining the device for '" + deviceId.getId() + "' and owner '"
|
||||
+ owner + "'";
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while opening a connection to the data source";
|
||||
log.error(msg);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in getDevice: " + deviceId.getId() + " with owner: " + owner;
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
} finally {
|
||||
DeviceManagementDAOFactory.closeConnection();
|
||||
}
|
||||
if (requireDeviceInfo) {
|
||||
device = this.getAllDeviceInfo(device);
|
||||
}
|
||||
return device;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendEnrolmentInvitation(String templateName, EmailMetaInfo metaInfo) throws DeviceManagementException,
|
||||
ConfigurationManagementException {
|
||||
if (metaInfo == null) {
|
||||
String msg = "Received incomplete data to method sendEnrolmentInvitation";
|
||||
log.error(msg);
|
||||
@ -798,6 +844,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
|
||||
String msg = "Error occurred while sending enrollment invitation";
|
||||
log.error(msg, ex);
|
||||
throw new DeviceManagementException(msg, ex);
|
||||
} catch (EmailTransportNotConfiguredException ex) {
|
||||
String msg = "Mail Server is not configured.";
|
||||
throw new ConfigurationManagementException(msg, ex);
|
||||
} catch (Exception ex) {
|
||||
String msg = "Error occurred in setEnrollmentInvitation";
|
||||
log.error(msg, ex);
|
||||
@ -806,7 +855,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException {
|
||||
public void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException,
|
||||
ConfigurationManagementException {
|
||||
if (metaInfo == null) {
|
||||
String msg = "Received incomplete request for sendRegistrationEmail";
|
||||
log.error(msg);
|
||||
@ -815,6 +865,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Send registration email");
|
||||
}
|
||||
EmailSenderService emailSenderService = DeviceManagementDataHolder.getInstance().getEmailSenderService();
|
||||
if (emailSenderService != null) {
|
||||
Map<String, TypedValue<Class<?>, Object>> params = new HashMap<>();
|
||||
params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.FIRST_NAME,
|
||||
new TypedValue<Class<?>, Object>(String.class, metaInfo.getProperty("first-name")));
|
||||
@ -835,17 +887,21 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
|
||||
DeviceManagementConstants.EmailAttributes.USER_REGISTRATION_TEMPLATE,
|
||||
params),
|
||||
metaInfo.getRecipients()).build();
|
||||
DeviceManagementDataHolder.getInstance().getEmailSenderService().sendEmail(ctx);
|
||||
emailSenderService.sendEmail(ctx);
|
||||
} catch (EmailSendingFailedException e) {
|
||||
String msg = "Error occurred while sending user registration notification." + e.getMessage();
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
} catch (EmailTransportNotConfiguredException e) {
|
||||
String msg = "Error occurred while sending user registration email." + e.getMessage();
|
||||
throw new ConfigurationManagementException(msg, e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in sendRegistrationEmail";
|
||||
String msg = "Error occurred while sending Registration Email.";
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public HashMap<Integer, Device> getTenantedDevice(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
|
||||
@ -969,6 +1025,51 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
|
||||
return device;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Device getDevice(DeviceIdentifier deviceId, String owner, Date since, boolean requireDeviceInfo)
|
||||
throws DeviceManagementException {
|
||||
if (deviceId == null || since == null) {
|
||||
String msg = "Received incomplete data for getDevice";
|
||||
log.error(msg);
|
||||
throw new DeviceManagementException(msg);
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Get device since '" + since.toString() + "' with identifier: " + deviceId.getId()
|
||||
+ " and type '" + deviceId.getType() + "' and owner '" + owner + "'");
|
||||
}
|
||||
Device device;
|
||||
try {
|
||||
DeviceManagementDAOFactory.openConnection();
|
||||
device = deviceDAO.getDevice(deviceId, owner, since, this.getTenantId());
|
||||
if (device == null) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("No device is found upon the type '" + deviceId.getType() + "' and id '" +
|
||||
deviceId.getId() + "' and owner name '" + owner + "'");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
} catch (DeviceManagementDAOException e) {
|
||||
String msg = "Error occurred while obtaining the device for id '" + deviceId.getId() + "' and owner '" +
|
||||
owner + "'";
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while opening a connection to the data source";
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in getDevice for device: " + deviceId.getId() + " and owner: " + owner;
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
} finally {
|
||||
DeviceManagementDAOFactory.closeConnection();
|
||||
}
|
||||
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);
|
||||
@ -1323,11 +1424,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
|
||||
.updateOperation(deviceId, operation);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteOperation(String type, int operationId) throws OperationManagementException {
|
||||
pluginRepository.getOperationManager(type, this.getTenantId()).deleteOperation(operationId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId,
|
||||
int operationId) throws OperationManagementException {
|
||||
@ -1357,11 +1453,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
|
||||
return DeviceManagementDataHolder.getInstance().getOperationManager().getOperationByActivityIdAndDevice(activity, deviceId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Activity> getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException {
|
||||
return DeviceManagementDataHolder.getInstance().getOperationManager().getActivitiesUpdatedAfter(timestamp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Activity> getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementException {
|
||||
limit = DeviceManagerUtil.validateActivityListPageSize(limit);
|
||||
@ -1650,6 +1741,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
|
||||
if (requireDeviceInfo) {
|
||||
this.getAllDeviceInfo(userDevices);
|
||||
}
|
||||
devices.addAll(userDevices);
|
||||
}
|
||||
return devices;
|
||||
}
|
||||
@ -1720,15 +1812,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Get devices by name " + request.toString() + " and requiredDeviceInfo: " + requireDeviceInfo);
|
||||
}
|
||||
List<Device> devices = new ArrayList<>();
|
||||
List<Device> allDevices;
|
||||
int limit = DeviceManagerUtil.validateDeviceListPageSize(request.getRowCount());
|
||||
try {
|
||||
DeviceManagementDAOFactory.openConnection();
|
||||
allDevices = deviceDAO.getDevicesByNameAndType(request.getDeviceName(), request.getDeviceType(),
|
||||
this.getTenantId(), request.getStartIndex(), limit);
|
||||
List<Device> filterd = null;
|
||||
filterd.get(0);
|
||||
} catch (DeviceManagementDAOException e) {
|
||||
String msg = "Error occurred while fetching the list of devices that matches to '"
|
||||
+ request.getDeviceName() + "'";
|
||||
@ -1802,41 +1891,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status status) throws DeviceManagementException {
|
||||
try {
|
||||
if (device == null || status == null) {
|
||||
String msg = "Received incomplete data for updateDeviceEnrolmentInfo";
|
||||
log.error(msg);
|
||||
throw new DeviceManagementException(msg);
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Updating enrolment for device: " + device.getId() + " of type '" + device.getType() + "'");
|
||||
}
|
||||
DeviceManagementDAOFactory.beginTransaction();
|
||||
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
|
||||
device.getEnrolmentInfo().setStatus(status);
|
||||
deviceDAO.updateDevice(device, this.getTenantId());
|
||||
DeviceManagementDAOFactory.commitTransaction();
|
||||
} catch (DeviceManagementDAOException e) {
|
||||
DeviceManagementDAOFactory.rollbackTransaction();
|
||||
String msg = "Error occurred while updating device enrolment status for " + device.getDeviceIdentifier() +
|
||||
" of type " + device.getType();
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
} catch (TransactionManagementException e) {
|
||||
String msg = "Error occurred while initiating transaction";
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in updateDeviceEnrolmentInfo";
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
} finally {
|
||||
DeviceManagementDAOFactory.closeConnection();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerDeviceManagementService(DeviceManagementService deviceManagementService) {
|
||||
if (log.isDebugEnabled()) {
|
||||
@ -2333,8 +2387,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
|
||||
DeviceManagementDAOFactory.openConnection();
|
||||
info = deviceInfoDAO.getDeviceInformation(device.getId());
|
||||
DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId());
|
||||
if (location != null) {
|
||||
//There are some cases where the device-info is not updated properly. Hence returning a null value.
|
||||
if (info != null) {
|
||||
info.setLocation(location);
|
||||
} else {
|
||||
info = new DeviceInfo();
|
||||
info.setLocation(location);
|
||||
}
|
||||
}
|
||||
} catch (DeviceDetailsMgtDAOException e) {
|
||||
String msg = "Error occurred while retrieving advance info of '" + device.getType() +
|
||||
|
||||
@ -27,6 +27,7 @@ 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.GroupNotExistException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@ -53,7 +54,7 @@ public interface GroupManagementProviderService {
|
||||
* @param groupId of the group.
|
||||
* @throws GroupManagementException
|
||||
*/
|
||||
void updateGroup(DeviceGroup deviceGroup, int groupId) throws GroupManagementException, GroupAlreadyExistException;
|
||||
void updateGroup(DeviceGroup deviceGroup, int groupId) throws GroupManagementException, GroupNotExistException;
|
||||
|
||||
/**
|
||||
* Delete existing device group.
|
||||
|
||||
@ -73,9 +73,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Creating group '" + deviceGroup.getName() + "'");
|
||||
}
|
||||
if (deviceGroup == null) {
|
||||
throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException());
|
||||
}
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
try {
|
||||
GroupManagementDAOFactory.beginTransaction();
|
||||
@ -95,6 +92,8 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
String msg = "Error occurred while initiating transaction.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (GroupAlreadyExistException ex) {
|
||||
throw ex;
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in creating group '" + deviceGroup.getName() + "'";
|
||||
log.error(msg, e);
|
||||
@ -113,7 +112,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
*/
|
||||
@Override
|
||||
public void updateGroup(DeviceGroup deviceGroup, int groupId)
|
||||
throws GroupManagementException, GroupAlreadyExistException {
|
||||
throws GroupManagementException, GroupNotExistException {
|
||||
if (deviceGroup == null) {
|
||||
String msg = "Received incomplete data for updateGroup";
|
||||
log.error(msg);
|
||||
@ -122,30 +121,29 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("update group '" + deviceGroup.getName() + "'");
|
||||
}
|
||||
if (deviceGroup == null) {
|
||||
throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException());
|
||||
}
|
||||
try {
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
GroupManagementDAOFactory.beginTransaction();
|
||||
DeviceGroup existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId);
|
||||
if (existingGroup == null || existingGroup.getGroupId() == groupId) {
|
||||
DeviceGroup existingGroup = this.groupDAO.getGroup(groupId, tenantId);
|
||||
if (existingGroup != null) {
|
||||
this.groupDAO.updateGroup(deviceGroup, groupId, tenantId);
|
||||
GroupManagementDAOFactory.commitTransaction();
|
||||
} else {
|
||||
throw new GroupAlreadyExistException("Group exist with name " + deviceGroup.getName());
|
||||
throw new GroupNotExistException("Group with ID - '" + groupId + "' doesn't exists!");
|
||||
}
|
||||
} catch (GroupManagementDAOException e) {
|
||||
GroupManagementDAOFactory.rollbackTransaction();
|
||||
String msg = "Error occurred while modifying deviceGroup '" + deviceGroup.getName() + "'.";
|
||||
String msg = "Error occurred while modifying device group with ID - '" + groupId + "'.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (TransactionManagementException e) {
|
||||
String msg = "Error occurred while initiating transaction.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (GroupNotExistException ex) {
|
||||
throw ex;
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in updating group '" + deviceGroup.getName() + "'";
|
||||
String msg = "Error occurred in updating the device group with ID - '" + groupId + "'.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} finally {
|
||||
@ -261,7 +259,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Get groups");
|
||||
}
|
||||
List<DeviceGroup> deviceGroups = new ArrayList<>();
|
||||
List<DeviceGroup> deviceGroups;
|
||||
try {
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
GroupManagementDAOFactory.openConnection();
|
||||
@ -295,7 +293,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
log.debug("Get groups with pagination " + request.toString());
|
||||
}
|
||||
request = DeviceManagerUtil.validateGroupListPageSize(request);
|
||||
List<DeviceGroup> deviceGroups = new ArrayList<>();
|
||||
List<DeviceGroup> deviceGroups;
|
||||
try {
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
GroupManagementDAOFactory.openConnection();
|
||||
@ -347,17 +345,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
for (DeviceGroup deviceGroup : deviceGroups) {
|
||||
groups.put(deviceGroup.getGroupId(), deviceGroup);
|
||||
}
|
||||
} catch (UserStoreException e) {
|
||||
String msg = "Error occurred while getting user store manager.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (SQLException e) {
|
||||
} catch (UserStoreException | SQLException | GroupManagementDAOException e) {
|
||||
String msg = "Error occurred while retrieving all groups accessible to user.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (GroupManagementDAOException e) {
|
||||
log.error(e);
|
||||
throw new GroupManagementException(e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in getGroups for " + username;
|
||||
log.error(msg, e);
|
||||
@ -369,16 +360,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
}
|
||||
|
||||
private List<Integer> getGroupIds(String username) throws GroupManagementException {
|
||||
if (username == null || username.isEmpty()) {
|
||||
String msg = "Received empty user name for getGroupIds";
|
||||
log.error(msg);
|
||||
throw new GroupManagementException(msg);
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Get groups Ids of owner '" + username + "'");
|
||||
}
|
||||
UserStoreManager userStoreManager;
|
||||
List<Integer> deviceGroupIds = new ArrayList<>();
|
||||
List<Integer> deviceGroupIds;
|
||||
try {
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
|
||||
@ -387,17 +373,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
GroupManagementDAOFactory.openConnection();
|
||||
deviceGroupIds = this.groupDAO.getOwnGroupIds(username, tenantId);
|
||||
deviceGroupIds.addAll(this.groupDAO.getGroupIds(roleList, tenantId));
|
||||
} catch (UserStoreException e) {
|
||||
String msg = "Error occurred while getting user store manager.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (SQLException e) {
|
||||
} catch (UserStoreException | SQLException | GroupManagementDAOException e) {
|
||||
String msg = "Error occurred while retrieving all groups accessible to user.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (GroupManagementDAOException e) {
|
||||
log.error(e);
|
||||
throw new GroupManagementException(e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in getGroups for username '" + username + "'";
|
||||
log.error(msg, e);
|
||||
@ -421,19 +400,15 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
}
|
||||
request = DeviceManagerUtil.validateGroupListPageSize(request);
|
||||
List<Integer> allDeviceGroupIdsOfUser = getGroupIds(currentUser);
|
||||
List<DeviceGroup> allMatchingGroups = new ArrayList<>();
|
||||
List<DeviceGroup> allMatchingGroups;
|
||||
try {
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
GroupManagementDAOFactory.openConnection();
|
||||
allMatchingGroups = this.groupDAO.getGroups(request, allDeviceGroupIdsOfUser, tenantId);
|
||||
} catch (GroupManagementDAOException e) {
|
||||
} catch (GroupManagementDAOException | SQLException e) {
|
||||
String msg = "Error occurred while retrieving all groups in tenant";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while opening a connection to the data source.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in getGroups";
|
||||
log.error(msg, e);
|
||||
@ -456,14 +431,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
GroupManagementDAOFactory.openConnection();
|
||||
return groupDAO.getGroupCount(tenantId);
|
||||
} catch (GroupManagementDAOException e) {
|
||||
} catch (GroupManagementDAOException | SQLException e) {
|
||||
String msg = "Error occurred while retrieving all groups in tenant";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while opening a connection to the data source.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred";
|
||||
log.error(msg, e);
|
||||
@ -486,14 +457,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
GroupManagementDAOFactory.openConnection();
|
||||
return groupDAO.getGroupCount(request, tenantId);
|
||||
} catch (GroupManagementDAOException e) {
|
||||
} catch (GroupManagementDAOException | SQLException e) {
|
||||
String msg = "Error occurred while retrieving all groups in tenant";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while opening a connection to the data source.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in getGroupCount";
|
||||
log.error(msg, e);
|
||||
@ -527,18 +494,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
count = groupDAO.getOwnGroupsCount(username, tenantId);
|
||||
count += groupDAO.getGroupsCount(roleList, tenantId);
|
||||
return count;
|
||||
} catch (UserStoreException e) {
|
||||
String msg = "Error occurred while getting user store manager.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (GroupManagementDAOException e) {
|
||||
} catch (UserStoreException | GroupManagementDAOException | SQLException e) {
|
||||
String msg = "Error occurred while retrieving group count of user '" + username + "'";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while opening a connection to the data source.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in getGroupCount for username '" + username + "'";
|
||||
log.error(msg, e);
|
||||
@ -615,14 +574,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
GroupManagementDAOFactory.openConnection();
|
||||
return groupDAO.getRoles(groupId, tenantId);
|
||||
} catch (GroupManagementDAOException e) {
|
||||
} catch (GroupManagementDAOException | SQLException e) {
|
||||
String msg = "Error occurred while retrieving all groups in tenant";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while opening a connection to the data source.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in getRoles for groupId: " + groupId;
|
||||
log.error(msg, e);
|
||||
@ -647,18 +602,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
rowCount = DeviceManagerUtil.validateDeviceListPageSize(rowCount);
|
||||
GroupManagementDAOFactory.openConnection();
|
||||
devices = this.groupDAO.getDevices(groupId, startIndex, rowCount, tenantId);
|
||||
} catch (GroupManagementDAOException e) {
|
||||
} catch (GroupManagementDAOException | SQLException | DeviceManagementException e) {
|
||||
String msg = "Error occurred while getting devices in group.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while opening a connection to the data source.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while validating the limit of the devices to be returned";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in getDevices for groupId: " + groupId;
|
||||
log.error(msg, e);
|
||||
@ -680,14 +627,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
try {
|
||||
GroupManagementDAOFactory.openConnection();
|
||||
return groupDAO.getDeviceCount(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId());
|
||||
} catch (GroupManagementDAOException e) {
|
||||
} catch (GroupManagementDAOException | SQLException e) {
|
||||
String msg = "Error occurred while retrieving all groups in tenant";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while opening a connection to the data source.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in getDeviceCount for groupId: " + groupId;
|
||||
log.error(msg, e);
|
||||
@ -838,18 +781,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
GroupManagementDAOFactory.openConnection();
|
||||
return groupDAO.getGroups(device.getId(),
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while retrieving the device details.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (GroupManagementDAOException e) {
|
||||
} catch (DeviceManagementException | GroupManagementDAOException | SQLException e) {
|
||||
String msg = "Error occurred while retrieving device groups.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while opening database connection.";
|
||||
log.error(msg, e);
|
||||
throw new GroupManagementException(msg, e);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred in getGroups";
|
||||
log.error(msg, e);
|
||||
|
||||
@ -21,6 +21,7 @@ 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.caching.impl.CacheImpl;
|
||||
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;
|
||||
@ -76,7 +77,7 @@ public final class DeviceManagerUtil {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceManagerUtil.class);
|
||||
|
||||
private static boolean isDeviceCacheInistialized = false;
|
||||
private static boolean isDeviceCacheInitialized = false;
|
||||
|
||||
public static Document convertToDocument(File file) throws DeviceManagementException {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
@ -473,6 +474,13 @@ public final class DeviceManagerUtil {
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isDeviceExists(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
|
||||
Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier,
|
||||
false);
|
||||
return !(device == null || device.getDeviceIdentifier() == null ||
|
||||
device.getDeviceIdentifier().isEmpty() || device.getEnrolmentInfo() == null);
|
||||
}
|
||||
|
||||
private static CacheManager getCacheManager() {
|
||||
return Caching.getCacheManagerFactory().getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER);
|
||||
}
|
||||
@ -492,16 +500,21 @@ public final class DeviceManagerUtil {
|
||||
public static void initializeDeviceCache() {
|
||||
DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
|
||||
int deviceCacheExpiry = config.getDeviceCacheConfiguration().getExpiryTime();
|
||||
long deviceCacheCapacity = config.getDeviceCacheConfiguration().getCapacity();
|
||||
CacheManager manager = getCacheManager();
|
||||
if (config.getDeviceCacheConfiguration().isEnabled()) {
|
||||
if(!isDeviceCacheInistialized) {
|
||||
isDeviceCacheInistialized = true;
|
||||
if(!isDeviceCacheInitialized) {
|
||||
isDeviceCacheInitialized = true;
|
||||
if (manager != null) {
|
||||
if (deviceCacheExpiry > 0) {
|
||||
manager.<DeviceCacheKey, Device>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();
|
||||
if(deviceCacheCapacity > 0 ) {
|
||||
((CacheImpl)(manager.<DeviceCacheKey, Device>getCache(DeviceManagementConstants.DEVICE_CACHE))).
|
||||
setCapacity(deviceCacheCapacity);
|
||||
}
|
||||
} else {
|
||||
manager.<DeviceCacheKey, Device>getCache(DeviceManagementConstants.DEVICE_CACHE);
|
||||
}
|
||||
@ -512,6 +525,8 @@ public final class DeviceManagerUtil {
|
||||
setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
|
||||
deviceCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
|
||||
Duration(TimeUnit.SECONDS, deviceCacheExpiry)).setStoreByValue(true).build();
|
||||
((CacheImpl)(manager.<DeviceCacheKey, Device>getCache(DeviceManagementConstants.DEVICE_CACHE))).
|
||||
setCapacity(deviceCacheCapacity);
|
||||
} else {
|
||||
Caching.getCacheManager().<DeviceCacheKey, Device>getCache(DeviceManagementConstants.DEVICE_CACHE);
|
||||
}
|
||||
@ -525,7 +540,7 @@ public final class DeviceManagerUtil {
|
||||
CacheManager manager = getCacheManager();
|
||||
Cache<DeviceCacheKey, Device> deviceCache = null;
|
||||
if (config.getDeviceCacheConfiguration().isEnabled()) {
|
||||
if(!isDeviceCacheInistialized) {
|
||||
if(!isDeviceCacheInitialized) {
|
||||
initializeDeviceCache();
|
||||
}
|
||||
if (manager != null) {
|
||||
|
||||
@ -21,17 +21,21 @@ import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManager;
|
||||
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
|
||||
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
|
||||
import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.task.impl.DeviceTaskManagerServiceImpl;
|
||||
|
||||
public class DeviceManagementRepositoryTests{
|
||||
|
||||
private DeviceManagementPluginRepository repository;
|
||||
|
||||
@BeforeClass
|
||||
public void initRepository() {
|
||||
public void init() throws Exception {
|
||||
this.repository = new DeviceManagementPluginRepository();
|
||||
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(new DeviceTaskManagerServiceImpl());
|
||||
DeviceManagementDataHolder.getInstance().setTaskService(new TestTaskServiceImpl());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@ -24,15 +24,27 @@ import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubsc
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
|
||||
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class TestDeviceManagementService implements DeviceManagementService {
|
||||
|
||||
private String providerType;
|
||||
private String tenantDomain;
|
||||
private String operationCode;
|
||||
|
||||
public TestDeviceManagementService(String deviceType, String tenantDomain, String operationCode) {
|
||||
providerType = deviceType;
|
||||
this.tenantDomain = tenantDomain;
|
||||
this.operationCode = operationCode;
|
||||
}
|
||||
|
||||
public TestDeviceManagementService(String deviceType, String tenantDomain) {
|
||||
providerType = deviceType;
|
||||
this.tenantDomain = tenantDomain;
|
||||
this.operationCode = "default";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return providerType;
|
||||
@ -40,7 +52,16 @@ public class TestDeviceManagementService implements DeviceManagementService {
|
||||
|
||||
@Override
|
||||
public OperationMonitoringTaskConfig getOperationMonitoringConfig() {
|
||||
return null;
|
||||
OperationMonitoringTaskConfig taskConfig = new OperationMonitoringTaskConfig();
|
||||
taskConfig.setEnabled(true);
|
||||
taskConfig.setFrequency(3000);
|
||||
List<MonitoringOperation> monitoringOperations = new ArrayList<>();
|
||||
MonitoringOperation monitoringOperation = new MonitoringOperation();
|
||||
monitoringOperation.setTaskName(operationCode);
|
||||
monitoringOperation.setRecurrentTimes(2);
|
||||
monitoringOperations.add(monitoringOperation);
|
||||
taskConfig.setMonitoringOperation(monitoringOperations);
|
||||
return taskConfig;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@ -50,22 +50,22 @@ public class TestDeviceManager implements DeviceManager {
|
||||
|
||||
@Override
|
||||
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@ -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.core;
|
||||
|
||||
import org.wso2.carbon.device.mgt.core.task.TestTaskManagerImpl;
|
||||
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.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class TestTaskServiceImpl implements TaskService {
|
||||
private Set<String> registeredTaskTypes;
|
||||
private TaskManager taskManager;
|
||||
|
||||
public TestTaskServiceImpl() {
|
||||
|
||||
this.registeredTaskTypes = new HashSet<>();
|
||||
this.taskManager = new TestTaskManagerImpl();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TaskManager getTaskManager(String s) throws TaskException {
|
||||
return this.taskManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TaskManager> getAllTenantTaskManagersForType(String s) throws TaskException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerTaskType(String s) throws TaskException {
|
||||
this.registeredTaskTypes.add(s);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> getRegisteredTaskTypes() {
|
||||
return this.registeredTaskTypes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serverInitialized() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isServerInit() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TaskServiceConfiguration getServerConfiguration() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runAfterRegistrationActions() throws TaskException {
|
||||
|
||||
}
|
||||
}
|
||||
@ -19,11 +19,24 @@ package org.wso2.carbon.device.mgt.core;
|
||||
|
||||
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.GroupPaginationRequest;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
|
||||
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
|
||||
import org.wso2.carbon.registry.core.config.RegistryContext;
|
||||
import org.wso2.carbon.registry.core.exceptions.RegistryException;
|
||||
import org.wso2.carbon.registry.core.internal.RegistryDataHolder;
|
||||
import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService;
|
||||
import org.wso2.carbon.registry.core.service.RegistryService;
|
||||
import org.wso2.carbon.user.core.service.RealmService;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class TestUtils {
|
||||
|
||||
@ -53,4 +66,63 @@ public class TestUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public static DeviceGroup createDeviceGroup1(){
|
||||
DeviceGroup group = new DeviceGroup();
|
||||
group.setName("TEST_GROUP_01");
|
||||
group.setDescription("TEST_GROUP_01 - Description");
|
||||
group.setOwner("admin");
|
||||
return group;
|
||||
}
|
||||
|
||||
|
||||
public static DeviceGroup createDeviceGroup2(){
|
||||
DeviceGroup group = new DeviceGroup();
|
||||
group.setName("TEST_GROUP_02");
|
||||
group.setDescription("TEST_GROUP_02 - Description");
|
||||
group.setOwner("admin");
|
||||
return group;
|
||||
}
|
||||
|
||||
public static DeviceGroup createDeviceGroup3(){
|
||||
DeviceGroup group = new DeviceGroup();
|
||||
group.setName("TEST_GROUP_03");
|
||||
group.setDescription("TEST_GROUP_03 - Description");
|
||||
group.setOwner("admin");
|
||||
return group;
|
||||
}
|
||||
|
||||
public static DeviceGroup createDeviceGroup4(){
|
||||
DeviceGroup group = new DeviceGroup();
|
||||
group.setName("TEST_GROUP_04");
|
||||
group.setDescription("TEST_GROUP_04 - Description");
|
||||
group.setOwner("admin");
|
||||
return group;
|
||||
}
|
||||
|
||||
|
||||
public static GroupPaginationRequest createPaginationRequest(){
|
||||
GroupPaginationRequest request = new GroupPaginationRequest(0, 5);
|
||||
return request;
|
||||
}
|
||||
|
||||
public static List<DeviceIdentifier> getDeviceIdentifiersList(){
|
||||
DeviceIdentifier identifier = new DeviceIdentifier();
|
||||
identifier.setId("12345");
|
||||
identifier.setType("Test");
|
||||
|
||||
List<DeviceIdentifier> list = new ArrayList<>();
|
||||
list.add(identifier);
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public static RegistryService getRegistryService(Class clazz) throws RegistryException {
|
||||
RealmService realmService = new InMemoryRealmService();
|
||||
RegistryDataHolder.getInstance().setRealmService(realmService);
|
||||
DeviceManagementDataHolder.getInstance().setRealmService(realmService);
|
||||
InputStream is = clazz.getClassLoader().getResourceAsStream("carbon-home/repository/conf/registry.xml");
|
||||
RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
|
||||
context.setSetup(true);
|
||||
return context.getEmbeddedRegistryService();
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,356 @@
|
||||
/*
|
||||
* 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.authorization;
|
||||
|
||||
import org.apache.commons.dbcp.BasicDataSource;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.mockito.Mockito;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.AfterClass;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.CarbonConstants;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceNotFoundException;
|
||||
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.DeviceAuthorizationResult;
|
||||
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.permission.mgt.PermissionManagementException;
|
||||
import org.wso2.carbon.device.mgt.core.TestDeviceManagementService;
|
||||
import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
|
||||
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.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
|
||||
import org.wso2.carbon.registry.core.config.RegistryContext;
|
||||
import org.wso2.carbon.registry.core.exceptions.RegistryException;
|
||||
import org.wso2.carbon.registry.core.internal.RegistryDataHolder;
|
||||
import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService;
|
||||
import org.wso2.carbon.registry.core.service.RegistryService;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
import org.wso2.carbon.user.api.UserStoreManager;
|
||||
import org.wso2.carbon.user.api.Permission;
|
||||
import org.wso2.carbon.user.core.service.RealmService;
|
||||
import org.wso2.carbon.user.core.tenant.JDBCTenantManager;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
import java.util.HashMap;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Unit tests for DeviceAccessAuthorizationServiceTest
|
||||
*/
|
||||
public class DeviceAccessAuthorizationServiceTest {
|
||||
private static final Log log = LogFactory.getLog(DeviceAccessAuthorizationServiceTest.class);
|
||||
private static final String DEVICE_TYPE = "AUTH_SERVICE_TEST_TYPE";
|
||||
private static final int NO_OF_DEVICES = 5;
|
||||
private static final String ADMIN_USER = "admin";
|
||||
private static final String NON_ADMIN_ALLOWED_USER = "nonAdmin";
|
||||
private static final String NORMAL_USER = "normal";
|
||||
private static final String ADMIN_ROLE = "adminRole";
|
||||
private static final String NON_ADMIN_ROLE = "nonAdminRole";
|
||||
private static final String DEFAULT_GROUP = "defaultGroup";
|
||||
private static final String DEVICE_ID_PREFIX = "AUTH-SERVICE-TEST-DEVICE-ID-";
|
||||
private static final String USER_CLAIM_EMAIL_ADDRESS = "http://wso2.org/claims/emailaddress";
|
||||
private static final String USER_CLAIM_FIRST_NAME = "http://wso2.org/claims/givenname";
|
||||
private static final String USER_CLAIM_LAST_NAME = "http://wso2.org/claims/lastname";
|
||||
private static final String ADMIN_PERMISSION = "/permission/admin";
|
||||
private static final String NON_ADMIN_PERMISSION = "/permission/admin/manage/device-mgt/devices/owning-device/view";
|
||||
private static final String FIRST_NAME = "firstName";
|
||||
private static final String LAST_NAME = "lastName";
|
||||
private static final String EMAIL = "email";
|
||||
private static final String PASSWORD = "password";
|
||||
private DeviceAccessAuthorizationServiceImpl deviceAccessAuthorizationService;
|
||||
private List<DeviceIdentifier> deviceIds = new ArrayList<>();
|
||||
private List<DeviceIdentifier> groupDeviceIds = new ArrayList<>();
|
||||
private Map<String, String> defaultUserClaims;
|
||||
|
||||
@BeforeClass
|
||||
public void init() throws Exception {
|
||||
DeviceConfigurationManager.getInstance().initConfig();
|
||||
log.info("Initializing test environment to test DeviceAccessAuthorization Class");
|
||||
for (int i = 0; i < NO_OF_DEVICES; i++) {
|
||||
deviceIds.add(new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE));
|
||||
}
|
||||
List<Device> devices = TestDataHolder.generateDummyDeviceData(this.deviceIds);
|
||||
DeviceManagementProviderService deviceMgtService = new DeviceManagementProviderServiceImpl();
|
||||
DeviceManagementServiceComponent.notifyStartupListeners();
|
||||
DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceMgtService);
|
||||
DeviceManagementDataHolder.getInstance().setRegistryService(getRegistryService());
|
||||
DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(new
|
||||
GroupManagementProviderServiceImpl());
|
||||
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null);
|
||||
deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE,
|
||||
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME));
|
||||
for (Device device : devices) {
|
||||
deviceMgtService.enrollDevice(device);
|
||||
}
|
||||
List<Device> returnedDevices = deviceMgtService.getAllDevices(DEVICE_TYPE);
|
||||
for (Device device : returnedDevices) {
|
||||
if (!device.getDeviceIdentifier().startsWith(DEVICE_ID_PREFIX)) {
|
||||
throw new Exception("Incorrect device with ID - " + device.getDeviceIdentifier() + " returned!");
|
||||
}
|
||||
}
|
||||
deviceAccessAuthorizationService = Mockito.mock(DeviceAccessAuthorizationServiceImpl.class,
|
||||
Mockito.CALLS_REAL_METHODS);
|
||||
defaultUserClaims = buildDefaultUserClaims(FIRST_NAME, LAST_NAME, EMAIL);
|
||||
initializeTestEnvironment();
|
||||
//Starting tenant flow
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID, true);
|
||||
}
|
||||
|
||||
private RegistryService getRegistryService() throws RegistryException, UserStoreException {
|
||||
RealmService realmService = new InMemoryRealmService();
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
|
||||
BasicDataSource dataSource = new BasicDataSource();
|
||||
String connectionUrl = "jdbc:h2:./target/databasetest/CARBON_TEST";
|
||||
dataSource.setUrl(connectionUrl);
|
||||
dataSource.setDriverClassName("org.h2.Driver");
|
||||
JDBCTenantManager jdbcTenantManager = new JDBCTenantManager(dataSource,
|
||||
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
|
||||
realmService.setTenantManager(jdbcTenantManager);
|
||||
RegistryDataHolder.getInstance().setRealmService(realmService);
|
||||
DeviceManagementDataHolder.getInstance().setRealmService(realmService);
|
||||
InputStream is = this.getClass().getClassLoader().getResourceAsStream("carbon-home/repository/conf/registry.xml");
|
||||
RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
|
||||
context.setSetup(true);
|
||||
return context.getEmbeddedRegistryService();
|
||||
}
|
||||
|
||||
private void initializeTestEnvironment() throws UserStoreException, GroupManagementException,
|
||||
RoleDoesNotExistException, DeviceNotFoundException {
|
||||
//creating UI permission
|
||||
Permission adminPermission = new Permission(ADMIN_PERMISSION, CarbonConstants.UI_PERMISSION_ACTION);
|
||||
Permission deviceViewPermission = new Permission(NON_ADMIN_PERMISSION, CarbonConstants.UI_PERMISSION_ACTION);
|
||||
UserStoreManager userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService()
|
||||
.getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getUserStoreManager();
|
||||
//Adding a non Admin User
|
||||
userStoreManager.addUser(NON_ADMIN_ALLOWED_USER, PASSWORD, null, defaultUserClaims, null);
|
||||
//Adding a normal user
|
||||
userStoreManager.addUser(NORMAL_USER, PASSWORD, null, defaultUserClaims, null);
|
||||
//Adding role with permission to Admin user
|
||||
userStoreManager.addRole(ADMIN_ROLE, new String[]{ADMIN_USER}, new Permission[]{adminPermission});
|
||||
//Adding role with permission to non Admin user
|
||||
userStoreManager.addRole(NON_ADMIN_ROLE, new String[]{NON_ADMIN_ALLOWED_USER},
|
||||
new Permission[]{deviceViewPermission});
|
||||
//Creating default group
|
||||
GroupManagementProviderService groupManagementProviderService = DeviceManagementDataHolder.getInstance()
|
||||
.getGroupManagementProviderService();
|
||||
groupManagementProviderService.createDefaultGroup(DEFAULT_GROUP);
|
||||
int groupId = groupManagementProviderService.getGroup(DEFAULT_GROUP).getGroupId();
|
||||
//Sharing group with admin and non admin roles
|
||||
groupManagementProviderService.manageGroupSharing(groupId, new ArrayList<>(Arrays.asList(ADMIN_ROLE,
|
||||
NON_ADMIN_ROLE)));
|
||||
//Adding first 2 devices to the group
|
||||
groupDeviceIds.add(deviceIds.get(0));
|
||||
groupDeviceIds.add(deviceIds.get(1));
|
||||
groupManagementProviderService.addDevices(groupId, groupDeviceIds);
|
||||
}
|
||||
|
||||
private Map<String, String> buildDefaultUserClaims(String firstName, String lastName, String emailAddress) {
|
||||
Map<String, String> defaultUserClaims = new HashMap<>();
|
||||
defaultUserClaims.put(USER_CLAIM_FIRST_NAME, firstName);
|
||||
defaultUserClaims.put(USER_CLAIM_LAST_NAME, lastName);
|
||||
defaultUserClaims.put(USER_CLAIM_EMAIL_ADDRESS, emailAddress);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Default claim map is created for new user: " + defaultUserClaims.toString());
|
||||
}
|
||||
return defaultUserClaims;
|
||||
}
|
||||
|
||||
//Admin User test cases
|
||||
@Test(description = "Check authorization giving a device identifier and username")
|
||||
public void userAuthDevIdUserName() throws Exception {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
|
||||
for (DeviceIdentifier deviceId : deviceIds) {
|
||||
Assert.assertTrue(deviceAccessAuthorizationService.isUserAuthorized(deviceId, ADMIN_USER),
|
||||
"Device access authorization for admin user failed");
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "Authorization for multiple device identifiers and username")
|
||||
public void userAuthDevIdUserNameResult() throws DeviceAccessAuthorizationException {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
|
||||
DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
|
||||
isUserAuthorized(deviceIds, ADMIN_USER);
|
||||
Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 5,
|
||||
"Expected 5 authorized devices for admin user");
|
||||
Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 0,
|
||||
"Expected 0 un-authorized devices for admin user");
|
||||
}
|
||||
|
||||
@Test(description = "Authorization by device identifier")
|
||||
public void userAuthDevId() throws Exception {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
|
||||
for (DeviceIdentifier deviceId : deviceIds) {
|
||||
Assert.assertTrue(deviceAccessAuthorizationService.isUserAuthorized(deviceId),
|
||||
"Authorize user from device identifier failed");
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "Authorization by multiple device identifiers")
|
||||
public void userAuthDevIdResult() throws Exception {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
|
||||
DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
|
||||
isUserAuthorized(deviceIds);
|
||||
Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 5,
|
||||
"Expected 5 authorized devices for admin user");
|
||||
Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 0,
|
||||
"Expected 0 un-authorized devices for admin user");
|
||||
}
|
||||
|
||||
@Test(description = "Check current user is a device administrator")
|
||||
public void isDevAdminAdminUser() throws DeviceAccessAuthorizationException, UserStoreException,
|
||||
PermissionManagementException {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
|
||||
Assert.assertTrue(deviceAccessAuthorizationService.isDeviceAdminUser(),
|
||||
"Admin user failed to authorize as admin");
|
||||
}
|
||||
|
||||
//Non admin user tests
|
||||
@Test(description = "Check authorization by device identifier and permission Allowed test case")
|
||||
public void userAuthDevIdPermission() throws DeviceAccessAuthorizationException, UserStoreException,
|
||||
PermissionManagementException {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
|
||||
Assert.assertTrue(deviceAccessAuthorizationService.isUserAuthorized(deviceIds.get(0),
|
||||
new String[]{NON_ADMIN_PERMISSION}), "Non admin user with permissions attempt to access failed");
|
||||
}
|
||||
|
||||
@Test(description = "Check authorization by device identifier and permission Not-allowed test case")
|
||||
public void userAuthFalseDevIdPermission() throws DeviceAccessAuthorizationException, UserStoreException,
|
||||
PermissionManagementException {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
|
||||
Assert.assertFalse(deviceAccessAuthorizationService.isUserAuthorized(deviceIds.get(3),
|
||||
new String[]{NON_ADMIN_PERMISSION}), "Non admin user accessing not allowed device authorized");
|
||||
}
|
||||
|
||||
@Test(description = "Authorization by giving a device identifier, username and permission Allowed test case")
|
||||
public void userAuthDevIdUserNamePermission() throws DeviceAccessAuthorizationException, UserStoreException,
|
||||
PermissionManagementException {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
|
||||
Assert.assertTrue(deviceAccessAuthorizationService.isUserAuthorized(deviceIds.get(0), NON_ADMIN_ALLOWED_USER,
|
||||
new String[]{NON_ADMIN_PERMISSION}), "Non admin user with permissions attempt to access failed");
|
||||
}
|
||||
|
||||
@Test(description = "Authorization by giving a device identifier, username and permission Not-allowed test case")
|
||||
public void userAuthFalseDevIdUserNamePermission() throws DeviceAccessAuthorizationException, UserStoreException,
|
||||
PermissionManagementException {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
|
||||
Assert.assertFalse(deviceAccessAuthorizationService.isUserAuthorized(deviceIds.get(3), NON_ADMIN_ALLOWED_USER,
|
||||
new String[]{NON_ADMIN_PERMISSION}), "Non admin user accessing not allowed device authorized");
|
||||
}
|
||||
|
||||
@Test(description = "Authorization by giving device identifiers and permission")
|
||||
public void userAuthDevIdPermissionResult() throws DeviceAccessAuthorizationException {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
|
||||
DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
|
||||
isUserAuthorized(deviceIds, new String[]{NON_ADMIN_PERMISSION});
|
||||
Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 2,
|
||||
"Non admin user authentication to 2 devices in a shared group failed");
|
||||
Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 3,
|
||||
"Non admin user authentication to 3 devices in a non-shared group failed");
|
||||
}
|
||||
|
||||
@Test(description = "Authorization by giving device identifiers, username and permission")
|
||||
public void userAuthDevIdUserNamePermissionResult() throws DeviceAccessAuthorizationException {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
|
||||
DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
|
||||
isUserAuthorized(deviceIds, NON_ADMIN_ALLOWED_USER, new String[]{NON_ADMIN_PERMISSION});
|
||||
Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 2,
|
||||
"Non admin user authentication to 2 devices in a shared group failed");
|
||||
Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 3,
|
||||
"Non admin user authentication to 3 devices in a non-shared group failed");
|
||||
}
|
||||
|
||||
@Test(description = "Authorization for device admin called by normal user")
|
||||
public void isDevAdminNormalUser() throws DeviceAccessAuthorizationException {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NORMAL_USER);
|
||||
Assert.assertFalse(deviceAccessAuthorizationService.isDeviceAdminUser(), "Normal user allowed as admin user");
|
||||
}
|
||||
|
||||
//Check branches of isUserAuthorized
|
||||
@Test(description = "Checking branch - user is device owner")
|
||||
public void nonAdminDeviceOwner() throws DeviceAccessAuthorizationException, DeviceManagementException {
|
||||
|
||||
//Creating a temporary device
|
||||
Device device = new Device();
|
||||
EnrolmentInfo enrolmentInfo = new EnrolmentInfo(NON_ADMIN_ALLOWED_USER, EnrolmentInfo.OwnerShip.BYOD, null);
|
||||
device.setEnrolmentInfo(enrolmentInfo);
|
||||
device.setName("temp");
|
||||
device.setType(DEVICE_TYPE);
|
||||
device.setDeviceIdentifier("1234");
|
||||
DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().enrollDevice(device);
|
||||
|
||||
//temporary device identifier
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setType(DEVICE_TYPE);
|
||||
deviceIdentifier.setId("1234");
|
||||
|
||||
List<DeviceIdentifier> tempList = new ArrayList<>();
|
||||
tempList.add(deviceIdentifier);
|
||||
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
|
||||
DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
|
||||
isUserAuthorized(tempList, NON_ADMIN_ALLOWED_USER, new String[]{NON_ADMIN_PERMISSION});
|
||||
Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 1,
|
||||
"Non admin device owner failed to access device");
|
||||
Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 0,
|
||||
"Non admin device owner failed to access device");
|
||||
}
|
||||
|
||||
@Test(description = "Check authorization without giving permissions")
|
||||
public void userAuthWithoutPermissions() throws DeviceAccessAuthorizationException {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
|
||||
DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
|
||||
isUserAuthorized(deviceIds, NON_ADMIN_ALLOWED_USER, null);
|
||||
Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 0,
|
||||
"Non admin user try authentication without permission failed");
|
||||
Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 5,
|
||||
"Non admin user try authentication without permission failed");
|
||||
}
|
||||
|
||||
//check Exception cases
|
||||
@Test(description = "check a null username in isUserAuthorized method")
|
||||
public void callUserAuthWithoutUsername() throws DeviceAccessAuthorizationException {
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
|
||||
DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
|
||||
isUserAuthorized(deviceIds, "", new String[]{NON_ADMIN_PERMISSION});
|
||||
Assert.assertEquals(deviceAuthorizationResult, null,
|
||||
"Not null result for empty username in isUserAuthorized method");
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public void clearAll() {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
|
||||
}
|
||||
@ -22,7 +22,6 @@ import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.tomcat.jdbc.pool.PoolProperties;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.AfterSuite;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.BeforeSuite;
|
||||
import org.w3c.dom.Document;
|
||||
@ -30,15 +29,31 @@ import org.wso2.carbon.base.MultitenantConstants;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.core.TestUtils;
|
||||
import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
|
||||
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.internal.DeviceManagementDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
|
||||
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory;
|
||||
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
|
||||
import org.wso2.carbon.registry.core.config.RegistryContext;
|
||||
import org.wso2.carbon.registry.core.exceptions.RegistryException;
|
||||
import org.wso2.carbon.registry.core.internal.RegistryDataHolder;
|
||||
import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService;
|
||||
import org.wso2.carbon.registry.core.service.RegistryService;
|
||||
import org.wso2.carbon.user.core.service.RealmService;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import javax.xml.bind.JAXBContext;
|
||||
import javax.xml.bind.JAXBException;
|
||||
import javax.xml.bind.Unmarshaller;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
@ -54,12 +69,36 @@ public abstract class BaseDeviceManagementTest {
|
||||
this.initDataSource();
|
||||
this.initSQLScript();
|
||||
this.initializeCarbonContext();
|
||||
this.initServices();
|
||||
}
|
||||
|
||||
public void initDataSource() throws Exception {
|
||||
protected void initDataSource() throws Exception {
|
||||
this.dataSource = this.getDataSource(this.readDataSourceConfig());
|
||||
DeviceManagementDAOFactory.init(dataSource);
|
||||
GroupManagementDAOFactory.init(dataSource);
|
||||
OperationManagementDAOFactory.init(dataSource);
|
||||
NotificationManagementDAOFactory.init(dataSource);
|
||||
}
|
||||
|
||||
private void initServices() throws DeviceManagementException, RegistryException {
|
||||
DeviceConfigurationManager.getInstance().initConfig();
|
||||
DeviceManagementProviderService deviceMgtService = new DeviceManagementProviderServiceImpl();
|
||||
DeviceManagementServiceComponent.notifyStartupListeners();
|
||||
DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceMgtService);
|
||||
DeviceManagementDataHolder.getInstance().setRegistryService(getRegistryService());
|
||||
DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(new DeviceAccessAuthorizationServiceImpl());
|
||||
DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(new GroupManagementProviderServiceImpl());
|
||||
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null);
|
||||
}
|
||||
|
||||
private RegistryService getRegistryService() throws RegistryException {
|
||||
RealmService realmService = new InMemoryRealmService();
|
||||
RegistryDataHolder.getInstance().setRealmService(realmService);
|
||||
DeviceManagementDataHolder.getInstance().setRealmService(realmService);
|
||||
InputStream is = this.getClass().getClassLoader().getResourceAsStream("carbon-home/repository/conf/registry.xml");
|
||||
RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
|
||||
context.setSetup(true);
|
||||
return context.getEmbeddedRegistryService();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
@ -124,21 +163,18 @@ public abstract class BaseDeviceManagementTest {
|
||||
}
|
||||
}
|
||||
|
||||
@AfterSuite
|
||||
public void deleteData() {
|
||||
Connection conn = null;
|
||||
try {
|
||||
conn = getDataSource().getConnection();
|
||||
conn.setAutoCommit(false);
|
||||
|
||||
//TODO:FIX ME
|
||||
// this.cleanupEnrolmentData(conn);
|
||||
// this.cleanApplicationMappingData(conn);
|
||||
// this.cleanApplicationData(conn);
|
||||
// this.cleanupDeviceData(conn);
|
||||
// this.cleanupDeviceTypeData(conn);
|
||||
this.cleanupGroupData(conn);
|
||||
|
||||
String[] cleanupTables = new String[]{"DM_NOTIFICATION","DM_DEVICE_OPERATION_RESPONSE","DM_ENROLMENT_OP_MAPPING", "DM_CONFIG_OPERATION",
|
||||
"DM_POLICY_OPERATION", "DM_COMMAND_OPERATION", "DM_PROFILE_OPERATION", "DM_DEVICE_GROUP_MAP",
|
||||
"DM_GROUP", "DM_ENROLMENT", "DM_DEVICE_APPLICATION_MAPPING",
|
||||
"DM_APPLICATION", "DM_DEVICE", "DM_DEVICE_TYPE"};
|
||||
for (String table : cleanupTables) {
|
||||
this.cleanData(conn, table);
|
||||
}
|
||||
conn.commit();
|
||||
} catch (SQLException e) {
|
||||
try {
|
||||
@ -162,44 +198,13 @@ public abstract class BaseDeviceManagementTest {
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanApplicationMappingData(Connection conn) throws SQLException {
|
||||
try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_APPLICATION_MAPPING")) {
|
||||
private void cleanData(Connection conn, String tableName) throws SQLException {
|
||||
try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM " + tableName)) {
|
||||
stmt.execute();
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanApplicationData(Connection conn) throws SQLException {
|
||||
try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_APPLICATION")) {
|
||||
stmt.execute();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void cleanupEnrolmentData(Connection conn) throws SQLException {
|
||||
try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_ENROLMENT")) {
|
||||
stmt.execute();
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanupDeviceData(Connection conn) throws SQLException {
|
||||
try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_DEVICE")) {
|
||||
stmt.execute();
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanupDeviceTypeData(Connection conn) throws SQLException {
|
||||
try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_TYPE")) {
|
||||
stmt.execute();
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanupGroupData(Connection conn) throws SQLException {
|
||||
try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_GROUP")) {
|
||||
stmt.execute();
|
||||
}
|
||||
}
|
||||
|
||||
public DataSource getDataSource() {
|
||||
protected DataSource getDataSource() {
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
|
||||
@ -16,12 +16,19 @@
|
||||
package org.wso2.carbon.device.mgt.core.common;
|
||||
|
||||
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.PaginationRequest;
|
||||
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
|
||||
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
|
||||
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
|
||||
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
|
||||
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
public class TestDataHolder {
|
||||
@ -35,7 +42,6 @@ public class TestDataHolder {
|
||||
public static DeviceType initialTestDeviceType;
|
||||
|
||||
public static Device generateDummyDeviceData(String deviceType) {
|
||||
|
||||
Device device = new Device();
|
||||
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
|
||||
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
|
||||
@ -50,6 +56,71 @@ public class TestDataHolder {
|
||||
return device;
|
||||
}
|
||||
|
||||
public static DeviceInfo generateDummyDeviceInfo() {
|
||||
DeviceInfo deviceInfo = new DeviceInfo();
|
||||
deviceInfo.setIMEI("IMEI-12345");
|
||||
deviceInfo.setIMSI("IMSI-12344");
|
||||
deviceInfo.setDeviceModel("DUMMY_MODEL");
|
||||
deviceInfo.setVendor("Google");
|
||||
deviceInfo.setOsVersion("Oreo");
|
||||
deviceInfo.setOsBuildDate("24-05-2017");
|
||||
deviceInfo.setBatteryLevel(25.0);
|
||||
deviceInfo.setInternalTotalMemory(1.5);
|
||||
deviceInfo.setInternalAvailableMemory(2.5);
|
||||
deviceInfo.setExternalTotalMemory(16.76);
|
||||
deviceInfo.setExternalAvailableMemory(4.56);
|
||||
deviceInfo.setConnectionType("CON_TYPE");
|
||||
deviceInfo.setSsid("SSID");
|
||||
deviceInfo.setCpuUsage(23.5);
|
||||
deviceInfo.setTotalRAMMemory(1.5);
|
||||
deviceInfo.setAvailableRAMMemory(2.33);
|
||||
deviceInfo.setPluggedIn(true);
|
||||
return deviceInfo;
|
||||
}
|
||||
|
||||
public static Notification getNotification(int notificationId, String status, String deviceId,
|
||||
String description, String deviceName, int operationId,
|
||||
String deviceType) {
|
||||
Notification notification = new Notification();
|
||||
notification.setNotificationId(notificationId);
|
||||
notification.setStatus(status);
|
||||
notification.setDeviceIdentifier(deviceId);
|
||||
notification.setDescription(description);
|
||||
notification.setDeviceName(deviceName);
|
||||
notification.setOperationId(operationId);
|
||||
notification.setDeviceType(deviceType);
|
||||
return notification;
|
||||
}
|
||||
|
||||
public static Device generateDummyDeviceData(String deviceIdentifier, String deviceType,
|
||||
EnrolmentInfo enrolmentInfo) {
|
||||
Device device = new Device();
|
||||
device.setEnrolmentInfo(enrolmentInfo);
|
||||
device.setDescription("Test Description");
|
||||
device.setDeviceIdentifier(deviceIdentifier);
|
||||
device.setType(deviceType);
|
||||
return device;
|
||||
}
|
||||
|
||||
public static List<Device> generateDummyDeviceData(List<DeviceIdentifier> deviceIds) {
|
||||
List<Device> devices = new ArrayList<>();
|
||||
for (DeviceIdentifier deviceId : deviceIds) {
|
||||
Device device = new Device();
|
||||
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
|
||||
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
|
||||
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
|
||||
enrolmentInfo.setOwner(OWNER);
|
||||
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
|
||||
enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED);
|
||||
device.setEnrolmentInfo(enrolmentInfo);
|
||||
device.setDescription("Test Description");
|
||||
device.setDeviceIdentifier(deviceId.getId());
|
||||
device.setType(deviceId.getType());
|
||||
devices.add(device);
|
||||
}
|
||||
return devices;
|
||||
}
|
||||
|
||||
public static DeviceType generateDeviceTypeData(String devTypeName) {
|
||||
DeviceType deviceType = new DeviceType();
|
||||
deviceType.setName(devTypeName);
|
||||
@ -57,11 +128,9 @@ public class TestDataHolder {
|
||||
}
|
||||
|
||||
public static Application generateApplicationDummyData(String appIdentifier) {
|
||||
|
||||
Application application = new Application();
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("test1", "testVal");
|
||||
|
||||
application.setName("SimpleCalculator");
|
||||
application.setCategory("TestCategory");
|
||||
application.setApplicationIdentifier(appIdentifier);
|
||||
@ -70,7 +139,6 @@ public class TestDataHolder {
|
||||
application.setImageUrl("http://test.org/image/");
|
||||
application.setLocationUrl("http://test.org/location/");
|
||||
application.setAppProperties(properties);
|
||||
|
||||
return application;
|
||||
}
|
||||
|
||||
|
||||
@ -25,6 +25,7 @@ import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
|
||||
import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException;
|
||||
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
|
||||
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
|
||||
@ -54,20 +55,20 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
|
||||
GroupManagementDAOFactory.beginTransaction();
|
||||
groupId = groupDAO.addGroup(deviceGroup, TestDataHolder.SUPER_TENANT_ID);
|
||||
GroupManagementDAOFactory.commitTransaction();
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
log.debug("Group added to database. ID: " + groupId);
|
||||
} catch (GroupManagementDAOException e) {
|
||||
GroupManagementDAOFactory.rollbackTransaction();
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while adding device type '" + deviceGroup.getName() + "'.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} catch (TransactionManagementException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while initiating transaction.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} finally {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
}
|
||||
|
||||
DeviceGroup group = getGroupById(groupId);
|
||||
Assert.assertNotNull(group, "Group is null");
|
||||
log.debug("Group name: " + group.getName());
|
||||
@ -81,19 +82,20 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
|
||||
request.setGroupName(null);
|
||||
request.setOwner(null);
|
||||
List<DeviceGroup> groups = groupDAO.getGroups(request, TestDataHolder.SUPER_TENANT_ID);
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
Assert.assertNotEquals(groups.size(), 0, "No groups found");
|
||||
Assert.assertNotNull(groups.get(0), "Group is null");
|
||||
log.debug("No of Groups found: " + groups.size());
|
||||
} catch (GroupManagementDAOException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while find group by name.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} catch (SQLException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while opening a connection to the data source.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} finally {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
}
|
||||
}
|
||||
|
||||
@ -109,18 +111,19 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
|
||||
}
|
||||
GroupManagementDAOFactory.commitTransaction();
|
||||
List<String> roles = groupDAO.getRoles(groupId, TestDataHolder.SUPER_TENANT_ID);
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
Assert.assertEquals(roles, addedRoles, "Added roles are not equal to returned roles.");
|
||||
log.debug("Group shared with roles.");
|
||||
} catch (GroupManagementDAOException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while find group by name.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} catch (TransactionManagementException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while opening a connection to the data source.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} finally {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
}
|
||||
}
|
||||
|
||||
@ -131,19 +134,20 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
|
||||
List<String> roles = groupDAO.getRoles(groupId, TestDataHolder.SUPER_TENANT_ID);
|
||||
roles.remove(0);
|
||||
List<DeviceGroup> deviceGroups = groupDAO.getGroups(roles.toArray(new String[roles.size()]), TestDataHolder.SUPER_TENANT_ID);
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
Assert.assertEquals(deviceGroups.size(), 1, "Unexpected number of device groups found with role.");
|
||||
Assert.assertEquals(deviceGroups.get(0).getGroupId(), groupId, "Unexpected groupId found with role.");
|
||||
log.debug("Group found for given roles.");
|
||||
} catch (GroupManagementDAOException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while getting groups shared with roles.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} catch (SQLException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while opening a connection to the data source.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} finally {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
}
|
||||
}
|
||||
|
||||
@ -157,18 +161,19 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
|
||||
}
|
||||
GroupManagementDAOFactory.commitTransaction();
|
||||
List<String> roles = groupDAO.getRoles(groupId, TestDataHolder.SUPER_TENANT_ID);
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
Assert.assertNotEquals(roles, rolesToRemove, "Roles not removed.");
|
||||
log.debug("Group unshared with given roles.");
|
||||
} catch (GroupManagementDAOException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while find group by name.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} catch (TransactionManagementException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while opening a connection to the data source.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} finally {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
}
|
||||
}
|
||||
|
||||
@ -181,36 +186,38 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
|
||||
GroupManagementDAOFactory.beginTransaction();
|
||||
groupDAO.addDevice(deviceGroup.getGroupId(), initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID);
|
||||
GroupManagementDAOFactory.commitTransaction();
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
log.debug("Device added to group.");
|
||||
} catch (GroupManagementDAOException e) {
|
||||
GroupManagementDAOFactory.rollbackTransaction();
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while adding device '" + initialTestDevice.getName() + "'.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} catch (TransactionManagementException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while initiating transaction.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} finally {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
}
|
||||
|
||||
try {
|
||||
GroupManagementDAOFactory.openConnection();
|
||||
List<Device> groupedDevices = groupDAO.getDevices(deviceGroup.getGroupId(), 0, 10, TestDataHolder.SUPER_TENANT_ID);
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
Assert.assertNotEquals(groupedDevices.size(), 0, "No device found");
|
||||
Assert.assertNotNull(groupedDevices.get(0), "Device is null");
|
||||
Assert.assertEquals(groupedDevices.get(0).getId(), initialTestDevice.getId(), "Device ids not matched");
|
||||
} catch (GroupManagementDAOException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while retrieving group details.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} catch (SQLException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while opening a connection to the data source.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} finally {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
}
|
||||
}
|
||||
|
||||
@ -223,18 +230,19 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
|
||||
GroupManagementDAOFactory.beginTransaction();
|
||||
groupDAO.removeDevice(deviceGroup.getGroupId(), initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID);
|
||||
GroupManagementDAOFactory.commitTransaction();
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
log.debug("Device added to group.");
|
||||
} catch (GroupManagementDAOException e) {
|
||||
GroupManagementDAOFactory.rollbackTransaction();
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while adding device '" + initialTestDevice.getDeviceIdentifier() + "'.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} catch (TransactionManagementException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while initiating transaction.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} finally {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
}
|
||||
}
|
||||
|
||||
@ -250,18 +258,19 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
|
||||
GroupManagementDAOFactory.beginTransaction();
|
||||
groupDAO.updateGroup(group, groupId, TestDataHolder.SUPER_TENANT_ID);
|
||||
GroupManagementDAOFactory.commitTransaction();
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
log.debug("Group updated");
|
||||
} catch (GroupManagementDAOException e) {
|
||||
GroupManagementDAOFactory.rollbackTransaction();
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while updating group details.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} catch (TransactionManagementException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while initiating transaction.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} finally {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
}
|
||||
|
||||
group = getGroupById(groupId);
|
||||
@ -278,18 +287,19 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
|
||||
GroupManagementDAOFactory.beginTransaction();
|
||||
groupDAO.deleteGroup(group.getGroupId(), TestDataHolder.SUPER_TENANT_ID);
|
||||
GroupManagementDAOFactory.commitTransaction();
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
log.debug("Group deleted");
|
||||
} catch (GroupManagementDAOException e) {
|
||||
GroupManagementDAOFactory.rollbackTransaction();
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while updating group details.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} catch (TransactionManagementException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while initiating transaction.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} finally {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
}
|
||||
group = getGroupById(groupId);
|
||||
Assert.assertNull(group, "Group is not deleted");
|
||||
@ -298,17 +308,19 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
|
||||
private DeviceGroup getGroupById(int groupId) {
|
||||
try {
|
||||
GroupManagementDAOFactory.openConnection();
|
||||
return groupDAO.getGroup(groupId, TestDataHolder.SUPER_TENANT_ID);
|
||||
DeviceGroup deviceGroup = groupDAO.getGroup(groupId, TestDataHolder.SUPER_TENANT_ID);
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
return deviceGroup;
|
||||
} catch (GroupManagementDAOException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while retrieving group details.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} catch (SQLException e) {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
String msg = "Error occurred while opening a connection to the data source.";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} finally {
|
||||
GroupManagementDAOFactory.closeConnection();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -0,0 +1,220 @@
|
||||
/*
|
||||
* 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.notification.mgt;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.EntityDoesNotExistException;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||
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.core.TestDeviceManagementService;
|
||||
import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
|
||||
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.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
|
||||
import org.wso2.carbon.registry.core.config.RegistryContext;
|
||||
import org.wso2.carbon.registry.core.exceptions.RegistryException;
|
||||
import org.wso2.carbon.registry.core.internal.RegistryDataHolder;
|
||||
import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService;
|
||||
import org.wso2.carbon.registry.core.service.RegistryService;
|
||||
import org.wso2.carbon.user.core.service.RealmService;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This is the test class for {@link NotificationManagementServiceImpl}
|
||||
*/
|
||||
public class NotificationManagementServiceImplTests {
|
||||
|
||||
private static final Log log = LogFactory.getLog(NotificationManagementServiceImplTests.class);
|
||||
private static final String DEVICE_TYPE = "NOTIFICATION_TEST_DEVICE";
|
||||
private static final String DEVICE_ID_PREFIX = "NOTIFICATION-TEST-DEVICE-ID-";
|
||||
private static final int NO_OF_DEVICES = 10;
|
||||
private static final int NO_OF_NOTIFICATIONS = 10;
|
||||
private List<DeviceIdentifier> deviceIds = new ArrayList<>();
|
||||
private NotificationManagementServiceImpl notificationManagementService;
|
||||
private static final String TEST_NOTIFICATION_DESCRIPTION = "test notification";
|
||||
private static final int NOTIFICATION_OPERATION_ID = 1;
|
||||
|
||||
@BeforeClass
|
||||
public void init() throws Exception {
|
||||
DeviceConfigurationManager.getInstance().initConfig();
|
||||
log.info("Initializing");
|
||||
for (int i = 1; i <= NO_OF_DEVICES; i++) {
|
||||
deviceIds.add(new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE));
|
||||
}
|
||||
List<Device> devices = TestDataHolder.generateDummyDeviceData(this.deviceIds);
|
||||
DeviceManagementProviderService deviceMgtService = new DeviceManagementProviderServiceImpl();
|
||||
DeviceManagementServiceComponent.notifyStartupListeners();
|
||||
DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceMgtService);
|
||||
DeviceManagementDataHolder.getInstance().setRegistryService(getRegistryService());
|
||||
DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(new DeviceAccessAuthorizationServiceImpl());
|
||||
DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(new GroupManagementProviderServiceImpl());
|
||||
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null);
|
||||
deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE,
|
||||
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME));
|
||||
for (Device device : devices) {
|
||||
Assert.assertTrue(deviceMgtService.enrollDevice(device), "Device with Identifier - " +
|
||||
device.getDeviceIdentifier() + " is not enrolled.");
|
||||
}
|
||||
List<Device> returnedDevices = deviceMgtService.getAllDevices(DEVICE_TYPE);
|
||||
|
||||
for (Device device : returnedDevices) {
|
||||
if (!device.getDeviceIdentifier().startsWith(DEVICE_ID_PREFIX)) {
|
||||
throw new Exception("Incorrect device with ID - " + device.getDeviceIdentifier() + " returned!");
|
||||
}
|
||||
}
|
||||
notificationManagementService = new NotificationManagementServiceImpl();
|
||||
}
|
||||
|
||||
private RegistryService getRegistryService() throws RegistryException {
|
||||
RealmService realmService = new InMemoryRealmService();
|
||||
RegistryDataHolder.getInstance().setRealmService(realmService);
|
||||
DeviceManagementDataHolder.getInstance().setRealmService(realmService);
|
||||
InputStream is = this.getClass().getClassLoader().getResourceAsStream("carbon-home/repository/conf/registry.xml");
|
||||
RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
|
||||
context.setSetup(true);
|
||||
return context.getEmbeddedRegistryService();
|
||||
}
|
||||
|
||||
@Test(description = "Add notifications using addNotification method and check whether it returns true.")
|
||||
public void addNotification() throws NotificationManagementException {
|
||||
for (int i = 1; i <= NO_OF_DEVICES; i++) {
|
||||
DeviceIdentifier testDeviceIdentifier = new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE);
|
||||
Notification notification = TestDataHolder.getNotification(i, Notification.Status.NEW.toString(),
|
||||
testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + i,
|
||||
NOTIFICATION_OPERATION_ID, DEVICE_TYPE);
|
||||
Assert.assertTrue(notificationManagementService.addNotification(testDeviceIdentifier, notification),
|
||||
"Adding notification failed for [" + notification.toString() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = EntityDoesNotExistException.class, description = "AddNotification method is checked" +
|
||||
" whether it returns EntityDoesNotExistException when the device not registered is added notification")
|
||||
public void addNotificationExceptions() throws NotificationManagementException {
|
||||
DeviceIdentifier testDeviceIdentifier = new DeviceIdentifier(DEVICE_ID_PREFIX + 123, DEVICE_TYPE);
|
||||
Notification notification = TestDataHolder.getNotification(1, Notification.Status.NEW.toString(),
|
||||
testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + 123,
|
||||
NOTIFICATION_OPERATION_ID, DEVICE_TYPE);
|
||||
notificationManagementService.addNotification(new DeviceIdentifier(DEVICE_ID_PREFIX + 123,
|
||||
DEVICE_TYPE), notification);
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = NotificationManagementException.class, description = "This tests the method getDevice which" +
|
||||
" is called internally in addNotification for DeviceManagementException exception passing null device Id.")
|
||||
public void getDevice() throws NotificationManagementException {
|
||||
DeviceIdentifier testDeviceIdentifier = new DeviceIdentifier(DEVICE_ID_PREFIX + 123, DEVICE_TYPE);
|
||||
Notification notification = TestDataHolder.getNotification(1, Notification.Status.NEW.toString(),
|
||||
testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + 123,
|
||||
NOTIFICATION_OPERATION_ID, DEVICE_TYPE);
|
||||
notificationManagementService.addNotification(null, notification);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "addNotification", description = "This tests the updateNotification Method" +
|
||||
" and check whether it returns true ( got updated )")
|
||||
public void updateNotification() throws NotificationManagementException {
|
||||
for (int i = 1; i <= NO_OF_DEVICES; i++) {
|
||||
DeviceIdentifier testDeviceIdentifier = new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE);
|
||||
Notification notification = TestDataHolder.getNotification(i, Notification.Status.CHECKED.toString(),
|
||||
testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + i,
|
||||
NOTIFICATION_OPERATION_ID, DEVICE_TYPE);
|
||||
Assert.assertTrue(notificationManagementService.updateNotification(notification), "Notification " +
|
||||
"update failed for [" + notification.toString() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "updateNotification", description = "This method update notification status " +
|
||||
"and check whether it got updated")
|
||||
public void updateNotificationStatus() throws NotificationManagementException {
|
||||
for (int i = 1; i <= NO_OF_DEVICES; i++) {
|
||||
Assert.assertTrue(notificationManagementService.updateNotificationStatus(i, Notification.Status.CHECKED),
|
||||
"Notification update status failed for notification id:- " + i);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "addNotification", description = "this tests getAllNotifications" +
|
||||
" method by listing down all the notifications.")
|
||||
public void getAllNotifications() throws NotificationManagementException {
|
||||
List<Notification> returnedNotifications = notificationManagementService.getAllNotifications();
|
||||
Assert.assertEquals(returnedNotifications.size(), NO_OF_DEVICES, "No. of notifications added is not " +
|
||||
"equal to no. of notifications retrieved.");
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "updateNotificationStatus", description = "this method retries notification by id" +
|
||||
" and checks it")
|
||||
public void getNotification() throws NotificationManagementException {
|
||||
for (int i = 1; i <= NO_OF_DEVICES; i++) {
|
||||
Notification returnedNotification = notificationManagementService.getNotification(i);
|
||||
Assert.assertEquals(returnedNotification.getNotificationId(), i, "Returned notification ID is not " +
|
||||
"same as added notification Id.");
|
||||
Assert.assertEquals(returnedNotification.getStatus(), Notification.Status.CHECKED, "Returned " +
|
||||
"notification status is not same as added notification status.");
|
||||
Assert.assertEquals(returnedNotification.getDescription(), TEST_NOTIFICATION_DESCRIPTION, "Returned" +
|
||||
" notification description is not same as added notification description.");
|
||||
Assert.assertEquals(returnedNotification.getOperationId(), NOTIFICATION_OPERATION_ID, "Returned " +
|
||||
"notification operation ID is not same as added notification operation Id.");
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "updateNotificationStatus", description = "this method gets all notification by status checked")
|
||||
public void getNotificationsByStatus() throws NotificationManagementException {
|
||||
List<Notification> returnedNotifications = notificationManagementService.getNotificationsByStatus(Notification.
|
||||
Status.CHECKED);
|
||||
Assert.assertEquals(returnedNotifications.size(), NO_OF_NOTIFICATIONS, "Returned no. of notification is " +
|
||||
"not same as added no. of notifications.");
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "addNotification", description = "this tests for getAllNotification method by passing " +
|
||||
"pagination request and validates the no. of total records and filtered records. ")
|
||||
public void getAllNotificationsWithPaginationRequest() throws NotificationManagementException {
|
||||
PaginationRequest request = new PaginationRequest(1, 2);
|
||||
PaginationResult result = notificationManagementService.getAllNotifications(request);
|
||||
Assert.assertEquals(result.getRecordsFiltered(), NO_OF_NOTIFICATIONS, "Returned filtered records is " +
|
||||
"not same as added filtered records.");
|
||||
Assert.assertEquals(result.getRecordsTotal(), NO_OF_NOTIFICATIONS, "Returned no. of records is not " +
|
||||
"same as added no. of records.");
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "updateNotificationStatus", description = "this tests for getAllNotification method by" +
|
||||
" passing pagination request & status and validates the no. of total records and filtered records. ")
|
||||
public void getAllNotificationsWithPaginationRequestAndStatus() throws NotificationManagementException {
|
||||
PaginationRequest request = new PaginationRequest(1, 2);
|
||||
PaginationResult result = notificationManagementService.getNotificationsByStatus(Notification.Status.CHECKED,
|
||||
request);
|
||||
Assert.assertEquals(result.getRecordsFiltered(), NO_OF_NOTIFICATIONS, "Returned filtered records is not " +
|
||||
"same as added filtered records.");
|
||||
Assert.assertEquals(result.getRecordsTotal(), NO_OF_NOTIFICATIONS, "Returned no. of records is not same" +
|
||||
" as added no. of records.");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,656 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
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.operation.mgt.Activity;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.ActivityStatus;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy;
|
||||
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
|
||||
import org.wso2.carbon.device.mgt.core.TestDeviceManagementService;
|
||||
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
|
||||
import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
|
||||
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.operation.mgt.OperationManagerImpl;
|
||||
import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation;
|
||||
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This is the testcase which covers the methods from {@link OperationManager}
|
||||
*/
|
||||
public class OperationManagementTests extends BaseDeviceManagementTest {
|
||||
|
||||
private static final String DEVICE_TYPE = "OP_TEST_TYPE";
|
||||
private static final String DEVICE_ID_PREFIX = "OP-TEST-DEVICE-ID-";
|
||||
private static final String COMMAND_OPERATON_CODE = "COMMAND-TEST";
|
||||
private static final String POLICY_OPERATION_CODE = "POLICY-TEST";
|
||||
private static final String CONFIG_OPERATION_CODE = "CONFIG-TEST";
|
||||
private static final String PROFILE_OPERATION_CODE = "PROFILE-TEST";
|
||||
private static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
|
||||
private static final int NO_OF_DEVICES = 5;
|
||||
private static final String ADMIN_USER = "admin";
|
||||
private static final String NON_ADMIN_USER = "test";
|
||||
private static final String INVALID_DEVICE = "ThisIsInvalid";
|
||||
|
||||
private List<DeviceIdentifier> deviceIds = new ArrayList<>();
|
||||
private OperationManager operationMgtService;
|
||||
private DeviceManagementProviderService deviceMgmtProvider;
|
||||
private Activity commandActivity;
|
||||
private long commandActivityBeforeUpdatedTimestamp;
|
||||
|
||||
@BeforeClass
|
||||
public void init() throws Exception {
|
||||
for (int i = 0; i < NO_OF_DEVICES; i++) {
|
||||
deviceIds.add(new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE));
|
||||
}
|
||||
List<Device> devices = TestDataHolder.generateDummyDeviceData(this.deviceIds);
|
||||
DeviceManagementProviderService deviceMgtService = DeviceManagementDataHolder.getInstance().
|
||||
getDeviceManagementProvider();
|
||||
deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE,
|
||||
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME));
|
||||
for (Device device : devices) {
|
||||
deviceMgtService.enrollDevice(device);
|
||||
}
|
||||
List<Device> returnedDevices = deviceMgtService.getAllDevices(DEVICE_TYPE);
|
||||
for (Device device : returnedDevices) {
|
||||
if (!device.getDeviceIdentifier().startsWith(DEVICE_ID_PREFIX)) {
|
||||
throw new Exception("Incorrect device with ID - " + device.getDeviceIdentifier() + " returned!");
|
||||
}
|
||||
}
|
||||
this.deviceMgmtProvider = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider();
|
||||
NotificationStrategy notificationStrategy = new TestNotificationStrategy();
|
||||
this.operationMgtService = new OperationManagerImpl(DEVICE_TYPE, notificationStrategy);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addCommandOperation() throws DeviceManagementException, OperationManagementException,
|
||||
InvalidDeviceException {
|
||||
this.commandActivity = this.operationMgtService.addOperation(
|
||||
getOperation(new CommandOperation(), Operation.Type.COMMAND, COMMAND_OPERATON_CODE),
|
||||
this.deviceIds);
|
||||
validateOperationResponse(this.commandActivity, ActivityStatus.Status.PENDING);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addCommandOperationInvalidDeviceIds() throws DeviceManagementException, OperationManagementException,
|
||||
InvalidDeviceException {
|
||||
startTenantFlowAsNonAdmin();
|
||||
try {
|
||||
ArrayList<DeviceIdentifier> invalidDevices = new ArrayList<>();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
invalidDevices.add(new DeviceIdentifier(INVALID_DEVICE + i, DEVICE_TYPE));
|
||||
}
|
||||
invalidDevices.addAll(this.deviceIds);
|
||||
Activity activity = this.operationMgtService.addOperation(getOperation(new CommandOperation(),
|
||||
Operation.Type.COMMAND, COMMAND_OPERATON_CODE), invalidDevices);
|
||||
Assert.assertEquals(activity.getActivityStatus().size(), invalidDevices.size(),
|
||||
"The operation response for add operation only have - " + activity.getActivityStatus().size());
|
||||
for (int i = 0; i < activity.getActivityStatus().size(); i++) {
|
||||
ActivityStatus status = activity.getActivityStatus().get(i);
|
||||
if (i < 3) {
|
||||
Assert.assertEquals(status.getStatus(), ActivityStatus.Status.INVALID);
|
||||
} else {
|
||||
Assert.assertEquals(status.getStatus(), ActivityStatus.Status.UNAUTHORIZED);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test(expectedExceptions = InvalidDeviceException.class)
|
||||
public void addEmptyDevicesCommandOperation() throws DeviceManagementException, OperationManagementException,
|
||||
InvalidDeviceException {
|
||||
this.operationMgtService.addOperation(getOperation(new CommandOperation(), Operation.Type.COMMAND,
|
||||
COMMAND_OPERATON_CODE),
|
||||
new ArrayList<>());
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = InvalidDeviceException.class)
|
||||
public void addNonInitializedDevicesCommandOperation() throws DeviceManagementException,
|
||||
OperationManagementException,
|
||||
InvalidDeviceException {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
|
||||
deviceIdentifiers.add(deviceIdentifier);
|
||||
this.operationMgtService.addOperation(getOperation(new CommandOperation(), Operation.Type.COMMAND,
|
||||
COMMAND_OPERATON_CODE),
|
||||
deviceIdentifiers);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addNonAdminUserDevicesCommandOperation() throws DeviceManagementException, OperationManagementException,
|
||||
InvalidDeviceException {
|
||||
startTenantFlowAsNonAdmin();
|
||||
Activity activity = this.operationMgtService.addOperation(getOperation(new CommandOperation(),
|
||||
Operation.Type.COMMAND, COMMAND_OPERATON_CODE),
|
||||
deviceIds);
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
validateOperationResponse(activity, ActivityStatus.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
private void startTenantFlowAsNonAdmin() {
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID, true);
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_USER);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "addCommandOperation")
|
||||
public void addPolicyOperation() throws DeviceManagementException, OperationManagementException,
|
||||
InvalidDeviceException {
|
||||
Activity activity = this.operationMgtService.addOperation(getOperation(new PolicyOperation(),
|
||||
Operation.Type.POLICY, POLICY_OPERATION_CODE),
|
||||
this.deviceIds);
|
||||
validateOperationResponse(activity, ActivityStatus.Status.PENDING);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "addPolicyOperation")
|
||||
public void addConfigOperation() throws DeviceManagementException, OperationManagementException,
|
||||
InvalidDeviceException {
|
||||
Activity activity = this.operationMgtService.addOperation(getOperation(new ConfigOperation(),
|
||||
Operation.Type.CONFIG, CONFIG_OPERATION_CODE),
|
||||
this.deviceIds);
|
||||
validateOperationResponse(activity, ActivityStatus.Status.PENDING);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "addConfigOperation")
|
||||
public void addProfileOperation() throws DeviceManagementException, OperationManagementException,
|
||||
InvalidDeviceException {
|
||||
Activity activity = this.operationMgtService.addOperation(getOperation(new ProfileOperation(),
|
||||
Operation.Type.PROFILE, PROFILE_OPERATION_CODE),
|
||||
this.deviceIds);
|
||||
validateOperationResponse(activity, ActivityStatus.Status.PENDING);
|
||||
}
|
||||
|
||||
static Operation getOperation(Operation operation, Operation.Type type, String code) {
|
||||
String date = new SimpleDateFormat(DATE_FORMAT_NOW).format(new Date());
|
||||
operation.setCreatedTimeStamp(date);
|
||||
operation.setType(type);
|
||||
operation.setCode(code);
|
||||
return operation;
|
||||
}
|
||||
|
||||
private void validateOperationResponse(Activity activity, ActivityStatus.Status expectedStatus) {
|
||||
Assert.assertEquals(activity.getActivityStatus().size(), NO_OF_DEVICES, "The operation response for add " +
|
||||
"operation only have - " + activity.getActivityStatus().size());
|
||||
for (ActivityStatus status : activity.getActivityStatus()) {
|
||||
Assert.assertEquals(status.getStatus(), expectedStatus);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "addProfileOperation")
|
||||
public void getOperations() throws DeviceManagementException, OperationManagementException, InvalidDeviceException {
|
||||
for (DeviceIdentifier deviceIdentifier : deviceIds) {
|
||||
List operations = this.operationMgtService.getOperations(deviceIdentifier);
|
||||
Assert.assertEquals(operations.size(), 4, "The operations should be 4, but found only " + operations.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "addProfileOperation", expectedExceptions = OperationManagementException.class)
|
||||
public void getOperationsAsNonAdmin() throws DeviceManagementException, OperationManagementException,
|
||||
InvalidDeviceException {
|
||||
try {
|
||||
startTenantFlowAsNonAdmin();
|
||||
for (DeviceIdentifier deviceIdentifier : deviceIds) {
|
||||
this.operationMgtService.getOperations(deviceIdentifier);
|
||||
}
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperations")
|
||||
public void getPendingOperations() throws DeviceManagementException, OperationManagementException,
|
||||
InvalidDeviceException {
|
||||
for (DeviceIdentifier deviceIdentifier : deviceIds) {
|
||||
List operations = this.operationMgtService.getPendingOperations(deviceIdentifier);
|
||||
Assert.assertEquals(operations.size(), 4, "The pending operations should be 4, but found only "
|
||||
+ operations.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperations", expectedExceptions = OperationManagementException.class)
|
||||
public void getPendingOperationsAsNonAdmin() throws DeviceManagementException, OperationManagementException,
|
||||
InvalidDeviceException {
|
||||
try {
|
||||
startTenantFlowAsNonAdmin();
|
||||
for (DeviceIdentifier deviceIdentifier : deviceIds) {
|
||||
this.operationMgtService.getPendingOperations(deviceIdentifier);
|
||||
}
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getPendingOperations")
|
||||
public void getPaginatedRequestAsAdmin() throws OperationManagementException {
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID, true);
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
|
||||
PaginationRequest request = new PaginationRequest(1, 2);
|
||||
request.setDeviceType(DEVICE_TYPE);
|
||||
request.setOwner(ADMIN_USER);
|
||||
for (DeviceIdentifier deviceIdentifier : deviceIds) {
|
||||
PaginationResult result = this.operationMgtService.getOperations(deviceIdentifier, request);
|
||||
Assert.assertEquals(result.getRecordsFiltered(), 4);
|
||||
Assert.assertEquals(result.getData().size(), 2);
|
||||
Assert.assertEquals(result.getRecordsTotal(), 4);
|
||||
}
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getPendingOperations", expectedExceptions = OperationManagementException.class)
|
||||
public void getPaginatedRequestAsNonAdmin() throws OperationManagementException {
|
||||
try {
|
||||
startTenantFlowAsNonAdmin();
|
||||
PaginationRequest request = new PaginationRequest(1, 2);
|
||||
request.setDeviceType(DEVICE_TYPE);
|
||||
request.setOwner(ADMIN_USER);
|
||||
for (DeviceIdentifier deviceIdentifier : deviceIds) {
|
||||
try {
|
||||
this.operationMgtService.getOperations(deviceIdentifier, request);
|
||||
} catch (OperationManagementException ex) {
|
||||
if (ex.getMessage() == null) {
|
||||
Assert.assertTrue(ex.getMessage().contains("User '" + NON_ADMIN_USER + "' is not authorized"));
|
||||
}
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getPaginatedRequestAsAdmin")
|
||||
public void updateOperation() throws OperationManagementException {
|
||||
//This is required to introduce a delay for the update operation of the device.
|
||||
this.commandActivityBeforeUpdatedTimestamp = System.currentTimeMillis();
|
||||
try {
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
DeviceIdentifier deviceIdentifier = this.deviceIds.get(0);
|
||||
List operations = this.operationMgtService.getPendingOperations(deviceIdentifier);
|
||||
Assert.assertTrue(operations != null && operations.size() == 4);
|
||||
Operation operation = (Operation) operations.get(0);
|
||||
operation.setStatus(Operation.Status.COMPLETED);
|
||||
operation.setOperationResponse("The operation is successfully completed");
|
||||
this.operationMgtService.updateOperation(deviceIdentifier, operation);
|
||||
List pendingOperations = this.operationMgtService.getPendingOperations(deviceIdentifier);
|
||||
Assert.assertEquals(pendingOperations.size(), 3);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "updateOperation", expectedExceptions = OperationManagementException.class)
|
||||
public void updateOperationAsNonAdmin() throws OperationManagementException {
|
||||
//This is required to introduce a delay for the update operation of the device.
|
||||
try {
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = this.deviceIds.get(0);
|
||||
List operations = this.operationMgtService.getPendingOperations(deviceIdentifier);
|
||||
Assert.assertTrue(operations != null && operations.size() == 3);
|
||||
startTenantFlowAsNonAdmin();
|
||||
Operation operation = (Operation) operations.get(0);
|
||||
operation.setStatus(Operation.Status.COMPLETED);
|
||||
operation.setOperationResponse("The operation is successfully completed, and updated by non admin!");
|
||||
this.operationMgtService.updateOperation(deviceIdentifier, operation);
|
||||
List pendingOperations = this.operationMgtService.getPendingOperations(deviceIdentifier);
|
||||
Assert.assertEquals(pendingOperations.size(), 3);
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "updateOperation")
|
||||
public void getNextPendingOperation() throws OperationManagementException {
|
||||
DeviceIdentifier deviceIdentifier = this.deviceIds.get(0);
|
||||
Operation operation = this.operationMgtService.getNextPendingOperation(deviceIdentifier);
|
||||
Assert.assertTrue(operation.getType().equals(Operation.Type.POLICY));
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "updateOperation", expectedExceptions = OperationManagementException.class)
|
||||
public void getNextPendingOperationAsNonAdmin() throws OperationManagementException {
|
||||
startTenantFlowAsNonAdmin();
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = this.deviceIds.get(0);
|
||||
this.operationMgtService.getNextPendingOperation(deviceIdentifier);
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getNextPendingOperation")
|
||||
public void getOperationByDeviceAndOperationId() throws OperationManagementException {
|
||||
DeviceIdentifier deviceIdentifier = this.deviceIds.get(0);
|
||||
Operation operation = this.operationMgtService.getOperationByDeviceAndOperationId(deviceIdentifier,
|
||||
getOperationId(this.commandActivity.getActivityId()));
|
||||
Assert.assertTrue(operation.getStatus().equals(Operation.Status.COMPLETED));
|
||||
Assert.assertTrue(operation.getType().equals(Operation.Type.COMMAND));
|
||||
}
|
||||
|
||||
private int getOperationId(String activityId) {
|
||||
return Integer.parseInt(activityId.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, ""));
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getNextPendingOperation", expectedExceptions = OperationManagementException.class)
|
||||
public void getOperationByDeviceAndOperationIdNonAdmin() throws OperationManagementException {
|
||||
startTenantFlowAsNonAdmin();
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = this.deviceIds.get(0);
|
||||
String operationId = this.commandActivity.getActivityId().
|
||||
replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, "");
|
||||
this.operationMgtService.getOperationByDeviceAndOperationId(deviceIdentifier,
|
||||
Integer.parseInt(operationId));
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationByDeviceAndOperationId")
|
||||
public void getOperationsByDeviceAndStatus() throws OperationManagementException, DeviceManagementException {
|
||||
DeviceIdentifier deviceIdentifier = this.deviceIds.get(0);
|
||||
List operation = this.operationMgtService.getOperationsByDeviceAndStatus(deviceIdentifier,
|
||||
Operation.Status.PENDING);
|
||||
Assert.assertEquals(operation.size(), 3);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationByDeviceAndOperationId", expectedExceptions = OperationManagementException.class)
|
||||
public void getOperationsByDeviceAndStatusByNonAdmin() throws OperationManagementException,
|
||||
DeviceManagementException {
|
||||
startTenantFlowAsNonAdmin();
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = this.deviceIds.get(0);
|
||||
this.operationMgtService.getOperationsByDeviceAndStatus(deviceIdentifier, Operation.Status.PENDING);
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationsByDeviceAndStatus")
|
||||
public void getOperation() throws OperationManagementException, DeviceManagementException {
|
||||
String operationId = this.commandActivity.getActivityId().
|
||||
replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, "");
|
||||
Operation operation = this.operationMgtService.getOperation(Integer.parseInt(operationId));
|
||||
Assert.assertEquals(operation.getType(), Operation.Type.COMMAND);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperation")
|
||||
public void getOperationActivity() throws OperationManagementException {
|
||||
Activity activity = this.operationMgtService.getOperationByActivityId(commandActivity.getActivityId());
|
||||
Assert.assertEquals(activity.getType(), Activity.Type.COMMAND);
|
||||
Assert.assertEquals(activity.getActivityStatus().size(), this.deviceIds.size());
|
||||
Assert.assertEquals(activity.getActivityStatus().get(0).getStatus(), ActivityStatus.Status.COMPLETED);
|
||||
for (int i = 1; i < this.deviceIds.size(); i++) {
|
||||
Assert.assertEquals(activity.getActivityStatus().get(i).getStatus(), ActivityStatus.Status.PENDING);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationActivity")
|
||||
public void getOperationByActivityIdAndDevice() throws OperationManagementException {
|
||||
Activity activity = this.operationMgtService.
|
||||
getOperationByActivityIdAndDevice(this.commandActivity.getActivityId(), this.deviceIds.get(0));
|
||||
Assert.assertEquals(activity.getType(), Activity.Type.COMMAND);
|
||||
Assert.assertEquals(activity.getActivityStatus().size(), 1);
|
||||
Assert.assertEquals(activity.getActivityStatus().get(0).getStatus(), ActivityStatus.Status.COMPLETED);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationActivity", expectedExceptions = OperationManagementException.class)
|
||||
public void getOperationByActivityIdAndDeviceAsNonAdmin() throws OperationManagementException {
|
||||
startTenantFlowAsNonAdmin();
|
||||
try {
|
||||
this.operationMgtService.
|
||||
getOperationByActivityIdAndDevice(this.commandActivity.getActivityId(), this.deviceIds.get(0));
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "updateOperation")
|
||||
public void getOperationUpdatedAfterWithLimitAndOffset() throws OperationManagementException, ParseException {
|
||||
List<Activity> operations = this.operationMgtService.getActivitiesUpdatedAfter
|
||||
(this.commandActivityBeforeUpdatedTimestamp / 1000, 10, 0);
|
||||
Assert.assertTrue(operations != null && operations.size() == 1,
|
||||
"The operations updated after the created should be 1");
|
||||
Activity operation = operations.get(0);
|
||||
Assert.assertTrue(operation.getActivityStatus() != null && operation.getActivityStatus().size() == 1,
|
||||
"The operation should be having the activity status of atleast one device");
|
||||
Assert.assertEquals(operation.getActivityStatus().get(0).getDeviceIdentifier().getId(),
|
||||
deviceIds.get(0).getId());
|
||||
Assert.assertEquals(operation.getActivityStatus().get(0).getDeviceIdentifier().getType(),
|
||||
deviceIds.get(0).getType());
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationUpdatedAfterWithLimitAndOffset")
|
||||
public void getActivityCountUpdatedAfter() throws OperationManagementException, ParseException {
|
||||
int activityCount = this.operationMgtService.getActivityCountUpdatedAfter
|
||||
(this.commandActivityBeforeUpdatedTimestamp / 1000);
|
||||
Assert.assertTrue(activityCount == 1,
|
||||
"The activities updated after the created should be 1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getNotificationStrategy() {
|
||||
Assert.assertTrue(this.operationMgtService.getNotificationStrategy() != null);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = {"getOperationByActivityIdAndDevice", "getOperationByActivityIdAndDeviceAsNonAdmin"})
|
||||
public void getOperationForInactiveDevice() throws DeviceManagementException, OperationManagementException {
|
||||
boolean disEnrolled = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
|
||||
disenrollDevice(deviceIds.get(0));
|
||||
Assert.assertTrue(disEnrolled);
|
||||
List operations = this.operationMgtService.getOperations(deviceIds.get(0));
|
||||
Assert.assertTrue(operations == null);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationForInactiveDevice", expectedExceptions = OperationManagementException.class)
|
||||
public void getPaginatedOperationDeviceForInvalidDevice() throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID, true);
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
|
||||
try {
|
||||
PaginationRequest request = new PaginationRequest(1, 2);
|
||||
request.setDeviceType(DEVICE_TYPE);
|
||||
request.setOwner(ADMIN_USER);
|
||||
PaginationResult result = this.operationMgtService.getOperations
|
||||
(new DeviceIdentifier(INVALID_DEVICE, DEVICE_TYPE), request);
|
||||
Assert.assertEquals(result.getRecordsFiltered(), 4);
|
||||
Assert.assertEquals(result.getData().size(), 2);
|
||||
Assert.assertEquals(result.getRecordsTotal(), 4);
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationForInactiveDevice", expectedExceptions = OperationManagementException.class)
|
||||
public void getPendingOperationDeviceForInvalidDevice() throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
this.operationMgtService.getPendingOperations(new DeviceIdentifier(INVALID_DEVICE, DEVICE_TYPE));
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getPendingOperationDeviceForInvalidDevice",
|
||||
expectedExceptions = OperationManagementException.class)
|
||||
public void getNextPendingOperationDeviceForInvalidDevice() throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
this.operationMgtService.getNextPendingOperation(new DeviceIdentifier(INVALID_DEVICE, DEVICE_TYPE));
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getNextPendingOperationDeviceForInvalidDevice",
|
||||
expectedExceptions = OperationManagementException.class)
|
||||
public void getUpdateOperationForInvalidDevice() throws DeviceManagementException, OperationManagementException {
|
||||
this.operationMgtService.updateOperation(new DeviceIdentifier(INVALID_DEVICE, DEVICE_TYPE),
|
||||
getOperation(new CommandOperation(), Operation.Type.COMMAND, COMMAND_OPERATON_CODE));
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getUpdateOperationForInvalidDevice",
|
||||
expectedExceptions = OperationManagementException.class)
|
||||
public void getOperationByDeviceAndOperationIdInvalidDevice() throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
this.operationMgtService.getOperationByDeviceAndOperationId(new DeviceIdentifier(INVALID_DEVICE, DEVICE_TYPE),
|
||||
getOperationId(this.commandActivity.getActivityId()));
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationByDeviceAndOperationIdInvalidDevice",
|
||||
expectedExceptions = OperationManagementException.class)
|
||||
public void getOperationsByDeviceAndStatusInvalidDevice() throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
this.operationMgtService.getOperationsByDeviceAndStatus(new DeviceIdentifier(INVALID_DEVICE, DEVICE_TYPE),
|
||||
Operation.Status.PENDING);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationsByDeviceAndStatusInvalidDevice",
|
||||
expectedExceptions = OperationManagementException.class)
|
||||
public void getOperationsInvalidOperationId() throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
this.operationMgtService.getOperation(123445);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationsInvalidOperationId", expectedExceptions = IllegalArgumentException.class)
|
||||
public void getOperationsByActivityIdInvalidActivityId() throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
this.operationMgtService.getOperationByActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + 0);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationsByActivityIdInvalidActivityId",
|
||||
expectedExceptions = IllegalArgumentException.class)
|
||||
public void getOperationByActivityIdAndDeviceInvalidActivityId() throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
this.operationMgtService.getOperationByActivityIdAndDevice(
|
||||
DeviceManagementConstants.OperationAttributes.ACTIVITY + 0,
|
||||
new DeviceIdentifier(INVALID_DEVICE, DEVICE_TYPE));
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationByActivityIdAndDeviceInvalidActivityId")
|
||||
public void getPendingOperationsInactiveEnrollment() throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
changeStatus(EnrolmentInfo.Status.INACTIVE);
|
||||
List operations = this.operationMgtService.getPendingOperations(this.deviceIds.get(1));
|
||||
Assert.assertTrue(operations != null);
|
||||
Assert.assertEquals(operations.size(), 4);
|
||||
changeStatus(EnrolmentInfo.Status.ACTIVE);
|
||||
}
|
||||
|
||||
private void changeStatus(EnrolmentInfo.Status status) throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
Device device = this.deviceMgmtProvider.getDevice(this.deviceIds.get(1));
|
||||
Assert.assertTrue(device != null);
|
||||
Assert.assertEquals(device.getType(), DEVICE_TYPE);
|
||||
Assert.assertTrue(device.getEnrolmentInfo() != null);
|
||||
device.getEnrolmentInfo().setStatus(status);
|
||||
boolean modified = this.deviceMgmtProvider.changeDeviceStatus(this.deviceIds.get(1), status);
|
||||
Assert.assertTrue(modified);
|
||||
device = this.deviceMgmtProvider.getDevice(this.deviceIds.get(1));
|
||||
Assert.assertEquals(device.getEnrolmentInfo().getStatus(), status);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getPendingOperationsInactiveEnrollment")
|
||||
public void getNextPendingOperationInactiveEnrollment() throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
changeStatus(EnrolmentInfo.Status.INACTIVE);
|
||||
Operation operation = this.operationMgtService.getNextPendingOperation(this.deviceIds.get(1));
|
||||
Assert.assertTrue(operation != null);
|
||||
changeStatus(EnrolmentInfo.Status.ACTIVE);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getNextPendingOperationInactiveEnrollment")
|
||||
public void getNextPendingOperationForAllOperations() throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
for (int i = 0; i < 4; i++) {
|
||||
Operation operation = this.operationMgtService.getNextPendingOperation(this.deviceIds.get(1));
|
||||
operation.setStatus(Operation.Status.COMPLETED);
|
||||
this.operationMgtService.updateOperation(deviceIds.get(1), operation);
|
||||
}
|
||||
Assert.assertTrue(this.operationMgtService.getNextPendingOperation(this.deviceIds.get(1)) == null);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getNextPendingOperationForAllOperations")
|
||||
public void getOperationByDeviceAndOperationIdForAllOperations() throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
for (int i = 1; i <= 4; i++) {
|
||||
Operation operation = this.operationMgtService.getOperationByDeviceAndOperationId(this.deviceIds.get(1), i);
|
||||
Assert.assertEquals(operation.getStatus(), Operation.Status.COMPLETED);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationByDeviceAndOperationIdForAllOperations")
|
||||
public void getOperationForAllOperations() throws DeviceManagementException,
|
||||
OperationManagementException {
|
||||
for (int i = 1; i <= 4; i++) {
|
||||
Operation operation = this.operationMgtService.getOperation(i);
|
||||
Assert.assertTrue(operation != null);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationForAllOperations")
|
||||
public void addCustomPolicyOperation() throws OperationManagementException, InvalidDeviceException {
|
||||
this.addCustomOperation(Operation.Type.POLICY, DeviceManagementConstants.AuthorizationSkippedOperationCodes.
|
||||
POLICY_OPERATION_CODE);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationForAllOperations")
|
||||
public void addCustomMonitorOperation() throws OperationManagementException, InvalidDeviceException {
|
||||
this.addCustomOperation(Operation.Type.COMMAND, DeviceManagementConstants.AuthorizationSkippedOperationCodes.
|
||||
MONITOR_OPERATION_CODE);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "getOperationForAllOperations")
|
||||
public void addCustomPolicyRevokeOperation() throws OperationManagementException, InvalidDeviceException {
|
||||
this.addCustomOperation(Operation.Type.POLICY, DeviceManagementConstants.AuthorizationSkippedOperationCodes.
|
||||
POLICY_REVOKE_OPERATION_CODE);
|
||||
}
|
||||
|
||||
private void addCustomOperation(Operation.Type type, String operationCode) throws OperationManagementException, InvalidDeviceException {
|
||||
Operation operation = new Operation();
|
||||
operation.setCode(operationCode);
|
||||
operation.setType(type);
|
||||
Activity activity = this.operationMgtService.addOperation(operation, Collections.singletonList(this.deviceIds.get(2)));
|
||||
Assert.assertEquals(activity.getActivityStatus().size(), 1);
|
||||
for (ActivityStatus status : activity.getActivityStatus()) {
|
||||
Assert.assertEquals(status.getStatus(), ActivityStatus.Status.PENDING);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,117 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import org.mockito.Mockito;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
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.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.operation.mgt.OperationManager;
|
||||
import org.wso2.carbon.device.mgt.core.TestDeviceManagementService;
|
||||
import org.wso2.carbon.device.mgt.core.TestTaskServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
|
||||
import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
|
||||
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
|
||||
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService;
|
||||
import org.wso2.carbon.device.mgt.core.task.impl.DeviceTaskManagerServiceImpl;
|
||||
import org.wso2.carbon.ntask.core.internal.TasksDSComponent;
|
||||
import org.wso2.carbon.ntask.core.service.TaskService;
|
||||
import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
|
||||
|
||||
import java.io.File;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.wso2.carbon.device.mgt.core.operation.OperationManagementTests.getOperation;
|
||||
|
||||
/**
|
||||
* This class tests the tasks based operations of {@link OperationManager}
|
||||
*/
|
||||
public class ScheduledTaskOperationTests extends BaseDeviceManagementTest {
|
||||
private static final String DEVICE_TYPE = "OP_SCHEDULE_TEST_TYPE";
|
||||
private static final String DEVICE_ID_PREFIX = "OP-SCHEDULED_TEST-DEVICE-ID-";
|
||||
private static final String COMMAND_OPERATON_CODE = "COMMAND-TEST";
|
||||
private static final int NO_OF_DEVICES = 5;
|
||||
private static final String DS_TASK_COMPONENT_FIELD = "taskService";
|
||||
private static final String CDM_CONFIG_LOCATION = "src" + File.separator + "test" + File.separator + "resources" +
|
||||
File.separator + "config" + File.separator + "operation" + File.separator + "cdm-config.xml";
|
||||
|
||||
private List<DeviceIdentifier> deviceIds = new ArrayList<>();
|
||||
private OperationManager operationMgtService;
|
||||
|
||||
@BeforeClass
|
||||
public void init() throws Exception {
|
||||
for (int i = 0; i < NO_OF_DEVICES; i++) {
|
||||
deviceIds.add(new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE));
|
||||
}
|
||||
List<Device> devices = TestDataHolder.generateDummyDeviceData(this.deviceIds);
|
||||
DeviceManagementProviderService deviceMgtService = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider();
|
||||
initTaskService();
|
||||
deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE,
|
||||
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, COMMAND_OPERATON_CODE));
|
||||
for (Device device : devices) {
|
||||
deviceMgtService.enrollDevice(device);
|
||||
}
|
||||
List<Device> returnedDevices = deviceMgtService.getAllDevices(DEVICE_TYPE);
|
||||
for (Device device : returnedDevices) {
|
||||
if (!device.getDeviceIdentifier().startsWith(DEVICE_ID_PREFIX)) {
|
||||
throw new Exception("Incorrect device with ID - " + device.getDeviceIdentifier() + " returned!");
|
||||
}
|
||||
}
|
||||
DeviceConfigurationManager.getInstance().initConfig(CDM_CONFIG_LOCATION);
|
||||
TestNotificationStrategy notificationStrategy = new TestNotificationStrategy();
|
||||
this.operationMgtService = new OperationManagerImpl(DEVICE_TYPE, notificationStrategy);
|
||||
}
|
||||
|
||||
|
||||
private void initTaskService() throws NoSuchFieldException, IllegalAccessException {
|
||||
TaskService taskService = new TestTaskServiceImpl();
|
||||
DeviceManagementDataHolder.getInstance().setTaskService(taskService);
|
||||
DeviceTaskManagerService deviceTaskManager = new DeviceTaskManagerServiceImpl();
|
||||
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(deviceTaskManager);
|
||||
Field taskServiceField = TasksDSComponent.class.getDeclaredField(DS_TASK_COMPONENT_FIELD);
|
||||
taskServiceField.setAccessible(true);
|
||||
taskServiceField.set(null, Mockito.mock(TaskServiceImpl.class, Mockito.RETURNS_MOCKS));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addCommandOperation() throws DeviceManagementException, OperationManagementException,
|
||||
InvalidDeviceException, NoSuchFieldException {
|
||||
Activity activity = this.operationMgtService.addOperation(getOperation(new CommandOperation(), Operation.Type.COMMAND, COMMAND_OPERATON_CODE),
|
||||
this.deviceIds);
|
||||
Assert.assertEquals(activity.getActivityStatus(), null);
|
||||
Assert.assertEquals(activity.getType(), Activity.Type.COMMAND);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@ -0,0 +1,58 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
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.util.HashMap;
|
||||
|
||||
public class TestNotificationStrategy implements NotificationStrategy {
|
||||
private PushNotificationConfig pushNotificationConfig;
|
||||
|
||||
public TestNotificationStrategy(){
|
||||
this.pushNotificationConfig = new PushNotificationConfig("TEST", true, new HashMap<>());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(NotificationContext ctx) throws PushNotificationExecutionFailedException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public NotificationContext buildContext() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void undeploy() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public PushNotificationConfig getConfig() {
|
||||
return pushNotificationConfig;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,121 @@
|
||||
/*
|
||||
* 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.permission.mgt;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.powermock.api.mockito.PowerMockito;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.testng.Assert;
|
||||
import org.testng.IObjectFactory;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.ObjectFactory;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
|
||||
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
|
||||
import org.wso2.carbon.registry.core.exceptions.RegistryException;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.mockito.MockitoAnnotations.initMocks;
|
||||
|
||||
@PrepareForTest(PermissionUtils.class)
|
||||
public class PermissionManagerServiceTest {
|
||||
|
||||
private static final Log log = LogFactory.getLog(PermissionManagerServiceTest.class);;
|
||||
private static final String PERMISSION_URL = "permission/admin/device-mgt/test/testPermission";
|
||||
private static final String PERMISSION_PATH = "permission/admin/device-mgt/test/testPermission";
|
||||
private static final String PERMISSION_METHOD = "ui.execute";
|
||||
private static final String PERMISSION_NAME = "Test Permission";
|
||||
|
||||
//For create properties to retrieve permission.
|
||||
private static final String HTTP_METHOD = "HTTP_METHOD";
|
||||
private static final String URL = "URL";
|
||||
|
||||
private Permission permission;
|
||||
private PermissionManagerService permissionManagerService;
|
||||
|
||||
@ObjectFactory
|
||||
public IObjectFactory getObjectFactory() {
|
||||
return new org.powermock.modules.testng.PowerMockObjectFactory();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public void init() throws RegistryException {
|
||||
initMocks(this);
|
||||
permissionManagerService = PermissionManagerServiceImpl.getInstance();
|
||||
this.permission = new Permission();
|
||||
permission.setName(PERMISSION_NAME);
|
||||
permission.setPath(PERMISSION_PATH);
|
||||
permission.setMethod(PERMISSION_METHOD);
|
||||
permission.setUrl(PERMISSION_URL);
|
||||
}
|
||||
|
||||
@Test (description = "Create a new permission in the permission tree.")
|
||||
public void testCreatePermission() {
|
||||
try {
|
||||
PowerMockito.mockStatic(PermissionUtils.class);
|
||||
PowerMockito.when(PermissionUtils.putPermission(permission)).thenReturn(true);
|
||||
|
||||
Assert.assertTrue(permissionManagerService.addPermission(permission));
|
||||
} catch (PermissionManagementException e) {
|
||||
log.error("Error creating permission " + e.getErrorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test (dependsOnMethods = {"testCreatePermission"}, description = "Test for retrieving the created permission " +
|
||||
"from the permission tree.")
|
||||
public void testGetPermission() throws PermissionManagementException {
|
||||
Permission permission = permissionManagerService.getPermission(createProperties());
|
||||
|
||||
Assert.assertEquals(permission.getMethod(), PERMISSION_METHOD);
|
||||
Assert.assertEquals(permission.getName(), PERMISSION_NAME);
|
||||
Assert.assertEquals(permission.getPath(), PERMISSION_PATH);
|
||||
Assert.assertEquals(permission.getUrl(), PERMISSION_URL);
|
||||
}
|
||||
|
||||
@Test (dependsOnMethods = {"testCreatePermission"},
|
||||
expectedExceptions = {PermissionManagementException.class},
|
||||
expectedExceptionsMessageRegExp = "Resource URI/HTTP method is empty")
|
||||
public void testGetPermissionError() throws PermissionManagementException {
|
||||
Permission permission = permissionManagerService.getPermission(createErrorProperty());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Property object which will be passed to getPermission method to retrieve a permission.
|
||||
* @return : Property object which contains permission url and method.
|
||||
* */
|
||||
private Properties createProperties() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(URL, PERMISSION_URL);
|
||||
properties.setProperty(HTTP_METHOD, PERMISSION_METHOD);
|
||||
return properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates property object with empty properties.
|
||||
* @return : Properties object with empty set of properties.
|
||||
* */
|
||||
private Properties createErrorProperty() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(URL, "");
|
||||
properties.setProperty(HTTP_METHOD, "");
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
@ -18,72 +18,422 @@ package org.wso2.carbon.device.mgt.core.service;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.AfterClass;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
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.FeatureManager;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
|
||||
import org.wso2.carbon.device.mgt.core.TestDeviceManagementService;
|
||||
import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
|
||||
import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
|
||||
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
|
||||
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.dto.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
|
||||
import org.wso2.carbon.registry.core.config.RegistryContext;
|
||||
import org.wso2.carbon.registry.core.exceptions.RegistryException;
|
||||
import org.wso2.carbon.registry.core.internal.RegistryDataHolder;
|
||||
import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService;
|
||||
import org.wso2.carbon.registry.core.service.RegistryService;
|
||||
import org.wso2.carbon.user.core.service.RealmService;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTest {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceManagementProviderServiceTest.class);
|
||||
private DeviceManagementProviderService providerService;
|
||||
private static final String DEVICE_TYPE = "RANDOM_DEVICE_TYPE";
|
||||
private DeviceDetailsDAO deviceDetailsDAO = DeviceManagementDAOFactory.getDeviceDetailsDAO();
|
||||
|
||||
private static final String NON_EXISTENT_DEVICE_TYPE = "Test";
|
||||
|
||||
DeviceManagementProviderService deviceMgtService;
|
||||
|
||||
@BeforeClass
|
||||
@Override
|
||||
public void init() throws Exception {
|
||||
this.initDataSource();
|
||||
this.providerService = new DeviceManagementProviderServiceImpl();
|
||||
DeviceConfigurationManager.getInstance().initConfig();
|
||||
log.info("Initializing");
|
||||
|
||||
deviceMgtService = new DeviceManagementProviderServiceImpl();
|
||||
DeviceManagementServiceComponent.notifyStartupListeners();
|
||||
DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceMgtService);
|
||||
DeviceManagementDataHolder.getInstance().setRegistryService(getRegistryService());
|
||||
DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(new DeviceAccessAuthorizationServiceImpl());
|
||||
DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(new GroupManagementProviderServiceImpl());
|
||||
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null);
|
||||
deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE,
|
||||
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME));
|
||||
}
|
||||
|
||||
// @Test
|
||||
// public void testEnrollment() {
|
||||
// try {
|
||||
// DeviceManagementPluginRepository deviceManagementPluginRepository = new DeviceManagementPluginRepository();
|
||||
// TestDeviceManagementService testDeviceManagementService =
|
||||
// new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE);
|
||||
// deviceManagementPluginRepository.addDeviceManagementProvider(testDeviceManagementService);
|
||||
//
|
||||
// deviceManagementProviderService = new DeviceManagementProviderServiceImpl();
|
||||
// DeviceManagerUtil.registerDeviceType(TestDataHolder.TEST_DEVICE_TYPE);
|
||||
//
|
||||
// Device device = TestDataHolder.generateDummyDeviceData(TestDataHolder.TEST_DEVICE_TYPE);
|
||||
// boolean isEnrolled = deviceManagementProviderService.enrollDevice(device);
|
||||
//
|
||||
// Assert.assertEquals(isEnrolled, true, "Enrolment fail");
|
||||
// if (isEnrolled) {
|
||||
// TestDataHolder.initialTestDevice = device;
|
||||
// }
|
||||
//
|
||||
// } catch (DeviceManagementException e) {
|
||||
// String msg = "Error occurred while adding device type '" + TestDataHolder.TEST_DEVICE_TYPE + "'";
|
||||
// log.error(msg, e);
|
||||
// Assert.fail(msg, e);
|
||||
// } finally {
|
||||
// DeviceManagementDAOFactory.closeConnection();
|
||||
// }
|
||||
// }
|
||||
private RegistryService getRegistryService() throws RegistryException {
|
||||
RealmService realmService = new InMemoryRealmService();
|
||||
RegistryDataHolder.getInstance().setRealmService(realmService);
|
||||
DeviceManagementDataHolder.getInstance().setRealmService(realmService);
|
||||
InputStream is = this.getClass().getClassLoader().getResourceAsStream("carbon-home/repository/conf/registry.xml");
|
||||
RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
|
||||
context.setSetup(true);
|
||||
return context.getEmbeddedRegistryService();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetFeatureManager() {
|
||||
public void testGetAvailableDeviceTypes() {
|
||||
try {
|
||||
FeatureManager featureManager = providerService.getFeatureManager(NON_EXISTENT_DEVICE_TYPE);
|
||||
Assert.assertNull(featureManager, "Feature manager retrieved is null, which is expected as the " +
|
||||
"input device type provided is non existent");
|
||||
List<DeviceType> deviceTypes = deviceMgtService.getDeviceTypes();
|
||||
Assert.assertTrue(deviceTypes.size() > 0);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while retrieving feature manager associated with device type '" +
|
||||
NON_EXISTENT_DEVICE_TYPE + "'";
|
||||
log.error(msg, e);
|
||||
String msg = "Error occurred while getting the device types";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public void cleanResources() {
|
||||
@Test
|
||||
public void testNullDeviceEnrollment() {
|
||||
try {
|
||||
boolean enrollmentStatus = deviceMgtService.enrollDevice(null);
|
||||
} catch (DeviceManagementException e) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccessfulDeviceEnrollment() {
|
||||
Device device = TestDataHolder.generateDummyDeviceData(DEVICE_TYPE);
|
||||
try {
|
||||
boolean enrollmentStatus = deviceMgtService.enrollDevice(device);
|
||||
Assert.assertTrue(enrollmentStatus);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while enrolling device";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "testSuccessfulDeviceEnrollment")
|
||||
public void testIsEnrolled() {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(TestDataHolder.initialDeviceIdentifier);
|
||||
deviceIdentifier.setType(DEVICE_TYPE);
|
||||
boolean enrollmentStatus = deviceMgtService.isEnrolled(deviceIdentifier);
|
||||
Assert.assertTrue(enrollmentStatus);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while checking enrollment status.";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsEnrolledForNonExistingDevice() {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId("34535235235235235");
|
||||
deviceIdentifier.setType(DEVICE_TYPE);
|
||||
boolean enrollmentStatus = deviceMgtService.isEnrolled(deviceIdentifier);
|
||||
Assert.assertFalse(enrollmentStatus);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while checking enrollment status.";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = DeviceManagementException.class)
|
||||
public void testIsEnrolledForNullDevice() throws DeviceManagementException {
|
||||
deviceMgtService.isEnrolled(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonExistentDeviceType() {
|
||||
Device device = TestDataHolder.generateDummyDeviceData("abc");
|
||||
try {
|
||||
boolean enrollmentStatus = deviceMgtService.enrollDevice(device);
|
||||
Assert.assertFalse(enrollmentStatus);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while enrolling device";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
|
||||
public void testReEnrollmentofSameDeviceUnderSameUser() {
|
||||
Device device = TestDataHolder.generateDummyDeviceData(DEVICE_TYPE);
|
||||
|
||||
try {
|
||||
boolean enrollment = deviceMgtService.enrollDevice(device);
|
||||
|
||||
Assert.assertTrue(enrollment);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while enrolling device";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = {"testReEnrollmentofSameDeviceUnderSameUser"})
|
||||
public void testReEnrollmentofSameDeviceWithOtherUser() {
|
||||
|
||||
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
|
||||
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
|
||||
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
|
||||
enrolmentInfo.setOwner("user1");
|
||||
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
|
||||
enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED);
|
||||
|
||||
Device alternateDevice = TestDataHolder.generateDummyDeviceData("12345", DEVICE_TYPE,
|
||||
enrolmentInfo);
|
||||
|
||||
try {
|
||||
Device retrievedDevice1 = deviceMgtService.getDevice(new DeviceIdentifier("12345", DEVICE_TYPE));
|
||||
|
||||
deviceMgtService.enrollDevice(alternateDevice);
|
||||
Device retrievedDevice2 = deviceMgtService.getDevice(new DeviceIdentifier(alternateDevice
|
||||
.getDeviceIdentifier(), alternateDevice.getType()));
|
||||
|
||||
log.info(retrievedDevice1.getEnrolmentInfo().getOwner());
|
||||
log.info(retrievedDevice2.getEnrolmentInfo().getOwner());
|
||||
|
||||
Assert.assertFalse(retrievedDevice1.getEnrolmentInfo().getOwner().equalsIgnoreCase
|
||||
(retrievedDevice2.getEnrolmentInfo().getOwner()));
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error Occured while enrolling device";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test(dependsOnMethods = {"testReEnrollmentofSameDeviceWithOtherUser"})
|
||||
public void testDisenrollment() {
|
||||
Device device = TestDataHolder.generateDummyDeviceData(DEVICE_TYPE);
|
||||
try {
|
||||
boolean disenrollmentStatus = deviceMgtService.disenrollDevice(new DeviceIdentifier
|
||||
(device
|
||||
.getDeviceIdentifier(),
|
||||
device.getType()));
|
||||
log.info(disenrollmentStatus);
|
||||
|
||||
Assert.assertTrue(disenrollmentStatus);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while enrolling device";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
|
||||
public void testGetDeviceCount() {
|
||||
try {
|
||||
int count = deviceMgtService.getDeviceCount();
|
||||
Assert.assertTrue(count > 0);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while getting the device count";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
|
||||
public void testGetDeviceCountForUser() {
|
||||
try {
|
||||
int count = deviceMgtService.getDeviceCount(TestDataHolder.OWNER);
|
||||
Assert.assertTrue(count > 0);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while getting the device count";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDeviceCountForNonExistingUser() {
|
||||
try {
|
||||
int count = deviceMgtService.getDeviceCount("ABCD");
|
||||
Assert.assertEquals(count, 0);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while getting the device count";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = DeviceManagementException.class)
|
||||
public void testGetDeviceCountForNullUser() throws DeviceManagementException {
|
||||
deviceMgtService.getDeviceCount(null);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
|
||||
public void testIsActive() {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(TestDataHolder.initialDeviceIdentifier);
|
||||
deviceIdentifier.setType(DEVICE_TYPE);
|
||||
Assert.assertTrue(deviceMgtService.isActive(deviceIdentifier));
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while checking the device status";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsActiveForNonExistingDevice() {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId("34535235235235235");
|
||||
deviceIdentifier.setType("TEST_TYPE");
|
||||
Assert.assertFalse(deviceMgtService.isActive(deviceIdentifier));
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while checking the device status";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
|
||||
public void testSetActive() {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(TestDataHolder.initialDeviceIdentifier);
|
||||
deviceIdentifier.setType(DEVICE_TYPE);
|
||||
Assert.assertFalse(deviceMgtService.setActive(deviceIdentifier, true));
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while updating the device status";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetActiveForNonExistingDevice() {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId("34535235235235235");
|
||||
deviceIdentifier.setType("TEST_TYPE");
|
||||
Assert.assertFalse(deviceMgtService.setActive(deviceIdentifier, true));
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while updating the device status for non-existing device";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
|
||||
public void testGetDeviceEnrolledTenants() {
|
||||
try {
|
||||
List<Integer> tenants = deviceMgtService.getDeviceEnrolledTenants();
|
||||
Assert.assertEquals(tenants.size(), 1);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while updating the device status";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
|
||||
public void testGetDevice() {
|
||||
try {
|
||||
Device device = deviceMgtService.getDevice(new DeviceIdentifier("12345",DEVICE_TYPE));
|
||||
Assert.assertTrue(device.getDeviceIdentifier().equalsIgnoreCase("12345"));
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while updating the device status";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
|
||||
public void testGetDeviceWithInfo() {
|
||||
try {
|
||||
Device device = deviceMgtService.getDevice(new DeviceIdentifier("12345", DEVICE_TYPE)
|
||||
, true);
|
||||
Assert.assertTrue(device.getDeviceInfo() != null);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while updating the device status";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
|
||||
public void testGetDeviceWithOutInfo() {
|
||||
try {
|
||||
Device device = deviceMgtService.getDevice(new DeviceIdentifier("12345", DEVICE_TYPE)
|
||||
, false);
|
||||
Assert.assertTrue(device.getDeviceInfo() == null);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while updating the device status";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
|
||||
public void testGetAllDevicesOfRole() {
|
||||
try {
|
||||
List<Device> devices = deviceMgtService.getAllDevicesOfRole("admin");
|
||||
Assert.assertTrue(devices.size() > 0);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while updating the device status";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
|
||||
public void testDeviceByOwner() {
|
||||
try {
|
||||
Device device = deviceMgtService.getDevice(new DeviceIdentifier("12345",
|
||||
DEVICE_TYPE), "admin", true);
|
||||
Assert.assertTrue(device != null);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while updating the device status";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
|
||||
public void testDeviceByDate() {
|
||||
try {
|
||||
Device initialDevice = deviceMgtService.getDevice(new DeviceIdentifier("12345",
|
||||
DEVICE_TYPE));
|
||||
|
||||
DeviceManagementDAOFactory.beginTransaction();
|
||||
|
||||
//Device details table will be reffered when looking for last updated time
|
||||
//This dao entry is to mimic a device info operation
|
||||
deviceDetailsDAO.addDeviceInformation(initialDevice.getId(), TestDataHolder
|
||||
.generateDummyDeviceInfo());
|
||||
} catch (DeviceManagementException e) {
|
||||
e.printStackTrace();
|
||||
} catch (TransactionManagementException e) {
|
||||
e.printStackTrace();
|
||||
} catch (DeviceDetailsMgtDAOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
DeviceManagementDAOFactory.closeConnection();
|
||||
}
|
||||
|
||||
try {
|
||||
Device device = deviceMgtService.getDevice(new DeviceIdentifier("12345",
|
||||
DEVICE_TYPE), yesterday());
|
||||
Assert.assertTrue(device != null);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while updating the device status";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = {"testDeviceByDate"})
|
||||
public void testDeviceByDateAndOwner() {
|
||||
try {
|
||||
Device device = deviceMgtService.getDevice(new DeviceIdentifier("12345",
|
||||
DEVICE_TYPE), "admin", yesterday(), true);
|
||||
Assert.assertTrue(device != null);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while updating the device status";
|
||||
Assert.fail(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
private Date yesterday() {
|
||||
final Calendar cal = Calendar.getInstance();
|
||||
cal.add(Calendar.DATE, -1);
|
||||
return cal.getTime();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -0,0 +1,285 @@
|
||||
/*
|
||||
* 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.service;
|
||||
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.device.mgt.common.*;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.*;
|
||||
import org.wso2.carbon.device.mgt.core.TestUtils;
|
||||
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
|
||||
import org.wso2.carbon.device.mgt.core.config.cache.DeviceCacheConfiguration;
|
||||
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
|
||||
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
|
||||
import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService;
|
||||
import org.wso2.carbon.user.api.Permission;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
import org.wso2.carbon.user.api.UserStoreManager;
|
||||
import org.wso2.carbon.user.core.service.RealmService;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class GroupManagementProviderServiceTest extends BaseDeviceManagementTest {
|
||||
|
||||
private GroupManagementProviderService groupManagementProviderService;
|
||||
private static final String DEFAULT_ADMIN_ROLE = "admin";
|
||||
private static final String[] DEFAULT_ADMIN_PERMISSIONS = {"/permission/device-mgt/admin/groups",
|
||||
"/permission/device-mgt/user/groups"};
|
||||
|
||||
@BeforeClass
|
||||
@Override
|
||||
public void init() throws Exception {
|
||||
groupManagementProviderService = new GroupManagementProviderServiceImpl();
|
||||
RealmService realmService = new InMemoryRealmService();
|
||||
DeviceManagementDataHolder.getInstance().setRealmService(realmService);
|
||||
realmService.getTenantManager().getSuperTenantDomain();
|
||||
DeviceConfigurationManager.getInstance().initConfig();
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = {GroupManagementException.class, GroupAlreadyExistException.class})
|
||||
public void createGroupNull() throws GroupManagementException, GroupAlreadyExistException {
|
||||
groupManagementProviderService.createGroup(null, null, null);
|
||||
}
|
||||
|
||||
|
||||
@Test(expectedExceptions = {GroupManagementException.class, GroupAlreadyExistException.class, TransactionManagementException.class})
|
||||
public void createGroupError() throws GroupManagementException, GroupAlreadyExistException, TransactionManagementException {
|
||||
GroupManagementDAOFactory.beginTransaction();
|
||||
groupManagementProviderService.createGroup(TestUtils.createDeviceGroup4(), DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void createGroup() throws GroupManagementException, GroupAlreadyExistException {
|
||||
groupManagementProviderService.createGroup(TestUtils.createDeviceGroup1(), DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS);
|
||||
groupManagementProviderService.createGroup(TestUtils.createDeviceGroup2(), DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS);
|
||||
groupManagementProviderService.createGroup(TestUtils.createDeviceGroup3(), DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS);
|
||||
groupManagementProviderService.createGroup(TestUtils.createDeviceGroup4(), DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void updateGroup() throws GroupManagementException, GroupNotExistException {
|
||||
DeviceGroup deviceGroup = groupManagementProviderService.getGroup(TestUtils.createDeviceGroup1().getName());
|
||||
deviceGroup.setName(deviceGroup.getName() + "_UPDATED");
|
||||
groupManagementProviderService.updateGroup(deviceGroup, deviceGroup.getGroupId());
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"), expectedExceptions = {GroupManagementException.class})
|
||||
public void getGroupNull() throws GroupManagementException, GroupNotExistException {
|
||||
groupManagementProviderService.getGroup(null);
|
||||
}
|
||||
|
||||
// Rename again to use in different place.
|
||||
@Test(dependsOnMethods = ("updateGroup"))
|
||||
public void updateGroupSecondTime() throws GroupManagementException, GroupNotExistException {
|
||||
DeviceGroup deviceGroup = groupManagementProviderService.getGroup(TestUtils.createDeviceGroup1().getName() + "_UPDATED");
|
||||
deviceGroup.setName(TestUtils.createDeviceGroup1().getName());
|
||||
groupManagementProviderService.updateGroup(deviceGroup, deviceGroup.getGroupId());
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"), expectedExceptions = {GroupManagementException.class, GroupNotExistException.class})
|
||||
public void updateGroupError() throws GroupManagementException, GroupNotExistException {
|
||||
groupManagementProviderService.updateGroup(null, 1);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"), expectedExceptions = {GroupManagementException.class, GroupNotExistException.class})
|
||||
public void updateGroupErrorNotExist() throws GroupManagementException, GroupNotExistException {
|
||||
DeviceGroup deviceGroup = groupManagementProviderService.getGroup(TestUtils.createDeviceGroup2().getName());
|
||||
deviceGroup.setName(deviceGroup.getName() + "_UPDATED");
|
||||
groupManagementProviderService.updateGroup(deviceGroup, 6);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void deleteGroup() throws GroupManagementException {
|
||||
DeviceGroup deviceGroup = groupManagementProviderService.getGroup(TestUtils.createDeviceGroup4().getName());
|
||||
Assert.assertTrue(groupManagementProviderService.deleteGroup(deviceGroup.getGroupId()));
|
||||
}
|
||||
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void deleteGroupNotExists() throws GroupManagementException {
|
||||
groupManagementProviderService.deleteGroup(8);
|
||||
}
|
||||
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void getGroup() throws GroupManagementException {
|
||||
|
||||
DeviceGroup deviceGroup = groupManagementProviderService.getGroup(TestUtils.createDeviceGroup3().getName());
|
||||
Assert.assertNotNull(groupManagementProviderService.getGroup(deviceGroup.getGroupId()));
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void getGroupByName() throws GroupManagementException {
|
||||
Assert.assertNotNull(groupManagementProviderService.getGroup(TestUtils.createDeviceGroup3().getName()));
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void getGroups() throws GroupManagementException {
|
||||
List<DeviceGroup> deviceGroups = groupManagementProviderService.getGroups();
|
||||
Assert.assertNotNull(deviceGroups);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void getGroupsByUsername() throws GroupManagementException {
|
||||
List<DeviceGroup> deviceGroups = groupManagementProviderService.getGroups("admin");
|
||||
Assert.assertNotNull(deviceGroups);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"), expectedExceptions = {GroupManagementException.class})
|
||||
public void getGroupsByUsernameError() throws GroupManagementException {
|
||||
groupManagementProviderService.getGroups((String) null);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void getGroupsByPagination() throws GroupManagementException {
|
||||
PaginationResult result = groupManagementProviderService.getGroups(TestUtils.createPaginationRequest());
|
||||
Assert.assertNotNull(result);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"), expectedExceptions = {GroupManagementException.class})
|
||||
public void getGroupsByPaginationError() throws GroupManagementException {
|
||||
GroupPaginationRequest request = null;
|
||||
groupManagementProviderService.getGroups(request);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void getGroupsByUsernameAndPagination()
|
||||
throws GroupManagementException {
|
||||
PaginationResult result = groupManagementProviderService.getGroups("admin", TestUtils.createPaginationRequest());
|
||||
Assert.assertNotNull(result);
|
||||
}
|
||||
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"), expectedExceptions = {GroupManagementException.class})
|
||||
public void getGroupsByUsernameAndPaginationError()
|
||||
throws GroupManagementException {
|
||||
groupManagementProviderService.getGroups(null, TestUtils.createPaginationRequest());
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void getGroupCount() throws GroupManagementException {
|
||||
int x = groupManagementProviderService.getGroupCount();
|
||||
Assert.assertNotNull(x);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void getGroupCountByUsername(String username) throws GroupManagementException {
|
||||
int x = groupManagementProviderService.getGroupCount(username);
|
||||
Assert.assertNotNull(x);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("updateGroupSecondTime"))
|
||||
public void manageGroupSharing() throws GroupManagementException, RoleDoesNotExistException, UserStoreException {
|
||||
groupManagementProviderService.manageGroupSharing(0, null);
|
||||
List<String> newRoles = new ArrayList<>();
|
||||
newRoles.add("TEST_ROLE_1");
|
||||
newRoles.add("TEST_ROLE_2");
|
||||
newRoles.add("TEST_ROLE_3");
|
||||
|
||||
UserStoreManager userStoreManager =
|
||||
DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(
|
||||
-1234).getUserStoreManager();
|
||||
Permission[] permissions = new Permission[1];
|
||||
Permission perm = new Permission("/admin/test/perm", "add");
|
||||
permissions[0] = perm;
|
||||
|
||||
userStoreManager.addRole("TEST_ROLE_1", null, permissions);
|
||||
userStoreManager.addRole("TEST_ROLE_2", null, permissions);
|
||||
userStoreManager.addRole("TEST_ROLE_3", null, permissions);
|
||||
|
||||
groupManagementProviderService.manageGroupSharing(groupManagementProviderService.getGroup(
|
||||
TestUtils.createDeviceGroup1().getName()).getGroupId(), newRoles);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void getRoles() throws GroupManagementException {
|
||||
List<String> roles = groupManagementProviderService.getRoles(1);
|
||||
Assert.assertNotNull(roles);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void getDevices() throws GroupManagementException {
|
||||
List<Device> devices = groupManagementProviderService.getDevices(1, 1, 50);
|
||||
Assert.assertNotNull(devices);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void getDeviceCount() throws GroupManagementException {
|
||||
int x = groupManagementProviderService.getDeviceCount(1);
|
||||
Assert.assertEquals(0, x);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void addDevices() throws GroupManagementException, DeviceNotFoundException {
|
||||
|
||||
DeviceCacheConfiguration configuration = new DeviceCacheConfiguration();
|
||||
configuration.setEnabled(false);
|
||||
|
||||
DeviceConfigurationManager.getInstance().getDeviceManagementConfig().setDeviceCacheConfiguration(configuration);
|
||||
List<DeviceIdentifier> list = TestUtils.getDeviceIdentifiersList();
|
||||
groupManagementProviderService.addDevices(groupManagementProviderService.getGroup(
|
||||
TestUtils.createDeviceGroup1().getName()).getGroupId(), list);
|
||||
groupManagementProviderService.addDevices(groupManagementProviderService.getGroup(
|
||||
TestUtils.createDeviceGroup2().getName()).getGroupId(), list);
|
||||
groupManagementProviderService.addDevices(groupManagementProviderService.getGroup(
|
||||
TestUtils.createDeviceGroup3().getName()).getGroupId(), list);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("addDevices"))
|
||||
public void removeDevice() throws GroupManagementException, DeviceNotFoundException {
|
||||
List<DeviceIdentifier> list = TestUtils.getDeviceIdentifiersList();
|
||||
groupManagementProviderService.removeDevice(groupManagementProviderService.getGroup(
|
||||
TestUtils.createDeviceGroup2().getName()).getGroupId(), list);
|
||||
groupManagementProviderService.removeDevice(groupManagementProviderService.getGroup(
|
||||
TestUtils.createDeviceGroup3().getName()).getGroupId(), list);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createGroup"))
|
||||
public void getGroupsByUsernameAndPermissions() throws GroupManagementException {
|
||||
List<DeviceGroup> groups = groupManagementProviderService.getGroups("admin", "/permission/device-mgt/admin/groups");
|
||||
Assert.assertNotNull(groups);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("addDevices"))
|
||||
public void getGroupsByDeviceIdentifier() throws GroupManagementException {
|
||||
DeviceIdentifier identifier = new DeviceIdentifier();
|
||||
identifier.setId("12345");
|
||||
identifier.setType("Test");
|
||||
List<DeviceGroup> groups = groupManagementProviderService.getGroups(identifier);
|
||||
Assert.assertNotNull(groups);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createDefaultGroup() throws GroupManagementException {
|
||||
groupManagementProviderService.createDefaultGroup("BYOD");
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = ("createDefaultGroup"))
|
||||
public void createDefaultGroupTwice() throws GroupManagementException {
|
||||
groupManagementProviderService.createDefaultGroup("BYOD");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,124 @@
|
||||
package org.wso2.carbon.device.mgt.core.task;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.opensaml.xml.signature.P;
|
||||
import org.powermock.api.mockito.PowerMockito;
|
||||
import org.quartz.impl.StdSchedulerFactory;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
|
||||
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
|
||||
import org.wso2.carbon.device.mgt.core.TestTaskServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.core.TestUtils;
|
||||
import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
|
||||
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.core.task.impl.DeviceTaskManagerServiceImpl;
|
||||
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.TaskUtils;
|
||||
import org.wso2.carbon.ntask.core.impl.QuartzCachedThreadPool;
|
||||
import org.wso2.carbon.ntask.core.internal.TasksDSComponent;
|
||||
import org.wso2.carbon.ntask.core.service.TaskService;
|
||||
import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl;
|
||||
import org.wso2.carbon.registry.core.exceptions.RegistryException;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
public class DeviceTaskManagerServiceTest {
|
||||
private static final Log log = LogFactory.getLog(DeviceTaskManagerService.class);
|
||||
private static final String TASK_TYPE = "DEVICE_MONITORING";
|
||||
private DeviceTaskManagerService deviceTaskManagerService;
|
||||
@Mock private TaskService taskService;
|
||||
|
||||
@BeforeClass public void init() throws Exception {
|
||||
DeviceConfigurationManager.getInstance().initConfig();
|
||||
log.info("Initializing Device Task Manager Service Test Suite");
|
||||
this.taskService = new TestTaskServiceImpl();
|
||||
DeviceManagementDataHolder.getInstance().setTaskService(this.taskService);
|
||||
this.deviceTaskManagerService = new DeviceTaskManagerServiceImpl();
|
||||
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(this.deviceTaskManagerService);
|
||||
Field taskServiceField = TasksDSComponent.class.getDeclaredField("taskService");
|
||||
taskServiceField.setAccessible(true);
|
||||
taskServiceField.set(null, Mockito.mock(TaskServiceImpl.class, Mockito.RETURNS_MOCKS));
|
||||
}
|
||||
|
||||
@Test(groups = "Device Task Manager")
|
||||
public void testStartTask() {
|
||||
try {
|
||||
log.debug("Attempting to start task from testStartTask");
|
||||
this.deviceTaskManagerService
|
||||
.startTask(TestDataHolder.TEST_DEVICE_TYPE, generateValidMonitoringTaskConfig("DEVICE_INFO"));
|
||||
TaskManager taskManager = this.taskService.getTaskManager(TASK_TYPE);
|
||||
Assert.assertEquals(this.taskService.getRegisteredTaskTypes().size(), 1);
|
||||
Assert.assertNotNull(taskManager
|
||||
.getTask(TestDataHolder.TEST_DEVICE_TYPE + String.valueOf(TestDataHolder.SUPER_TENANT_ID)));
|
||||
log.debug("Task Successfully started");
|
||||
} catch (DeviceMgtTaskException | TaskException e) {
|
||||
Assert.fail("Exception occurred when starting the task", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(groups = "Device Task Manager", dependsOnMethods = "testStartTask")
|
||||
public void testUpdateTask() {
|
||||
try {
|
||||
log.debug("Attempting to update task from testStartTask");
|
||||
this.deviceTaskManagerService
|
||||
.updateTask(TestDataHolder.TEST_DEVICE_TYPE, generateValidMonitoringTaskConfig("DEVICE_LOCATION"));
|
||||
Assert.assertEquals(this.taskService.getRegisteredTaskTypes().size(), 1);
|
||||
TaskManager taskManager = this.taskService.getTaskManager(TASK_TYPE);
|
||||
Assert.assertEquals(taskManager.getAllTasks().size(), 1);
|
||||
log.debug("Task Successfully updated");
|
||||
} catch (DeviceMgtTaskException | TaskException e) {
|
||||
Assert.fail("Exception occurred when updating the task", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(groups = "Device Task Manager", dependsOnMethods = "testUpdateTask")
|
||||
public void testStopTask() {
|
||||
log.debug("Attempting to stop task from testStopTask");
|
||||
try {
|
||||
this.deviceTaskManagerService
|
||||
.stopTask(TestDataHolder.TEST_DEVICE_TYPE, generateValidMonitoringTaskConfig("DEVICE_LOCATION"));
|
||||
TaskManager taskManager = this.taskService.getTaskManager(TASK_TYPE);
|
||||
Assert.assertEquals(taskManager.getAllTasks().size(), 0);
|
||||
} catch (DeviceMgtTaskException | TaskException e) {
|
||||
Assert.fail("Exception occurred when stopping the task", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private OperationMonitoringTaskConfig generateValidMonitoringTaskConfig(String operationConfig) {
|
||||
OperationMonitoringTaskConfig validTaskConfig = new OperationMonitoringTaskConfig();
|
||||
List<MonitoringOperation> operationList = new ArrayList<>();
|
||||
MonitoringOperation operation = new MonitoringOperation();
|
||||
operation.setTaskName(operationConfig);
|
||||
operation.setRecurrentTimes(1);
|
||||
operationList.add(operation);
|
||||
|
||||
validTaskConfig.setEnabled(true);
|
||||
validTaskConfig.setFrequency(60000);
|
||||
validTaskConfig.setMonitoringOperation(operationList);
|
||||
|
||||
return validTaskConfig;
|
||||
}
|
||||
|
||||
private Properties getStandardQuartzProps() {
|
||||
Properties result = new Properties();
|
||||
result.put("org.quartz.scheduler.skipUpdateCheck", "true");
|
||||
result.put("org.quartz.threadPool.class", QuartzCachedThreadPool.class.getName());
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,82 @@
|
||||
package org.wso2.carbon.device.mgt.core.task;
|
||||
|
||||
import org.wso2.carbon.ntask.common.TaskException;
|
||||
import org.wso2.carbon.ntask.core.TaskInfo;
|
||||
import org.wso2.carbon.ntask.core.TaskManager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class TestTaskManagerImpl implements TaskManager {
|
||||
private List<TaskInfo> registeredTasks;
|
||||
|
||||
public TestTaskManagerImpl() {
|
||||
this.registeredTasks = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initStartupTasks() throws TaskException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void scheduleTask(String taskName) throws TaskException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rescheduleTask(String taskName) throws TaskException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteTask(String taskName) throws TaskException {
|
||||
for (TaskInfo task : this.registeredTasks) {
|
||||
if (task.getName().contains(taskName)) {
|
||||
this.registeredTasks.remove(task);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pauseTask(String taskName) throws TaskException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resumeTask(String taskName) throws TaskException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerTask(TaskInfo taskInfo) throws TaskException {
|
||||
this.registeredTasks.add(taskInfo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TaskState getTaskState(String taskName) throws TaskException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TaskInfo getTask(String taskName) throws TaskException {
|
||||
for (TaskInfo task : this.registeredTasks) {
|
||||
if (task.getName().contains(taskName)) {
|
||||
return task;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TaskInfo> getAllTasks() throws TaskException {
|
||||
return this.registeredTasks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTaskScheduled(String taskName) throws TaskException {
|
||||
return this.registeredTasks.size() > 0;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,429 @@
|
||||
CREATE TABLE IF NOT EXISTS REG_CLUSTER_LOCK (
|
||||
REG_LOCK_NAME VARCHAR (20),
|
||||
REG_LOCK_STATUS VARCHAR (20),
|
||||
REG_LOCKED_TIME TIMESTAMP,
|
||||
REG_TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (REG_LOCK_NAME)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_LOG (
|
||||
REG_LOG_ID INTEGER AUTO_INCREMENT,
|
||||
REG_PATH VARCHAR (2000),
|
||||
REG_USER_ID VARCHAR (31) NOT NULL,
|
||||
REG_LOGGED_TIME TIMESTAMP NOT NULL,
|
||||
REG_ACTION INTEGER NOT NULL,
|
||||
REG_ACTION_DATA VARCHAR (500),
|
||||
REG_TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (REG_LOG_ID, REG_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS REG_LOG_IND_BY_REG_LOGTIME ON REG_LOG(REG_LOGGED_TIME, REG_TENANT_ID);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_PATH(
|
||||
REG_PATH_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
REG_PATH_VALUE VARCHAR(2000) NOT NULL,
|
||||
REG_PATH_PARENT_ID INT,
|
||||
REG_TENANT_ID INTEGER DEFAULT 0,
|
||||
CONSTRAINT PK_REG_PATH PRIMARY KEY(REG_PATH_ID, REG_TENANT_ID)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS REG_PATH_IND_BY_NAME ON REG_PATH(REG_PATH_VALUE, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_PATH_IND_BY_PARENT_ID ON REG_PATH(REG_PATH_PARENT_ID, REG_TENANT_ID);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_CONTENT (
|
||||
REG_CONTENT_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
REG_CONTENT_DATA LONGBLOB,
|
||||
REG_TENANT_ID INTEGER DEFAULT 0,
|
||||
CONSTRAINT PK_REG_CONTENT PRIMARY KEY(REG_CONTENT_ID, REG_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_CONTENT_HISTORY (
|
||||
REG_CONTENT_ID INTEGER NOT NULL,
|
||||
REG_CONTENT_DATA LONGBLOB,
|
||||
REG_DELETED SMALLINT,
|
||||
REG_TENANT_ID INTEGER DEFAULT 0,
|
||||
CONSTRAINT PK_REG_CONTENT_HISTORY PRIMARY KEY(REG_CONTENT_ID, REG_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_RESOURCE (
|
||||
REG_PATH_ID INTEGER NOT NULL,
|
||||
REG_NAME VARCHAR(256),
|
||||
REG_VERSION INTEGER NOT NULL AUTO_INCREMENT,
|
||||
REG_MEDIA_TYPE VARCHAR(500),
|
||||
REG_CREATOR VARCHAR(31) NOT NULL,
|
||||
REG_CREATED_TIME TIMESTAMP NOT NULL,
|
||||
REG_LAST_UPDATOR VARCHAR(31),
|
||||
REG_LAST_UPDATED_TIME TIMESTAMP NOT NULL,
|
||||
REG_DESCRIPTION VARCHAR(1000),
|
||||
REG_CONTENT_ID INTEGER,
|
||||
REG_TENANT_ID INTEGER DEFAULT 0,
|
||||
REG_UUID VARCHAR(100) NOT NULL,
|
||||
CONSTRAINT PK_REG_RESOURCE PRIMARY KEY(REG_VERSION, REG_TENANT_ID)
|
||||
);
|
||||
|
||||
ALTER TABLE REG_RESOURCE ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID);
|
||||
ALTER TABLE REG_RESOURCE ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_FK_BY_CONTENT_ID FOREIGN KEY (REG_CONTENT_ID, REG_TENANT_ID) REFERENCES REG_CONTENT (REG_CONTENT_ID, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_NAME ON REG_RESOURCE(REG_NAME, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_PATH_ID_NAME ON REG_RESOURCE(REG_PATH_ID, REG_NAME, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_UUID ON REG_RESOURCE(REG_UUID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_TENANT ON REG_RESOURCE(REG_TENANT_ID, REG_UUID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_TYPE ON REG_RESOURCE(REG_TENANT_ID, REG_MEDIA_TYPE);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_RESOURCE_HISTORY (
|
||||
REG_PATH_ID INTEGER NOT NULL,
|
||||
REG_NAME VARCHAR(256),
|
||||
REG_VERSION INTEGER NOT NULL,
|
||||
REG_MEDIA_TYPE VARCHAR(500),
|
||||
REG_CREATOR VARCHAR(31) NOT NULL,
|
||||
REG_CREATED_TIME TIMESTAMP NOT NULL,
|
||||
REG_LAST_UPDATOR VARCHAR(31),
|
||||
REG_LAST_UPDATED_TIME TIMESTAMP NOT NULL,
|
||||
REG_DESCRIPTION VARCHAR(1000),
|
||||
REG_CONTENT_ID INTEGER,
|
||||
REG_DELETED SMALLINT,
|
||||
REG_TENANT_ID INTEGER DEFAULT 0,
|
||||
REG_UUID VARCHAR(100) NOT NULL,
|
||||
CONSTRAINT PK_REG_RESOURCE_HISTORY PRIMARY KEY(REG_VERSION, REG_TENANT_ID)
|
||||
);
|
||||
|
||||
ALTER TABLE REG_RESOURCE_HISTORY ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_HIST_FK_BY_PATHID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID);
|
||||
ALTER TABLE REG_RESOURCE_HISTORY ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_HIST_FK_BY_CONTENT_ID FOREIGN KEY (REG_CONTENT_ID, REG_TENANT_ID) REFERENCES REG_CONTENT_HISTORY (REG_CONTENT_ID, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_HISTORY_IND_BY_NAME ON REG_RESOURCE_HISTORY(REG_NAME, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_HISTORY_IND_BY_PATH_ID_NAME ON REG_RESOURCE(REG_PATH_ID, REG_NAME, REG_TENANT_ID);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_COMMENT (
|
||||
REG_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
REG_COMMENT_TEXT VARCHAR(500) NOT NULL,
|
||||
REG_USER_ID VARCHAR(31) NOT NULL,
|
||||
REG_COMMENTED_TIME TIMESTAMP NOT NULL,
|
||||
REG_TENANT_ID INTEGER DEFAULT 0,
|
||||
CONSTRAINT PK_REG_COMMENT PRIMARY KEY(REG_ID, REG_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_RESOURCE_COMMENT (
|
||||
REG_COMMENT_ID INTEGER NOT NULL,
|
||||
REG_VERSION INTEGER,
|
||||
REG_PATH_ID INTEGER,
|
||||
REG_RESOURCE_NAME VARCHAR(256),
|
||||
REG_TENANT_ID INTEGER DEFAULT 0
|
||||
);
|
||||
|
||||
ALTER TABLE REG_RESOURCE_COMMENT ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_COMMENT_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID);
|
||||
ALTER TABLE REG_RESOURCE_COMMENT ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_COMMENT_FK_BY_COMMENT_ID FOREIGN KEY (REG_COMMENT_ID, REG_TENANT_ID) REFERENCES REG_COMMENT (REG_ID, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_COMMENT_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_RESOURCE_COMMENT(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_COMMENT_IND_BY_VERSION ON REG_RESOURCE_COMMENT(REG_VERSION, REG_TENANT_ID);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_RATING (
|
||||
REG_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
REG_RATING INTEGER NOT NULL,
|
||||
REG_USER_ID VARCHAR(31) NOT NULL,
|
||||
REG_RATED_TIME TIMESTAMP NOT NULL,
|
||||
REG_TENANT_ID INTEGER DEFAULT 0,
|
||||
CONSTRAINT PK_REG_RATING PRIMARY KEY(REG_ID, REG_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_RESOURCE_RATING (
|
||||
REG_RATING_ID INTEGER NOT NULL,
|
||||
REG_VERSION INTEGER,
|
||||
REG_PATH_ID INTEGER,
|
||||
REG_RESOURCE_NAME VARCHAR(256),
|
||||
REG_TENANT_ID INTEGER DEFAULT 0
|
||||
);
|
||||
|
||||
ALTER TABLE REG_RESOURCE_RATING ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_RATING_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID);
|
||||
ALTER TABLE REG_RESOURCE_RATING ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_RATING_FK_BY_RATING_ID FOREIGN KEY (REG_RATING_ID, REG_TENANT_ID) REFERENCES REG_RATING (REG_ID, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_RATING_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_RESOURCE_RATING(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_RATING_IND_BY_VERSION ON REG_RESOURCE_RATING(REG_VERSION, REG_TENANT_ID);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_TAG (
|
||||
REG_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
REG_TAG_NAME VARCHAR(500) NOT NULL,
|
||||
REG_USER_ID VARCHAR(31) NOT NULL,
|
||||
REG_TAGGED_TIME TIMESTAMP NOT NULL,
|
||||
REG_TENANT_ID INTEGER DEFAULT 0,
|
||||
CONSTRAINT PK_REG_TAG PRIMARY KEY(REG_ID, REG_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_RESOURCE_TAG (
|
||||
REG_TAG_ID INTEGER NOT NULL,
|
||||
REG_VERSION INTEGER,
|
||||
REG_PATH_ID INTEGER,
|
||||
REG_RESOURCE_NAME VARCHAR(256),
|
||||
REG_TENANT_ID INTEGER DEFAULT 0
|
||||
);
|
||||
|
||||
ALTER TABLE REG_RESOURCE_TAG ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_TAG_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID);
|
||||
ALTER TABLE REG_RESOURCE_TAG ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_TAG_FK_BY_TAG_ID FOREIGN KEY (REG_TAG_ID, REG_TENANT_ID) REFERENCES REG_TAG (REG_ID, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_TAG_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_RESOURCE_TAG(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_TAG_IND_BY_VERSION ON REG_RESOURCE_TAG(REG_VERSION, REG_TENANT_ID);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_PROPERTY (
|
||||
REG_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
REG_NAME VARCHAR(100) NOT NULL,
|
||||
REG_VALUE VARCHAR(1000),
|
||||
REG_TENANT_ID INTEGER DEFAULT 0,
|
||||
CONSTRAINT PK_REG_PROPERTY PRIMARY KEY(REG_ID, REG_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_RESOURCE_PROPERTY (
|
||||
REG_PROPERTY_ID INTEGER NOT NULL,
|
||||
REG_VERSION INTEGER,
|
||||
REG_PATH_ID INTEGER,
|
||||
REG_RESOURCE_NAME VARCHAR(256),
|
||||
REG_TENANT_ID INTEGER DEFAULT 0
|
||||
);
|
||||
|
||||
ALTER TABLE REG_RESOURCE_PROPERTY ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_PROPERTY_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID);
|
||||
ALTER TABLE REG_RESOURCE_PROPERTY ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_PROPERTY_FK_BY_TAG_ID FOREIGN KEY (REG_PROPERTY_ID, REG_TENANT_ID) REFERENCES REG_PROPERTY (REG_ID, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_PROPERTY_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_RESOURCE_PROPERTY(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_RESOURCE_PROPERTY_IND_BY_VERSION ON REG_RESOURCE_PROPERTY(REG_VERSION, REG_TENANT_ID);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_ASSOCIATION (
|
||||
REG_ASSOCIATION_ID INTEGER AUTO_INCREMENT,
|
||||
REG_SOURCEPATH VARCHAR (2000) NOT NULL,
|
||||
REG_TARGETPATH VARCHAR (2000) NOT NULL,
|
||||
REG_ASSOCIATION_TYPE VARCHAR (2000) NOT NULL,
|
||||
REG_TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (REG_ASSOCIATION_ID, REG_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS REG_SNAPSHOT (
|
||||
REG_SNAPSHOT_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
REG_PATH_ID INTEGER NOT NULL,
|
||||
REG_RESOURCE_NAME VARCHAR (256),
|
||||
REG_RESOURCE_VIDS LONGBLOB NOT NULL,
|
||||
REG_TENANT_ID INTEGER DEFAULT 0,
|
||||
CONSTRAINT PK_REG_SNAPSHOT PRIMARY KEY(REG_SNAPSHOT_ID, REG_TENANT_ID)
|
||||
);
|
||||
|
||||
ALTER TABLE REG_SNAPSHOT ADD CONSTRAINT IF NOT EXISTS REG_SNAPSHOT_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID);
|
||||
CREATE INDEX IF NOT EXISTS REG_SNAPSHOT_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_SNAPSHOT(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID);
|
||||
|
||||
-- ################################
|
||||
-- USER MANAGER TABLES
|
||||
-- ################################
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_TENANT (
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_DOMAIN_NAME VARCHAR(255) NOT NULL,
|
||||
UM_EMAIL VARCHAR(255),
|
||||
UM_ACTIVE BOOLEAN DEFAULT FALSE,
|
||||
UM_CREATED_DATE TIMESTAMP NOT NULL,
|
||||
UM_USER_CONFIG LONGBLOB NOT NULL,
|
||||
PRIMARY KEY (UM_ID),
|
||||
UNIQUE(UM_DOMAIN_NAME));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_DOMAIN(
|
||||
UM_DOMAIN_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_DOMAIN_NAME VARCHAR(255),
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (UM_DOMAIN_ID, UM_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS INDEX_UM_TENANT_UM_DOMAIN_NAME ON UM_TENANT (UM_DOMAIN_NAME);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_USER (
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_USER_NAME VARCHAR(255) NOT NULL,
|
||||
UM_USER_PASSWORD VARCHAR(255) NOT NULL,
|
||||
UM_SALT_VALUE VARCHAR(31),
|
||||
UM_REQUIRE_CHANGE BOOLEAN DEFAULT FALSE,
|
||||
UM_CHANGED_TIME TIMESTAMP NOT NULL,
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID),
|
||||
UNIQUE(UM_USER_NAME, UM_TENANT_ID));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_SYSTEM_USER (
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_USER_NAME VARCHAR(255) NOT NULL,
|
||||
UM_USER_PASSWORD VARCHAR(255) NOT NULL,
|
||||
UM_SALT_VALUE VARCHAR(31),
|
||||
UM_REQUIRE_CHANGE BOOLEAN DEFAULT FALSE,
|
||||
UM_CHANGED_TIME TIMESTAMP NOT NULL,
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID),
|
||||
UNIQUE(UM_USER_NAME, UM_TENANT_ID));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_USER_ATTRIBUTE (
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_ATTR_NAME VARCHAR(255) NOT NULL,
|
||||
UM_ATTR_VALUE VARCHAR(1024),
|
||||
UM_PROFILE_ID VARCHAR(255),
|
||||
UM_USER_ID INTEGER,
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID),
|
||||
FOREIGN KEY (UM_USER_ID, UM_TENANT_ID) REFERENCES UM_USER(UM_ID, UM_TENANT_ID));
|
||||
|
||||
CREATE INDEX IF NOT EXISTS UM_USER_ID_INDEX ON UM_USER_ATTRIBUTE(UM_USER_ID);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_ROLE (
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_ROLE_NAME VARCHAR(255) NOT NULL,
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
UM_SHARED_ROLE BOOLEAN DEFAULT FALSE,
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID),
|
||||
UNIQUE(UM_ROLE_NAME, UM_TENANT_ID));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_MODULE(
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_MODULE_NAME VARCHAR(100),
|
||||
UNIQUE(UM_MODULE_NAME),
|
||||
PRIMARY KEY(UM_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_MODULE_ACTIONS(
|
||||
UM_ACTION VARCHAR(255) NOT NULL,
|
||||
UM_MODULE_ID INTEGER NOT NULL,
|
||||
PRIMARY KEY(UM_ACTION, UM_MODULE_ID),
|
||||
FOREIGN KEY (UM_MODULE_ID) REFERENCES UM_MODULE(UM_ID) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_PERMISSION (
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_RESOURCE_ID VARCHAR(255) NOT NULL,
|
||||
UM_ACTION VARCHAR(255) NOT NULL,
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
UM_MODULE_ID INTEGER DEFAULT 0,
|
||||
UNIQUE(UM_RESOURCE_ID,UM_ACTION, UM_TENANT_ID),
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID));
|
||||
|
||||
CREATE INDEX IF NOT EXISTS INDEX_UM_PERMISSION_UM_RESOURCE_ID_UM_ACTION ON UM_PERMISSION (UM_RESOURCE_ID, UM_ACTION, UM_TENANT_ID);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_ROLE_PERMISSION (
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_PERMISSION_ID INTEGER NOT NULL,
|
||||
UM_ROLE_NAME VARCHAR(255) NOT NULL,
|
||||
UM_IS_ALLOWED SMALLINT NOT NULL,
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
UM_DOMAIN_ID INTEGER,
|
||||
FOREIGN KEY (UM_PERMISSION_ID, UM_TENANT_ID) REFERENCES UM_PERMISSION(UM_ID, UM_TENANT_ID) ON DELETE CASCADE,
|
||||
FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID, UM_TENANT_ID) ON DELETE CASCADE,
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_USER_PERMISSION (
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_PERMISSION_ID INTEGER NOT NULL,
|
||||
UM_USER_NAME VARCHAR(255) NOT NULL,
|
||||
UM_IS_ALLOWED SMALLINT NOT NULL,
|
||||
UNIQUE (UM_PERMISSION_ID, UM_USER_NAME, UM_TENANT_ID),
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (UM_PERMISSION_ID, UM_TENANT_ID) REFERENCES UM_PERMISSION(UM_ID, UM_TENANT_ID) ON DELETE CASCADE,
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_USER_ROLE (
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_ROLE_ID INTEGER NOT NULL,
|
||||
UM_USER_ID INTEGER NOT NULL,
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
UNIQUE (UM_USER_ID, UM_ROLE_ID, UM_TENANT_ID),
|
||||
FOREIGN KEY (UM_ROLE_ID, UM_TENANT_ID) REFERENCES UM_ROLE(UM_ID, UM_TENANT_ID),
|
||||
FOREIGN KEY (UM_USER_ID, UM_TENANT_ID) REFERENCES UM_USER(UM_ID, UM_TENANT_ID),
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID));
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_SHARED_USER_ROLE(
|
||||
UM_ROLE_ID INTEGER NOT NULL,
|
||||
UM_USER_ID INTEGER NOT NULL,
|
||||
UM_USER_TENANT_ID INTEGER NOT NULL,
|
||||
UM_ROLE_TENANT_ID INTEGER NOT NULL,
|
||||
UNIQUE(UM_USER_ID,UM_ROLE_ID,UM_USER_TENANT_ID, UM_ROLE_TENANT_ID),
|
||||
FOREIGN KEY(UM_ROLE_ID,UM_ROLE_TENANT_ID) REFERENCES UM_ROLE(UM_ID,UM_TENANT_ID) ON DELETE CASCADE ,
|
||||
FOREIGN KEY(UM_USER_ID,UM_USER_TENANT_ID) REFERENCES UM_USER(UM_ID,UM_TENANT_ID) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_ACCOUNT_MAPPING(
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_USER_NAME VARCHAR(255) NOT NULL,
|
||||
UM_TENANT_ID INTEGER NOT NULL,
|
||||
UM_USER_STORE_DOMAIN VARCHAR(100),
|
||||
UM_ACC_LINK_ID INTEGER NOT NULL,
|
||||
UNIQUE(UM_USER_NAME, UM_TENANT_ID, UM_USER_STORE_DOMAIN, UM_ACC_LINK_ID),
|
||||
FOREIGN KEY (UM_TENANT_ID) REFERENCES UM_TENANT(UM_ID) ON DELETE CASCADE,
|
||||
PRIMARY KEY (UM_ID)
|
||||
);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_DIALECT(
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_DIALECT_URI VARCHAR(255) NOT NULL,
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
UNIQUE(UM_DIALECT_URI, UM_TENANT_ID),
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID)
|
||||
);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_CLAIM(
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_DIALECT_ID INTEGER NOT NULL,
|
||||
UM_CLAIM_URI VARCHAR(255) NOT NULL,
|
||||
UM_DISPLAY_TAG VARCHAR(255),
|
||||
UM_DESCRIPTION VARCHAR(255),
|
||||
UM_MAPPED_ATTRIBUTE_DOMAIN VARCHAR(255),
|
||||
UM_MAPPED_ATTRIBUTE VARCHAR(255),
|
||||
UM_REG_EX VARCHAR(255),
|
||||
UM_SUPPORTED SMALLINT,
|
||||
UM_REQUIRED SMALLINT,
|
||||
UM_DISPLAY_ORDER INTEGER,
|
||||
UM_CHECKED_ATTRIBUTE SMALLINT,
|
||||
UM_READ_ONLY SMALLINT,
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
UNIQUE(UM_DIALECT_ID, UM_CLAIM_URI,UM_MAPPED_ATTRIBUTE_DOMAIN, UM_TENANT_ID),
|
||||
FOREIGN KEY(UM_DIALECT_ID, UM_TENANT_ID) REFERENCES UM_DIALECT(UM_ID, UM_TENANT_ID),
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_PROFILE_CONFIG(
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_DIALECT_ID INTEGER,
|
||||
UM_PROFILE_NAME VARCHAR(255),
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
FOREIGN KEY(UM_DIALECT_ID, UM_TENANT_ID) REFERENCES UM_DIALECT(UM_ID, UM_TENANT_ID),
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID)
|
||||
);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_HYBRID_ROLE(
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_ROLE_NAME VARCHAR(255),
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_HYBRID_USER_ROLE(
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_USER_NAME VARCHAR(255),
|
||||
UM_ROLE_ID INTEGER NOT NULL,
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
UM_DOMAIN_ID INTEGER,
|
||||
UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID,UM_DOMAIN_ID),
|
||||
FOREIGN KEY (UM_ROLE_ID, UM_TENANT_ID) REFERENCES UM_HYBRID_ROLE(UM_ID, UM_TENANT_ID) ON DELETE CASCADE,
|
||||
FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID, UM_TENANT_ID) ON DELETE CASCADE,
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_HYBRID_REMEMBER_ME (
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_USER_NAME VARCHAR(255) NOT NULL,
|
||||
UM_COOKIE_VALUE VARCHAR(1024),
|
||||
UM_CREATED_TIME TIMESTAMP,
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_SYSTEM_ROLE(
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_ROLE_NAME VARCHAR(255),
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS UM_SYSTEM_USER_ROLE(
|
||||
UM_ID INTEGER NOT NULL AUTO_INCREMENT,
|
||||
UM_USER_NAME VARCHAR(255),
|
||||
UM_ROLE_ID INTEGER NOT NULL,
|
||||
UM_TENANT_ID INTEGER DEFAULT 0,
|
||||
UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID),
|
||||
FOREIGN KEY (UM_ROLE_ID, UM_TENANT_ID) REFERENCES UM_SYSTEM_ROLE(UM_ID, UM_TENANT_ID),
|
||||
PRIMARY KEY (UM_ID, UM_TENANT_ID)
|
||||
);
|
||||
@ -0,0 +1,96 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
|
||||
<DeviceMgtConfiguration>
|
||||
<ManagementRepository>
|
||||
<DataSourceConfiguration>
|
||||
<JndiLookupDefinition>
|
||||
<Name>jdbc/DM_DS</Name>
|
||||
</JndiLookupDefinition>
|
||||
</DataSourceConfiguration>
|
||||
</ManagementRepository>
|
||||
<PushNotificationConfiguration>
|
||||
<SchedulerBatchSize>1000</SchedulerBatchSize>
|
||||
<SchedulerBatchDelayMills>60000</SchedulerBatchDelayMills>
|
||||
<SchedulerTaskInitialDelay>60000</SchedulerTaskInitialDelay>
|
||||
<SchedulerTaskEnabled>true</SchedulerTaskEnabled>
|
||||
<PushNotificationProviders>
|
||||
<Provider>org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.FCMBasedPushNotificationProvider</Provider>
|
||||
<!--<Provider>org.wso2.carbon.device.mgt.mobile.impl.ios.apns.APNSBasedPushNotificationProvider</Provider>-->
|
||||
<Provider>org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.MQTTBasedPushNotificationProvider</Provider>
|
||||
<Provider>org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.HTTPBasedPushNotificationProvider</Provider>
|
||||
<Provider>org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.XMPPBasedPushNotificationProvider</Provider>
|
||||
</PushNotificationProviders>
|
||||
</PushNotificationConfiguration>
|
||||
<PullNotificationConfiguration>
|
||||
<Enabled>false</Enabled>
|
||||
</PullNotificationConfiguration>
|
||||
<IdentityConfiguration>
|
||||
<ServerUrl>https://localhost:9443</ServerUrl>
|
||||
<AdminUsername>admin</AdminUsername>
|
||||
<AdminPassword>admin</AdminPassword>
|
||||
</IdentityConfiguration>
|
||||
<PolicyConfiguration>
|
||||
<MonitoringClass>org.wso2.carbon.policy.mgt</MonitoringClass>
|
||||
<MonitoringEnable>true</MonitoringEnable>
|
||||
<MonitoringFrequency>60000</MonitoringFrequency>
|
||||
<MaxRetries>5</MaxRetries>
|
||||
<MinRetriesToMarkUnreachable>8</MinRetriesToMarkUnreachable>
|
||||
<MinRetriesToMarkInactive>20</MinRetriesToMarkInactive>
|
||||
<!--Set the policy evaluation point name-->
|
||||
<!--Simple -> Simple policy evaluation point-->
|
||||
<!--Merged -> Merged policy evaluation point -->
|
||||
<PolicyEvaluationPoint>Simple</PolicyEvaluationPoint>
|
||||
</PolicyConfiguration>
|
||||
<!-- Default Page size configuration for paginated DM APIs-->
|
||||
<PaginationConfiguration>
|
||||
<DeviceListPageSize>20</DeviceListPageSize>
|
||||
<GroupListPageSize>20</GroupListPageSize>
|
||||
<NotificationListPageSize>20</NotificationListPageSize>
|
||||
<ActivityListPageSize>20</ActivityListPageSize>
|
||||
<OperationListPageSize>20</OperationListPageSize>
|
||||
<TopicListPageSize>20</TopicListPageSize>
|
||||
</PaginationConfiguration>
|
||||
<!--This specifies whether to enable the DeviceStatus Task in this node. In clustered setup only master node
|
||||
should have to run this task.-->
|
||||
<DeviceStatusTaskConfig>
|
||||
<Enable>true</Enable>
|
||||
</DeviceStatusTaskConfig>
|
||||
<!--This controls the in-memory device cache which is local to this node. Setting it enable will activate the
|
||||
device caching for upto configured expiry-time in seconds. In clustered setup all worker nodes can enable the
|
||||
device-cache to improve performance. -->
|
||||
<DeviceCacheConfiguration>
|
||||
<Enable>false</Enable>
|
||||
<ExpiryTime>600</ExpiryTime>
|
||||
<!--This configuration specifies the number of cache entries in device cache. default capacity is 10000 entries.
|
||||
This can be configured to higher number if cache eviction happens due to large number of devices in the
|
||||
server environment-->
|
||||
<Capacity>10000</Capacity>
|
||||
</DeviceCacheConfiguration>
|
||||
<CertificateCacheConfiguration>
|
||||
<Enable>false</Enable>
|
||||
<ExpiryTime>86400</ExpiryTime>
|
||||
</CertificateCacheConfiguration>
|
||||
<GeoLocationConfiguration>
|
||||
<isEnabled>false</isEnabled>
|
||||
<PublishLocationOperationResponse>false</PublishLocationOperationResponse>
|
||||
</GeoLocationConfiguration>
|
||||
<DefaultGroupsConfiguration>BYOD,COPE</DefaultGroupsConfiguration>
|
||||
</DeviceMgtConfiguration>
|
||||
|
||||
@ -0,0 +1,51 @@
|
||||
<tasks-configuration xmlns:svns="http://org.wso2.securevault/configuration">
|
||||
|
||||
<!--
|
||||
The currently running server mode; possible values are:-
|
||||
STANDALONE, CLUSTERED, REMOTE, AUTO.
|
||||
In AUTO mode, the server startup checks whether clustering is enabled in the system,
|
||||
if so, CLUSTERED mode will be used, or else, the the server mode will be STANDALONE.
|
||||
-->
|
||||
<taskServerMode>STANDALONE</taskServerMode>
|
||||
|
||||
<!--
|
||||
To be used in CLUSTERED mode to notify how many servers are there in
|
||||
the task server cluster, the servers wait till this amount of servers
|
||||
are activated before the tasks are scheduled -->
|
||||
<taskServerCount>2</taskServerCount>
|
||||
|
||||
<!-- The default location resolver configuration -->
|
||||
<defaultLocationResolver>
|
||||
<locationResolverClass>org.wso2.carbon.ntask.core.impl.RoundRobinTaskLocationResolver</locationResolverClass>
|
||||
</defaultLocationResolver>
|
||||
|
||||
<!--
|
||||
if task-type-pattern matches and task-name-pattern matches, check existing addresses of address-pattern,
|
||||
and if addresses exist, select address in round-robin fashion, if not move onto next rule in sequence.
|
||||
<property name="rule-[order]">[task-type-pattern],[task-name-pattern],[address-pattern]</property>
|
||||
-->
|
||||
<!--defaultLocationResolver>
|
||||
<locationResolverClass>org.wso2.carbon.ntask.core.impl.RuleBasedLocationResolver</locationResolverClass>
|
||||
<properties>
|
||||
<property name="rule-1">HIVE_TASK,.*,192.168.2.*</property>
|
||||
<property name="rule-5">.*,.*,.*</property>
|
||||
</properties>
|
||||
</defaultLocationResolver-->
|
||||
|
||||
<!-- The address to which the remote task server should dispatch the trigger messages to,
|
||||
usually this would be an endpoint to a load balancer -->
|
||||
<taskClientDispatchAddress>https://localhost:9448</taskClientDispatchAddress>
|
||||
|
||||
<!-- The address of the remote task server -->
|
||||
<remoteServerAddress>https://localhost:9443</remoteServerAddress>
|
||||
|
||||
<!-- The username to authenticate to the remote task server -->
|
||||
<remoteServerUsername>admin</remoteServerUsername>
|
||||
|
||||
<!-- The password to authenticate to the remote task server -->
|
||||
<remoteServerPassword>admin</remoteServerPassword>
|
||||
|
||||
<!-- Below contain a sample to be used when using with secure vault -->
|
||||
<!--remoteServerPassword svns:secretAlias="remote.task.server.password"></remoteServerPassword-->
|
||||
|
||||
</tasks-configuration>
|
||||
@ -28,7 +28,13 @@
|
||||
<registryRoot>/</registryRoot>
|
||||
|
||||
<dbConfig name="wso2registry">
|
||||
<dataSource>jdbc/WSO2CarbonDB</dataSource>
|
||||
<url>jdbc:h2:./target/databasetest/CARBON_TEST</url>
|
||||
<!--userName>sa</userName>
|
||||
<password>sa</password-->
|
||||
<driverName>org.h2.Driver</driverName>
|
||||
<maxActive>80</maxActive>
|
||||
<maxWait>60000</maxWait>
|
||||
<minIdle>5</minIdle>
|
||||
</dbConfig>
|
||||
|
||||
<!--<handler class="org.wso2.carbon.registry.extensions.handlers.SynapseRepositoryHandler">
|
||||
|
||||
@ -89,7 +89,8 @@
|
||||
<Property name="WriteGroups">true</Property>
|
||||
<Property name="UserNameUniqueAcrossTenants">false</Property>
|
||||
<Property name="PasswordJavaRegEx">^[\S]{5,30}$</Property>
|
||||
<Property name="PasswordJavaRegExViolationErrorMsg">Password length should be between 5 to 30 characters</Property>
|
||||
<Property name="PasswordJavaRegExViolationErrorMsg">Password length should be between 5 to 30 characters
|
||||
</Property>
|
||||
<Property name="PasswordJavaScriptRegEx">^[\S]{5,30}$</Property>
|
||||
<Property name="UsernameJavaRegEx">[a-zA-Z0-9._-|//]{3,30}$</Property>
|
||||
<Property name="UsernameJavaScriptRegEx">^[\S]{3,30}$</Property>
|
||||
|
||||
@ -0,0 +1,96 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
|
||||
<DeviceMgtConfiguration>
|
||||
<ManagementRepository>
|
||||
<DataSourceConfiguration>
|
||||
<JndiLookupDefinition>
|
||||
<Name>jdbc/DM_DS</Name>
|
||||
</JndiLookupDefinition>
|
||||
</DataSourceConfiguration>
|
||||
</ManagementRepository>
|
||||
<PushNotificationConfiguration>
|
||||
<SchedulerBatchSize>2</SchedulerBatchSize>
|
||||
<SchedulerBatchDelayMills>2000</SchedulerBatchDelayMills>
|
||||
<SchedulerTaskInitialDelay>2000</SchedulerTaskInitialDelay>
|
||||
<SchedulerTaskEnabled>true</SchedulerTaskEnabled>
|
||||
<PushNotificationProviders>
|
||||
<Provider>org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.FCMBasedPushNotificationProvider</Provider>
|
||||
<!--<Provider>org.wso2.carbon.device.mgt.mobile.impl.ios.apns.APNSBasedPushNotificationProvider</Provider>-->
|
||||
<Provider>org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.MQTTBasedPushNotificationProvider</Provider>
|
||||
<Provider>org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.HTTPBasedPushNotificationProvider</Provider>
|
||||
<Provider>org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.XMPPBasedPushNotificationProvider</Provider>
|
||||
</PushNotificationProviders>
|
||||
</PushNotificationConfiguration>
|
||||
<PullNotificationConfiguration>
|
||||
<Enabled>false</Enabled>
|
||||
</PullNotificationConfiguration>
|
||||
<IdentityConfiguration>
|
||||
<ServerUrl>https://localhost:9443</ServerUrl>
|
||||
<AdminUsername>admin</AdminUsername>
|
||||
<AdminPassword>admin</AdminPassword>
|
||||
</IdentityConfiguration>
|
||||
<PolicyConfiguration>
|
||||
<MonitoringClass>org.wso2.carbon.policy.mgt</MonitoringClass>
|
||||
<MonitoringEnable>true</MonitoringEnable>
|
||||
<MonitoringFrequency>60000</MonitoringFrequency>
|
||||
<MaxRetries>5</MaxRetries>
|
||||
<MinRetriesToMarkUnreachable>8</MinRetriesToMarkUnreachable>
|
||||
<MinRetriesToMarkInactive>20</MinRetriesToMarkInactive>
|
||||
<!--Set the policy evaluation point name-->
|
||||
<!--Simple -> Simple policy evaluation point-->
|
||||
<!--Merged -> Merged policy evaluation point -->
|
||||
<PolicyEvaluationPoint>Simple</PolicyEvaluationPoint>
|
||||
</PolicyConfiguration>
|
||||
<!-- Default Page size configuration for paginated DM APIs-->
|
||||
<PaginationConfiguration>
|
||||
<DeviceListPageSize>20</DeviceListPageSize>
|
||||
<GroupListPageSize>20</GroupListPageSize>
|
||||
<NotificationListPageSize>20</NotificationListPageSize>
|
||||
<ActivityListPageSize>20</ActivityListPageSize>
|
||||
<OperationListPageSize>20</OperationListPageSize>
|
||||
<TopicListPageSize>20</TopicListPageSize>
|
||||
</PaginationConfiguration>
|
||||
<!--This specifies whether to enable the DeviceStatus Task in this node. In clustered setup only master node
|
||||
should have to run this task.-->
|
||||
<DeviceStatusTaskConfig>
|
||||
<Enable>true</Enable>
|
||||
</DeviceStatusTaskConfig>
|
||||
<!--This controls the in-memory device cache which is local to this node. Setting it enable will activate the
|
||||
device caching for upto configured expiry-time in seconds. In clustered setup all worker nodes can enable the
|
||||
device-cache to improve performance. -->
|
||||
<DeviceCacheConfiguration>
|
||||
<Enable>false</Enable>
|
||||
<ExpiryTime>600</ExpiryTime>
|
||||
<!--This configuration specifies the number of cache entries in device cache. default capacity is 10000 entries.
|
||||
This can be configured to higher number if cache eviction happens due to large number of devices in the
|
||||
server environment-->
|
||||
<Capacity>10000</Capacity>
|
||||
</DeviceCacheConfiguration>
|
||||
<CertificateCacheConfiguration>
|
||||
<Enable>false</Enable>
|
||||
<ExpiryTime>86400</ExpiryTime>
|
||||
</CertificateCacheConfiguration>
|
||||
<GeoLocationConfiguration>
|
||||
<isEnabled>false</isEnabled>
|
||||
<PublishLocationOperationResponse>false</PublishLocationOperationResponse>
|
||||
</GeoLocationConfiguration>
|
||||
<DefaultGroupsConfiguration>BYOD,COPE</DefaultGroupsConfiguration>
|
||||
</DeviceMgtConfiguration>
|
||||
|
||||
@ -24,15 +24,7 @@ CREATE TABLE IF NOT EXISTS DM_ROLE_GROUP_MAP (
|
||||
TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (ID),
|
||||
CONSTRAINT fk_DM_ROLE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
|
||||
REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
|
||||
ID INTEGER auto_increment NOT NULL,
|
||||
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
|
||||
CERTIFICATE BLOB DEFAULT NULL,
|
||||
TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (ID)
|
||||
REFERENCES DM_GROUP (ID) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_DEVICE (
|
||||
@ -45,7 +37,17 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE (
|
||||
TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (ID),
|
||||
CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID)
|
||||
REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
|
||||
REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
|
||||
CONSTRAINT uk_DM_DEVICE UNIQUE (NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_PROPERTIES (
|
||||
DEVICE_TYPE_NAME VARCHAR(300) NOT NULL,
|
||||
DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL,
|
||||
PROPERTY_NAME VARCHAR(100) DEFAULT 0,
|
||||
PROPERTY_VALUE VARCHAR(100) DEFAULT NULL,
|
||||
TENANT_ID VARCHAR(100),
|
||||
PRIMARY KEY (DEVICE_TYPE_NAME, DEVICE_IDENTIFICATION, PROPERTY_NAME, TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP (
|
||||
@ -55,9 +57,9 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP (
|
||||
TENANT_ID INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (ID),
|
||||
CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID)
|
||||
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
|
||||
REFERENCES DM_DEVICE (ID) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
|
||||
REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
|
||||
REFERENCES DM_GROUP (ID) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_OPERATION (
|
||||
@ -72,6 +74,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION (
|
||||
CREATE TABLE IF NOT EXISTS DM_CONFIG_OPERATION (
|
||||
OPERATION_ID INTEGER NOT NULL,
|
||||
OPERATION_CONFIG BLOB DEFAULT NULL,
|
||||
ENABLED BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
PRIMARY KEY (OPERATION_ID),
|
||||
CONSTRAINT fk_dm_operation_config FOREIGN KEY (OPERATION_ID) REFERENCES
|
||||
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
|
||||
@ -114,7 +117,8 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
|
||||
TENANT_ID INT NOT NULL,
|
||||
PRIMARY KEY (ID),
|
||||
CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES
|
||||
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
|
||||
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
|
||||
CONSTRAINT uk_dm_device_enrolment UNIQUE (DEVICE_ID, OWNER, OWNERSHIP, TENANT_ID)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING (
|
||||
@ -122,6 +126,9 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING (
|
||||
ENROLMENT_ID INTEGER NOT NULL,
|
||||
OPERATION_ID INTEGER NOT NULL,
|
||||
STATUS VARCHAR(50) NULL,
|
||||
PUSH_NOTIFICATION_STATUS VARCHAR(50) NULL,
|
||||
CREATED_TIMESTAMP INT NOT NULL,
|
||||
UPDATED_TIMESTAMP INT NOT NULL,
|
||||
PRIMARY KEY (ID),
|
||||
CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES
|
||||
DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
|
||||
@ -133,12 +140,16 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE (
|
||||
ID INTEGER AUTO_INCREMENT NOT NULL,
|
||||
ENROLMENT_ID INTEGER NOT NULL,
|
||||
OPERATION_ID INTEGER NOT NULL,
|
||||
EN_OP_MAP_ID INTEGER NOT NULL,
|
||||
OPERATION_RESPONSE LONGBLOB DEFAULT NULL,
|
||||
RECEIVED_TIMESTAMP TIMESTAMP NULL,
|
||||
PRIMARY KEY (ID),
|
||||
CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES
|
||||
DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
|
||||
CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES
|
||||
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
|
||||
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
|
||||
CONSTRAINT fk_dm_en_op_map_response FOREIGN KEY (EN_OP_MAP_ID) REFERENCES
|
||||
DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
-- POLICY RELATED TABLES --
|
||||
@ -147,21 +158,12 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE (
|
||||
ID INT NOT NULL AUTO_INCREMENT ,
|
||||
PROFILE_NAME VARCHAR(45) NOT NULL ,
|
||||
TENANT_ID INT NOT NULL ,
|
||||
DEVICE_TYPE_ID INT NOT NULL ,
|
||||
DEVICE_TYPE VARCHAR(300) NOT NULL ,
|
||||
CREATED_TIME DATETIME NOT NULL ,
|
||||
UPDATED_TIME DATETIME NOT NULL ,
|
||||
PRIMARY KEY (ID) ,
|
||||
CONSTRAINT DM_PROFILE_DEVICE_TYPE
|
||||
FOREIGN KEY (DEVICE_TYPE_ID )
|
||||
REFERENCES DM_DEVICE_TYPE (ID )
|
||||
ON DELETE NO ACTION
|
||||
ON UPDATE NO ACTION
|
||||
PRIMARY KEY (ID)
|
||||
);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_POLICY (
|
||||
ID INT(11) NOT NULL AUTO_INCREMENT ,
|
||||
NAME VARCHAR(45) DEFAULT NULL ,
|
||||
@ -181,9 +183,6 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
|
||||
ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY (
|
||||
ID INT(11) NOT NULL AUTO_INCREMENT ,
|
||||
DEVICE_ID INT(11) NOT NULL ,
|
||||
@ -203,35 +202,23 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY (
|
||||
ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY (
|
||||
ID INT(11) NOT NULL ,
|
||||
DEVICE_TYPE_ID INT(11) NOT NULL ,
|
||||
DEVICE_TYPE VARCHAR(300) NOT NULL ,
|
||||
POLICY_ID INT(11) NOT NULL ,
|
||||
PRIMARY KEY (ID) ,
|
||||
CONSTRAINT FK_DEVICE_TYPE_POLICY
|
||||
FOREIGN KEY (POLICY_ID )
|
||||
REFERENCES DM_POLICY (ID )
|
||||
ON DELETE NO ACTION
|
||||
ON UPDATE NO ACTION,
|
||||
CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE
|
||||
FOREIGN KEY (DEVICE_TYPE_ID )
|
||||
REFERENCES DM_DEVICE_TYPE (ID )
|
||||
ON DELETE NO ACTION
|
||||
ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES (
|
||||
ID INT(11) NOT NULL AUTO_INCREMENT,
|
||||
PROFILE_ID INT(11) NOT NULL,
|
||||
FEATURE_CODE VARCHAR(100) NOT NULL,
|
||||
DEVICE_TYPE_ID INT NOT NULL,
|
||||
DEVICE_TYPE VARCHAR(300) NOT NULL,
|
||||
TENANT_ID INT(11) NOT NULL ,
|
||||
CONTENT BLOB NULL DEFAULT NULL,
|
||||
PRIMARY KEY (ID),
|
||||
@ -242,9 +229,6 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES (
|
||||
ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY (
|
||||
ID INT(11) NOT NULL AUTO_INCREMENT ,
|
||||
ROLE_NAME VARCHAR(45) NOT NULL ,
|
||||
@ -257,9 +241,6 @@ CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY (
|
||||
ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_USER_POLICY (
|
||||
ID INT NOT NULL AUTO_INCREMENT ,
|
||||
POLICY_ID INT NOT NULL ,
|
||||
@ -272,7 +253,6 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY (
|
||||
ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED (
|
||||
ID INT NOT NULL AUTO_INCREMENT ,
|
||||
DEVICE_ID INT NOT NULL ,
|
||||
@ -292,8 +272,6 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY (
|
||||
ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_CRITERIA (
|
||||
ID INT NOT NULL AUTO_INCREMENT,
|
||||
TENANT_ID INT NOT NULL,
|
||||
@ -301,8 +279,6 @@ CREATE TABLE IF NOT EXISTS DM_CRITERIA (
|
||||
PRIMARY KEY (ID)
|
||||
);
|
||||
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA (
|
||||
ID INT NOT NULL AUTO_INCREMENT,
|
||||
CRITERIA_ID INT NOT NULL,
|
||||
@ -348,16 +324,14 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS (
|
||||
PRIMARY KEY (ID)
|
||||
);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT (
|
||||
ID INT NOT NULL AUTO_INCREMENT,
|
||||
POLICY_ID INT NOT NULL,
|
||||
DEVICE_TYPE_ID INT NOT NULL,
|
||||
DEVICE_TYPE VARCHAR(300) NOT NULL ,
|
||||
TENANT_ID INT(11) NOT NULL,
|
||||
PRIMARY KEY (ID)
|
||||
);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES (
|
||||
ID INT NOT NULL AUTO_INCREMENT,
|
||||
COMPLIANCE_STATUS_ID INT NOT NULL,
|
||||
@ -372,20 +346,6 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES (
|
||||
ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
|
||||
ID INTEGER AUTO_INCREMENT NOT NULL,
|
||||
DEVICE_ID INTEGER NOT NULL,
|
||||
OWNER VARCHAR(50) NOT NULL,
|
||||
OWNERSHIP VARCHAR(45) DEFAULT NULL,
|
||||
STATUS VARCHAR(50) NULL,
|
||||
DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL,
|
||||
DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL,
|
||||
TENANT_ID INT NOT NULL,
|
||||
PRIMARY KEY (ID),
|
||||
CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES
|
||||
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_APPLICATION (
|
||||
ID INTEGER AUTO_INCREMENT NOT NULL,
|
||||
NAME VARCHAR(150) NOT NULL,
|
||||
@ -424,7 +384,7 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION (
|
||||
OPERATION_ID INTEGER NOT NULL,
|
||||
TENANT_ID INTEGER NOT NULL,
|
||||
STATUS VARCHAR(10) NULL,
|
||||
DESCRIPTION VARCHAR(100) NULL,
|
||||
DESCRIPTION VARCHAR(1000) NULL,
|
||||
PRIMARY KEY (NOTIFICATION_ID),
|
||||
CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES
|
||||
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
|
||||
@ -433,8 +393,6 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION (
|
||||
);
|
||||
-- NOTIFICATION TABLE END --
|
||||
|
||||
DROP TABLE IF EXISTS DM_DEVICE_INFO;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
|
||||
ID INTEGER AUTO_INCREMENT NOT NULL,
|
||||
DEVICE_ID INT NULL,
|
||||
@ -448,10 +406,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
|
||||
ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
|
||||
|
||||
DROP TABLE IF EXISTS DM_DEVICE_LOCATION;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
|
||||
ID INTEGER AUTO_INCREMENT NOT NULL,
|
||||
DEVICE_ID INT NULL,
|
||||
@ -472,7 +426,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
|
||||
ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
|
||||
ID INT NOT NULL AUTO_INCREMENT,
|
||||
DEVICE_ID INT NOT NULL,
|
||||
@ -485,7 +438,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
|
||||
INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL,
|
||||
EXTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL,
|
||||
EXTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL,
|
||||
CONNECTION_TYPE VARCHAR(10) NULL,
|
||||
CONNECTION_TYPE VARCHAR(50) NULL,
|
||||
SSID VARCHAR(45) NULL,
|
||||
CPU_USAGE DECIMAL(5) NULL,
|
||||
TOTAL_RAM_MEMORY DECIMAL(30,3) NULL,
|
||||
@ -500,9 +453,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
|
||||
ON UPDATE NO ACTION
|
||||
);
|
||||
|
||||
|
||||
-- POLICY AND DEVICE GROUP MAPPING --
|
||||
|
||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY (
|
||||
ID INT NOT NULL AUTO_INCREMENT,
|
||||
DEVICE_GROUP_ID INT NOT NULL,
|
||||
@ -512,20 +463,21 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY (
|
||||
CONSTRAINT FK_DM_DEVICE_GROUP_POLICY
|
||||
FOREIGN KEY (DEVICE_GROUP_ID)
|
||||
REFERENCES DM_GROUP (ID)
|
||||
ON DELETE NO ACTION
|
||||
ON UPDATE NO ACTION,
|
||||
ON DELETE CASCADE
|
||||
ON UPDATE CASCADE ,
|
||||
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
|
||||
FOREIGN KEY (POLICY_ID , DEVICE_GROUP_ID)
|
||||
REFERENCES DM_POLICY (ID , ID)
|
||||
ON DELETE NO ACTION
|
||||
ON UPDATE NO ACTION
|
||||
FOREIGN KEY (POLICY_ID)
|
||||
REFERENCES DM_POLICY (ID)
|
||||
ON DELETE CASCADE
|
||||
ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
-- END OF POLICY AND DEVICE GROUP MAPPING --
|
||||
|
||||
CREATE VIEW DEVICES_VIEW_1 AS
|
||||
-- DASHBOARD RELATED VIEWS --
|
||||
CREATE VIEW POLICY_COMPLIANCE_INFO AS
|
||||
SELECT
|
||||
DEVICE_INFO.DEVICE_ID,
|
||||
DEVICE_INFO.DEVICE_IDENTIFICATION,
|
||||
DEVICE_INFO.PLATFORM,
|
||||
DEVICE_INFO.OWNERSHIP,
|
||||
DEVICE_INFO.CONNECTIVITY_STATUS,
|
||||
@ -535,10 +487,11 @@ DEVICE_INFO.TENANT_ID
|
||||
FROM
|
||||
(SELECT
|
||||
DM_DEVICE.ID AS DEVICE_ID,
|
||||
DM_DEVICE.DEVICE_IDENTIFICATION,
|
||||
DM_DEVICE_TYPE.NAME AS PLATFORM,
|
||||
DM_ENROLMENT.OWNERSHIP AS OWNERSHIP,
|
||||
DM_ENROLMENT.OWNERSHIP,
|
||||
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
|
||||
DM_DEVICE.TENANT_ID AS TENANT_ID
|
||||
DM_DEVICE.TENANT_ID
|
||||
FROM DM_DEVICE, DM_DEVICE_TYPE, DM_ENROLMENT
|
||||
WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) DEVICE_INFO
|
||||
LEFT JOIN
|
||||
@ -546,7 +499,33 @@ LEFT JOIN
|
||||
DEVICE_ID,
|
||||
POLICY_ID,
|
||||
STATUS AS IS_COMPLIANT
|
||||
FROM
|
||||
DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO
|
||||
FROM DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO
|
||||
ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID
|
||||
ORDER BY DEVICE_INFO.DEVICE_ID;
|
||||
|
||||
CREATE VIEW FEATURE_NON_COMPLIANCE_INFO AS
|
||||
SELECT
|
||||
DM_DEVICE.ID AS DEVICE_ID,
|
||||
DM_DEVICE.DEVICE_IDENTIFICATION,
|
||||
DM_DEVICE_DETAIL.DEVICE_MODEL,
|
||||
DM_DEVICE_DETAIL.VENDOR,
|
||||
DM_DEVICE_DETAIL.OS_VERSION,
|
||||
DM_ENROLMENT.OWNERSHIP,
|
||||
DM_ENROLMENT.OWNER,
|
||||
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
|
||||
DM_POLICY_COMPLIANCE_STATUS.POLICY_ID,
|
||||
DM_DEVICE_TYPE.NAME AS PLATFORM,
|
||||
DM_POLICY_COMPLIANCE_FEATURES.FEATURE_CODE,
|
||||
DM_POLICY_COMPLIANCE_FEATURES.STATUS AS IS_COMPLAINT,
|
||||
DM_DEVICE.TENANT_ID
|
||||
FROM
|
||||
DM_POLICY_COMPLIANCE_FEATURES, DM_POLICY_COMPLIANCE_STATUS, DM_ENROLMENT, DM_DEVICE, DM_DEVICE_TYPE, DM_DEVICE_DETAIL
|
||||
WHERE
|
||||
DM_POLICY_COMPLIANCE_FEATURES.COMPLIANCE_STATUS_ID = DM_POLICY_COMPLIANCE_STATUS.ID AND
|
||||
DM_POLICY_COMPLIANCE_STATUS.ENROLMENT_ID = DM_ENROLMENT.ID AND
|
||||
DM_POLICY_COMPLIANCE_STATUS.DEVICE_ID = DM_DEVICE.ID AND
|
||||
DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND
|
||||
DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID
|
||||
ORDER BY TENANT_ID, DEVICE_ID;
|
||||
|
||||
-- END OF DASHBOARD RELATED VIEWS --
|
||||
|
||||
@ -40,6 +40,13 @@
|
||||
<classes>
|
||||
<class name="org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceTest"/>
|
||||
<class name="org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderServiceTest"/>
|
||||
<class name="org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceTest"/>
|
||||
<class name="org.wso2.carbon.device.mgt.core.operation.OperationManagementTests"/>
|
||||
<class name="org.wso2.carbon.device.mgt.core.operation.ScheduledTaskOperationTests"/>
|
||||
<class name="org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceTest" />
|
||||
<class name="org.wso2.carbon.device.mgt.core.notification.mgt.NotificationManagementServiceImplTests"/>
|
||||
<class name="org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerServiceTest"/>
|
||||
<class name="org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceTest"/>
|
||||
</classes>
|
||||
</test>
|
||||
</suite>
|
||||
|
||||
@ -0,0 +1,101 @@
|
||||
<!--
|
||||
~ Copyright (c) 2005-2011, 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.
|
||||
-->
|
||||
<UserManager>
|
||||
<Realm>
|
||||
<Configuration>
|
||||
<AddAdmin>true</AddAdmin>
|
||||
<AdminRole>admin</AdminRole>
|
||||
<AdminUser>
|
||||
<UserName>admin</UserName>
|
||||
<Password>admin</Password>
|
||||
</AdminUser>
|
||||
<EveryOneRoleName>everyone</EveryOneRoleName>
|
||||
<ReadOnly>false</ReadOnly>
|
||||
<MaxUserNameListLength>500</MaxUserNameListLength>
|
||||
<Property name="url">jdbc:h2:target/databasetest/CARBON_TEST</Property>
|
||||
<Property name="driverName">org.h2.Driver</Property>
|
||||
<Property name="maxActive">50</Property>
|
||||
<Property name="maxWait">60000</Property>
|
||||
<Property name="minIdle">5</Property>
|
||||
</Configuration>
|
||||
<UserStoreManager
|
||||
class="org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager">
|
||||
<Property name="PasswordJavaRegEx">[\S]{5,30}$</Property>
|
||||
<Property name="PasswordJavaScriptRegEx">[\\S]{5,30}</Property>
|
||||
<Property name="SelectUserSQL">SELECT * FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?</Property>
|
||||
<!--<Property name="GetRoleListSQL">SELECT UM_ROLE_NAME FROM UM_ROLE WHERE UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="UserFilterSQL">SELECT UM_USER_NAME FROM UM_USER WHERE UM_USER_NAME LIKE ? AND UM_TENANT_ID=? ORDER BY UM_USER_NAME</Property>-->
|
||||
<!--<Property name="UserRoleSQL">SELECT UM_ROLE_NAME FROM UM_USER_ROLE, UM_ROLE, UM_USER WHERE UM_USER.UM_USER_NAME=? AND UM_USER.UM_ID=UM_USER_ROLE.UM_USER_ID AND UM_ROLE.UM_ID=UM_USER_ROLE.UM_ROLE_ID AND UM_USER_ROLE.UM_TENANT_ID=? AND UM_ROLE.UM_TENANT_ID=? AND UM_USER.UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="IsRoleExistingSQL">SELECT UM_ID FROM UM_ROLE WHERE UM_ROLE_NAME=? AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="IsUserExistingSQL">SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="GetUserListOfRoleSQL">SELECT UM_USER_NAME FROM UM_USER_ROLE, UM_ROLE, UM_USER WHERE UM_ROLE.UM_ROLE_NAME=? AND UM_USER.UM_ID=UM_USER_ROLE.UM_USER_ID AND UM_ROLE.UM_ID=UM_USER_ROLE.UM_ROLE_ID AND UM_USER_ROLE.UM_TENANT_ID=? AND UM_ROLE.UM_TENANT_ID=? AND UM_USER.UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="GetUserPropertyForProfileSQL">SELECT UM_ATTR_VALUE FROM UM_USER_ATTRIBUTE, UM_USER WHERE UM_USER.UM_ID = UM_USER_ATTRIBUTE.UM_USER_ID AND UM_USER.UM_USER_NAME=? AND UM_ATTR_NAME=? AND UM_PROFILE_ID=? AND UM_USER_ATTRIBUTE.UM_TENANT_ID=? AND UM_USER.UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="GetUserPropertiesForProfileSQL">SELECT UM_ATTR_NAME, UM_ATTR_VALUE FROM UM_USER_ATTRIBUTE, UM_USER WHERE UM_USER.UM_ID = UM_USER_ATTRIBUTE.UM_USER_ID AND UM_USER.UM_USER_NAME=? AND UM_PROFILE_ID=? AND UM_USER_ATTRIBUTE.UM_TENANT_ID=? AND UM_USER.UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="GetProfileNamesSQL">SELECT DISTINCT UM_PROFILE_ID FROM UM_USER_ATTRIBUTE WHERE UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="GetUserProfileNamesSQL">SELECT DISTINCT UM_PROFILE_ID FROM UM_USER_ATTRIBUTE WHERE UM_USER_ID=(SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?) AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="GetUsersWithDefaultPasswordsSQL">SELECT UM_USER_NAME FROM UM_USER WHERE WHERE UM_USER_NAME=? AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="UserNameUniqueAcrossTenantsSQL">SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=?</Property>-->
|
||||
<!--<Property name="GetUserIDFromUserNameSQL">SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="GetUserNameFromTenantIDSQL">SELECT UM_USER_NAME FROM UM_USER WHERE UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="GetTenantIDFromUserNameSQL">SELECT UM_TENANT_ID FROM UM_USER WHERE UM_USER_NAME=?</Property>-->
|
||||
<Property name="PasswordDigest">SHA-256</Property>
|
||||
<Property name="StoreSaltedPassword">true</Property>
|
||||
<Property name="UserNameUniqueAcrossTenants">false</Property>
|
||||
<Property name="IsEmailUserName">false</Property>
|
||||
<Property name="SuperDomain">wso2.com</Property>
|
||||
<Property name="IsUsersOfRoleListing">true</Property>
|
||||
<Property name="MaxUserNameListLength">100</Property>
|
||||
<!-- writing sqls follow-->
|
||||
<!--<Property name="AddUserSQL">INSERT INTO UM_USER (UM_USER_NAME, UM_USER_PASSWORD, UM_SALT_VALUE, UM_REQUIRE_CHANGE, UM_CHANGED_TIME, UM_TENANT_ID) VALUES (?, ?, ?, ?, ?, ?)</Property>-->
|
||||
<Property name="AddRoleSQL">INSERT INTO UM_ROLE (UM_ROLE_NAME, UM_TENANT_ID) VALUES (?, ?)</Property>
|
||||
<!--<Property name="AddUserToRoleSQL">INSERT INTO UM_USER_ROLE (UM_USER_ID, UM_ROLE_ID, UM_TENANT_ID) VALUES ((SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?),(SELECT UM_ID FROM UM_ROLE WHERE UM_ROLE_NAME=? AND UM_TENANT_ID=?), ?)</Property>-->
|
||||
<!--<Property name="AddUserToRoleSQL-mssql">INSERT INTO UM_USER_ROLE (UM_USER_ID, UM_ROLE_ID, UM_TENANT_ID) SELECT (SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?),(SELECT UM_ID FROM UM_ROLE WHERE UM_ROLE_NAME=? AND UM_TENANT_ID=?),(?)</Property>-->
|
||||
<!--<Property name="RemoveUserFromRoleSQL">DELETE FROM UM_USER_ROLE WHERE UM_USER_ID=(SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?) AND UM_ROLE_ID=(SELECT UM_ID FROM UM_ROLE WHERE UM_ROLE_NAME=? AND UM_TENANT_ID=?) AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="AddRoleToUserSQL">INSERT INTO UM_USER_ROLE (UM_ROLE_ID, UM_USER_ID, UM_TENANT_ID) VALUES ((SELECT UM_ID FROM UM_ROLE WHERE UM_ROLE_NAME=? AND UM_TENANT_ID=?),(SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?), ?)</Property>-->
|
||||
<!--<Property name="AddRoleToUserSQL-mssql">INSERT INTO UM_USER_ROLE (UM_ROLE_ID, UM_USER_ID, UM_TENANT_ID) SELECT (SELECT UM_ID FROM UM_ROLE WHERE UM_ROLE_NAME=? AND UM_TENANT_ID=?),(SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?), (?)</Property>-->
|
||||
<!--<Property name="RemoveRoleFromUserSQL">DELETE FROM UM_USER_ROLE WHERE UM_ROLE_ID=(SELECT UM_ID FROM UM_ROLE WHERE UM_ROLE_NAME=? AND UM_TENANT_ID=?) AND UM_USER_ID=(SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?) AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="DeleteRoleSQL">DELETE FROM UM_ROLE WHERE UM_ROLE_NAME = ? AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="OnDeleteRoleRemoveUserRoleMappingSQL">DELETE FROM UM_USER_ROLE WHERE UM_ROLE_ID=(SELECT UM_ID FROM UM_ROLE WHERE UM_ROLE_NAME=? AND UM_TENANT_ID=?) AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="OnDeleteUserRemoveUserRoleMappingSQL">DELETE FROM UM_USER_ROLE WHERE UM_USER_ID=(SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?) AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="OnDeleteUserRemoveUserAttributeSQL">DELETE FROM UM_USER_ATTRIBUTE WHERE UM_USER_ID=(SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?) AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="DeleteUserSQL">DELETE FROM UM_USER WHERE UM_USER_NAME = ? AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="UpdateUserPasswordSQL">UPDATE UM_USER SET UM_USER_PASSWORD= ?, UM_SALT_VALUE=?, UM_REQUIRE_CHANGE=?, UM_CHANGED_TIME=? WHERE UM_USER_NAME= ? AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="AddUserPropertySQL">INSERT INTO UM_USER_ATTRIBUTE (UM_USER_ID, UM_ATTR_NAME, UM_ATTR_VALUE, UM_PROFILE_ID, UM_TENANT_ID) VALUES ((SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?), ?, ?, ?, ?)</Property>-->
|
||||
<!--<Property name="AddUserPropertySQL-mssql">INSERT INTO UM_USER_ATTRIBUTE (UM_USER_ID, UM_ATTR_NAME, UM_ATTR_VALUE, UM_PROFILE_ID, UM_TENANT_ID) SELECT (SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?), (?), (?), (?), (?)</Property>-->
|
||||
<!--<Property name="UpdateUserPropertySQL">UPDATE UM_USER_ATTRIBUTE SET UM_ATTR_VALUE=? WHERE UM_USER_ID=(SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?) AND UM_ATTR_NAME=? AND UM_PROFILE_ID=? AND UM_TENANT_ID=?</Property>-->
|
||||
<!--<Property name="DeleteUserPropertySQL">DELETE FROM UM_USER_ATTRIBUTE WHERE UM_USER_ID=(SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=?) AND UM_ATTR_NAME=? AND UM_PROFILE_ID=? AND UM_TENANT_ID=?</Property>-->
|
||||
<Property name="TenantManager">org.wso2.carbon.user.core.tenant.JDBCTenantManager</Property>
|
||||
</UserStoreManager>
|
||||
<AuthorizationManager
|
||||
class="org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager">
|
||||
<Property name="AuthorizationCacheEnabled">true</Property>
|
||||
</AuthorizationManager>
|
||||
</Realm>
|
||||
<SystemPermission>
|
||||
<Permission>login</Permission>
|
||||
<Permission>manage-configuration</Permission>
|
||||
<Permission>manage-security</Permission>
|
||||
<Permission>upload-services</Permission>
|
||||
<Permission>manage-services</Permission>
|
||||
<Permission>manage-lc-configuration</Permission>
|
||||
<Permission>manage-mediation</Permission>
|
||||
<Permission>monitor-system</Permission>
|
||||
<Permission>delegate-identity</Permission>
|
||||
</SystemPermission>
|
||||
</UserManager>
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.93-SNAPSHOT</version>
|
||||
<version>3.0.129-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -62,6 +62,66 @@
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-api-mockito</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.extensions.pull.notification</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database.wso2</groupId>
|
||||
<artifactId>h2-database-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-dbcp.wso2</groupId>
|
||||
<artifactId>commons-dbcp</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-pool.wso2</groupId>
|
||||
<artifactId>commons-pool</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.governance</groupId>
|
||||
<artifactId>org.wso2.carbon.governance.registry.extensions</artifactId>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>jaxen</groupId>
|
||||
<artifactId>jaxen</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.registry</groupId>
|
||||
<artifactId>org.wso2.carbon.registry.indexing</artifactId>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@ -117,6 +177,42 @@
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<suiteXmlFiles>
|
||||
<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
|
||||
</suiteXmlFiles>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@ -130,6 +130,17 @@ public class DeviceTypeManager implements DeviceManager {
|
||||
//Check whether device dao definition exist.
|
||||
String tableName = deviceTypeConfiguration.getDeviceDetails().getTableId();
|
||||
if (tableName != null && !tableName.isEmpty()) {
|
||||
DataSource dataSource = deviceTypeConfiguration.getDataSource();
|
||||
if (dataSource == null) {
|
||||
throw new DeviceTypeDeployerPayloadException("Could not find the datasource related with the "
|
||||
+ "table id " + tableName + " for the device type " + deviceType);
|
||||
}
|
||||
TableConfig tableConfig = dataSource.getTableConfig();
|
||||
|
||||
if (tableConfig == null) {
|
||||
throw new DeviceTypeDeployerPayloadException("Could not find the table config with the "
|
||||
+ "table id " + tableName + " for the device type " + deviceType);
|
||||
}
|
||||
List<Table> tables = deviceTypeConfiguration.getDataSource().getTableConfig().getTable();
|
||||
Table deviceDefinitionTable = null;
|
||||
for (Table table : tables) {
|
||||
@ -189,6 +200,9 @@ public class DeviceTypeManager implements DeviceManager {
|
||||
@Override
|
||||
public boolean saveConfiguration(PlatformConfiguration tenantConfiguration)
|
||||
throws DeviceManagementException {
|
||||
if (tenantConfiguration == null) {
|
||||
throw new DeviceManagementException("Platform configuration is null. Cannot save the configuration");
|
||||
}
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Persisting " + deviceType + " configurations in Registry");
|
||||
@ -246,6 +260,9 @@ public class DeviceTypeManager implements DeviceManager {
|
||||
|
||||
@Override
|
||||
public boolean enrollDevice(Device device) throws DeviceManagementException {
|
||||
if (device == null) {
|
||||
throw new DeviceManagementException("Device is null. Cannot enroll the device.");
|
||||
}
|
||||
if (propertiesExist) {
|
||||
boolean status = false;
|
||||
boolean isEnrolled = this.isEnrolled(
|
||||
@ -313,6 +330,9 @@ public class DeviceTypeManager implements DeviceManager {
|
||||
|
||||
@Override
|
||||
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
|
||||
if (deviceId == null) {
|
||||
throw new DeviceManagementException("Cannot check the enrollment status of a null device");
|
||||
}
|
||||
if (propertiesExist) {
|
||||
boolean isEnrolled = false;
|
||||
try {
|
||||
@ -347,6 +367,9 @@ public class DeviceTypeManager implements DeviceManager {
|
||||
|
||||
@Override
|
||||
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
|
||||
if (deviceId == null) {
|
||||
throw new DeviceManagementException("Cannot get the device. DeviceIdentifier is null");
|
||||
}
|
||||
if (propertiesExist) {
|
||||
Device device;
|
||||
try {
|
||||
@ -433,8 +456,11 @@ public class DeviceTypeManager implements DeviceManager {
|
||||
if (propertiesExist) {
|
||||
boolean status;
|
||||
Device existingDevice = this.getDevice(deviceIdentifier);
|
||||
existingDevice.setProperties(device.getProperties());
|
||||
|
||||
if (existingDevice == null) {
|
||||
return false;
|
||||
}
|
||||
existingDevice.setProperties(device.getProperties());
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
|
||||
@ -41,17 +41,26 @@ public class DeviceDAODefinition {
|
||||
|
||||
|
||||
public DeviceDAODefinition(Table table) {
|
||||
if (table == null) {
|
||||
throw new DeviceTypeDeployerPayloadException("Table is null. Cannot create DeviceDAODefinition");
|
||||
}
|
||||
deviceTableName = table.getName();
|
||||
primarykey = table.getPrimaryKey();
|
||||
List<String> attributes = table.getAttributes().getAttribute();
|
||||
|
||||
if (deviceTableName == null || deviceTableName.isEmpty()) {
|
||||
throw new DeviceTypeDeployerPayloadException("Missing deviceTableName");
|
||||
}
|
||||
|
||||
if (primarykey == null || primarykey.isEmpty()) {
|
||||
throw new DeviceTypeDeployerPayloadException("Missing primaryKey ");
|
||||
throw new DeviceTypeDeployerPayloadException("Missing primaryKey for the table " + deviceTableName);
|
||||
}
|
||||
|
||||
if (table.getAttributes() == null) {
|
||||
throw new DeviceTypeDeployerPayloadException("Table " + deviceTableName + " attributes are not specified. "
|
||||
+ "Cannot created DeviceDAODefinition");
|
||||
}
|
||||
|
||||
List<String> attributes = table.getAttributes().getAttribute();
|
||||
if (attributes == null || attributes.size() == 0) {
|
||||
throw new DeviceTypeDeployerPayloadException("Missing Attributes ");
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user