Harshan Liyanage 8 years ago
parent 7e83b53bb4
commit 35d1c9897e

@ -0,0 +1,67 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "DeviceStatusTaskConfig")
public class DeviceStatusTaskConfiguration {
private boolean enabled;
private int frequency;
private int idleTimeToMarkInactive;
private int idleTimeToMarkUnreachable;
@XmlElement(name = "RequireStatusMonitoring", required = true)
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@XmlElement(name = "Frequency", required = true)
public int getFrequency() {
return frequency;
}
public void setFrequency(int frequency) {
this.frequency = frequency;
}
@XmlElement(name = "IdleTimeToMarkInactive", required = true)
public int getIdleTimeToMarkInactive() {
return idleTimeToMarkInactive;
}
public void setIdleTimeToMarkInactive(int idleTimeToMarkInactive) {
this.idleTimeToMarkInactive = idleTimeToMarkInactive;
}
@XmlElement(name = "IdleTimeToMarkUnreachable", required = true)
public int getIdleTimeToMarkUnreachable() {
return idleTimeToMarkUnreachable;
}
public void setIdleTimeToMarkUnreachable(int idleTimeToMarkUnreachable) {
this.idleTimeToMarkUnreachable = idleTimeToMarkUnreachable;
}
}

@ -40,6 +40,7 @@ import java.util.List;
* <element name="DataSource" type="{}DataSource"/> * <element name="DataSource" type="{}DataSource"/>
* <element name="PolicyMonitoring" type="{}PolicyMonitoring"/> * <element name="PolicyMonitoring" type="{}PolicyMonitoring"/>
* <element name="DeviceAuthorizationConfig" type="{}DeviceAuthorizationConfig"/> * <element name="DeviceAuthorizationConfig" type="{}DeviceAuthorizationConfig"/>
* <element name="DeviceStatusTaskConfig" type="{}DeviceStatusTaskConfig"/>
* </sequence> * </sequence>
* <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction> * </restriction>
@ -67,6 +68,8 @@ public class DeviceTypeConfiguration {
protected DataSource dataSource; protected DataSource dataSource;
@XmlElement(name = "TaskConfiguration", required = true) @XmlElement(name = "TaskConfiguration", required = true)
private TaskConfiguration taskConfiguration; private TaskConfiguration taskConfiguration;
@XmlElement(name = "DeviceStatusTaskConfig")
private DeviceStatusTaskConfiguration deviceStatusTaskConfiguration;
@XmlElement(name = "DeviceAuthorizationConfig", required = true) @XmlElement(name = "DeviceAuthorizationConfig", required = true)
protected DeviceAuthorizationConfig deviceAuthorizationConfig; protected DeviceAuthorizationConfig deviceAuthorizationConfig;
@XmlAttribute(name = "name") @XmlAttribute(name = "name")
@ -85,9 +88,29 @@ public class DeviceTypeConfiguration {
this.operations = operations; this.operations = operations;
} }
/**
* Gets the value of the deviceStatusTaskConfiguration property.
*
* @return
* possible object is
* {@link DeviceStatusTaskConfiguration }
*
*/
public DeviceStatusTaskConfiguration getDeviceStatusTaskConfiguration() {
return deviceStatusTaskConfiguration;
}
/**
* Sets the value of the deviceStatusTaskConfiguration property.
*
* @param deviceStatusTaskConfiguration
* allowed object is
* {@link DeviceStatusTaskConfiguration }
*
*/
public void setDeviceStatusTaskConfiguration(DeviceStatusTaskConfiguration deviceStatusTaskConfiguration) {
this.deviceStatusTaskConfiguration = deviceStatusTaskConfiguration;
}
/** /**
* Gets the value of the taskConfiguration property. * Gets the value of the taskConfiguration property.
@ -313,5 +336,4 @@ public class DeviceTypeConfiguration {
public void setDeviceAuthorizationConfig(DeviceAuthorizationConfig value) { public void setDeviceAuthorizationConfig(DeviceAuthorizationConfig value) {
this.deviceAuthorizationConfig = value; this.deviceAuthorizationConfig = value;
} }
} }

@ -20,11 +20,8 @@ package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.InitialOperationConfig; import org.wso2.carbon.device.mgt.common.InitialOperationConfig;
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig; import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
@ -32,11 +29,7 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration
import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.ConfigProperties; import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.*;
import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.DeviceTypeConfiguration;
import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.Property;
import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.PushNotificationProvider;
import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.TaskConfiguration;
import org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.policy.mgt.DefaultPolicyMonitoringManager; import org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.policy.mgt.DefaultPolicyMonitoringManager;
import java.util.ArrayList; import java.util.ArrayList;
@ -60,6 +53,7 @@ public class DeviceTypeManagerService implements DeviceManagementService {
private List<MonitoringOperation> monitoringOperations; private List<MonitoringOperation> monitoringOperations;
private PolicyMonitoringManager policyMonitoringManager; private PolicyMonitoringManager policyMonitoringManager;
private InitialOperationConfig initialOperationConfig; private InitialOperationConfig initialOperationConfig;
private DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig;
public DeviceTypeManagerService(DeviceTypeConfigIdentifier deviceTypeConfigIdentifier, public DeviceTypeManagerService(DeviceTypeConfigIdentifier deviceTypeConfigIdentifier,
DeviceTypeConfiguration deviceTypeConfiguration) { DeviceTypeConfiguration deviceTypeConfiguration) {
@ -71,6 +65,8 @@ public class DeviceTypeManagerService implements DeviceManagementService {
this.setOperationMonitoringConfig(deviceTypeConfiguration); this.setOperationMonitoringConfig(deviceTypeConfiguration);
this.initialOperationConfig = new InitialOperationConfig(); this.initialOperationConfig = new InitialOperationConfig();
this.setInitialOperationConfig(deviceTypeConfiguration); this.setInitialOperationConfig(deviceTypeConfiguration);
this.deviceStatusTaskPluginConfig = new DeviceStatusTaskPluginConfig();
this.setDeviceStatusTaskPluginConfig(deviceTypeConfiguration.getDeviceStatusTaskConfiguration());
if (deviceTypeConfiguration.getPolicyMonitoring() != null ) { if (deviceTypeConfiguration.getPolicyMonitoring() != null ) {
this.policyMonitoringManager = new DefaultPolicyMonitoringManager(); this.policyMonitoringManager = new DefaultPolicyMonitoringManager();
} }
@ -174,6 +170,10 @@ public class DeviceTypeManagerService implements DeviceManagementService {
return initialOperationConfig; return initialOperationConfig;
} }
public DeviceStatusTaskPluginConfig getDeviceStatusTaskPluginConfig() {
return deviceStatusTaskPluginConfig;
}
private void setProvisioningConfig(String tenantDomain, DeviceTypeConfiguration deviceTypeConfiguration) { private void setProvisioningConfig(String tenantDomain, DeviceTypeConfiguration deviceTypeConfiguration) {
if (deviceTypeConfiguration.getProvisioningConfig() != null) { if (deviceTypeConfiguration.getProvisioningConfig() != null) {
boolean sharedWithAllTenants = deviceTypeConfiguration.getProvisioningConfig().isSharedWithAllTenants(); boolean sharedWithAllTenants = deviceTypeConfiguration.getProvisioningConfig().isSharedWithAllTenants();
@ -183,6 +183,15 @@ public class DeviceTypeManagerService implements DeviceManagementService {
} }
} }
private void setDeviceStatusTaskPluginConfig(DeviceStatusTaskConfiguration deviceStatusTaskConfiguration) {
if (deviceStatusTaskConfiguration != null && deviceStatusTaskConfiguration.isEnabled()) {
deviceStatusTaskPluginConfig.setRequireStatusMonitoring(deviceStatusTaskConfiguration.isEnabled());
deviceStatusTaskPluginConfig.setIdleTimeToMarkInactive(deviceStatusTaskConfiguration.getIdleTimeToMarkInactive());
deviceStatusTaskPluginConfig.setIdleTimeToMarkUnreachable(deviceStatusTaskConfiguration.getIdleTimeToMarkUnreachable());
deviceStatusTaskPluginConfig.setFrequency(deviceStatusTaskConfiguration.getFrequency());
}
}
protected void setInitialOperationConfig(DeviceTypeConfiguration deviceTypeConfiguration) { protected void setInitialOperationConfig(DeviceTypeConfiguration deviceTypeConfiguration) {
if (deviceTypeConfiguration.getOperations() != null) { if (deviceTypeConfiguration.getOperations() != null) {
List<String> ops = deviceTypeConfiguration.getOperations(); List<String> ops = deviceTypeConfiguration.getOperations();

@ -0,0 +1,62 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common;
/**
* This class holds plugin specific configurations for Device Status Monitoring Task.
*/
public class DeviceStatusTaskPluginConfig {
private boolean requireStatusMonitoring;
private int frequency;
private int idleTimeToMarkInactive;
private int idleTimeToMarkUnreachable;
public int getFrequency() {
return frequency;
}
public void setFrequency(int frequency) {
this.frequency = frequency;
}
public int getIdleTimeToMarkInactive() {
return idleTimeToMarkInactive;
}
public void setIdleTimeToMarkInactive(int idleTimeToMarkInactive) {
this.idleTimeToMarkInactive = idleTimeToMarkInactive;
}
public int getIdleTimeToMarkUnreachable() {
return idleTimeToMarkUnreachable;
}
public void setIdleTimeToMarkUnreachable(int idleTimeToMarkUnreachable) {
this.idleTimeToMarkUnreachable = idleTimeToMarkUnreachable;
}
public boolean isRequireStatusMonitoring() {
return requireStatusMonitoring;
}
public void setRequireStatusMonitoring(boolean requireStatusMonitoring) {
this.requireStatusMonitoring = requireStatusMonitoring;
}
}

@ -47,6 +47,6 @@ public interface DeviceManagementService {
InitialOperationConfig getInitialOperationConfig(); InitialOperationConfig getInitialOperationConfig();
DeviceStatusTaskPluginConfig getDeviceStatusTaskPluginConfig();
} }

@ -24,17 +24,23 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceTypeIdentifier; import org.wso2.carbon.device.mgt.common.DeviceTypeIdentifier;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig; import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; 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.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationProvider; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationProvider;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; 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.DeviceManagementServiceComponent;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagerStartupListener; import org.wso2.carbon.device.mgt.core.internal.DeviceManagerStartupListener;
import org.wso2.carbon.device.mgt.core.internal.DeviceMonitoringOperationDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceMonitoringOperationDataHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerRepository; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerRepository;
import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskException;
import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskManagerService;
import org.wso2.carbon.device.mgt.core.status.task.impl.DeviceStatusTaskManagerServiceImpl;
import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException; import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException;
import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
@ -46,7 +52,7 @@ import java.util.Map;
public class DeviceManagementPluginRepository implements DeviceManagerStartupListener { public class DeviceManagementPluginRepository implements DeviceManagerStartupListener {
private Map<DeviceTypeIdentifier, DeviceManagementService> providers; private Map<DeviceTypeIdentifier, DeviceManagementService> providers;
private boolean isInited; private boolean isInitiated;
private static final Log log = LogFactory.getLog(DeviceManagementPluginRepository.class); private static final Log log = LogFactory.getLog(DeviceManagementPluginRepository.class);
private OperationManagerRepository operationManagerRepository; private OperationManagerRepository operationManagerRepository;
@ -58,9 +64,9 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
public void addDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { public void addDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException {
String deviceType = provider.getType().toLowerCase(); String deviceType = provider.getType().toLowerCase();
ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); ProvisioningConfig provisioningConfig = provider.getProvisioningConfig();
String tenantDomain = provisioningConfig.getProviderTenantDomain(); String tenantDomain = provisioningConfig.getProviderTenantDomain();
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
boolean isSharedWithAllTenants = provisioningConfig.isSharedWithAllTenants(); boolean isSharedWithAllTenants = provisioningConfig.isSharedWithAllTenants();
int tenantId = DeviceManagerUtil.getTenantId(tenantDomain); int tenantId = DeviceManagerUtil.getTenantId(tenantDomain);
if (tenantId == -1) { if (tenantId == -1) {
@ -68,15 +74,18 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
} }
synchronized (providers) { synchronized (providers) {
try { try {
if (isInited) { if (isInitiated) {
/* Initializing Device Management Service Provider */ /* Initializing Device Management Service Provider */
provider.init(); provider.init();
DeviceManagerUtil.registerDeviceType(deviceType, tenantId, isSharedWithAllTenants); DeviceManagerUtil.registerDeviceType(deviceType, tenantId, isSharedWithAllTenants);
DeviceManagementDataHolder.getInstance().setRequireDeviceAuthorization(deviceType, DeviceManagementDataHolder.getInstance().setRequireDeviceAuthorization(deviceType,
provider.getDeviceManager() provider.getDeviceManager().
.requireDeviceAuthorization()); requireDeviceAuthorization());
registerPushNotificationStrategy(provider); registerPushNotificationStrategy(provider);
registerMonitoringTask(provider); registerMonitoringTask(provider);
if (deviceManagementConfig != null && deviceManagementConfig.getDeviceStatusTaskConfig().isEnabled()) {
registerDeviceStatusMonitoringTask(provider);
}
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
throw new DeviceManagementException("Error occurred while adding device management provider '" + throw new DeviceManagementException("Error occurred while adding device management provider '" +
@ -94,19 +103,23 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
public void removeDeviceManagementProvider(DeviceManagementService provider) public void removeDeviceManagementProvider(DeviceManagementService provider)
throws DeviceManagementException { throws DeviceManagementException {
String deviceTypeName = provider.getType().toLowerCase(); String deviceTypeName = provider.getType().toLowerCase();
DeviceTypeIdentifier deviceTypeIdentifier; DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); DeviceTypeIdentifier deviceTypeIdentifier;
if (provisioningConfig.isSharedWithAllTenants()) { ProvisioningConfig provisioningConfig = provider.getProvisioningConfig();
deviceTypeIdentifier = new DeviceTypeIdentifier(deviceTypeName); if (provisioningConfig.isSharedWithAllTenants()) {
providers.remove(deviceTypeIdentifier); deviceTypeIdentifier = new DeviceTypeIdentifier(deviceTypeName);
} else { providers.remove(deviceTypeIdentifier);
int providerTenantId = DeviceManagerUtil.getTenantId(provisioningConfig.getProviderTenantDomain()); } else {
deviceTypeIdentifier = new DeviceTypeIdentifier(deviceTypeName, providerTenantId); int providerTenantId = DeviceManagerUtil.getTenantId(provisioningConfig.getProviderTenantDomain());
providers.remove(deviceTypeIdentifier); deviceTypeIdentifier = new DeviceTypeIdentifier(deviceTypeName, providerTenantId);
} providers.remove(deviceTypeIdentifier);
unregisterPushNotificationStrategy(deviceTypeIdentifier); }
unregisterMonitoringTask(provider); unregisterPushNotificationStrategy(deviceTypeIdentifier);
unregisterMonitoringTask(provider);
if (deviceManagementConfig != null && deviceManagementConfig.getDeviceStatusTaskConfig().isEnabled()) {
unregisterDeviceStatusMonitoringTask(provider);
}
} }
private void unregisterPushNotificationStrategy(DeviceTypeIdentifier deviceTypeIdentifier) { private void unregisterPushNotificationStrategy(DeviceTypeIdentifier deviceTypeIdentifier) {
@ -181,12 +194,10 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
private void registerMonitoringTask(DeviceManagementService deviceManagementService) private void registerMonitoringTask(DeviceManagementService deviceManagementService)
throws DeviceManagementException { throws DeviceManagementException {
try { try {
DeviceTaskManagerService deviceTaskManagerService = DeviceManagementDataHolder.getInstance() DeviceTaskManagerService deviceTaskManagerService = DeviceManagementDataHolder.getInstance().
.getDeviceTaskManagerService(); getDeviceTaskManagerService();
OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementService.
OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementService getOperationMonitoringConfig();
.getOperationMonitoringConfig();
if (operationMonitoringTaskConfig != null && operationMonitoringTaskConfig.isEnabled()) { if (operationMonitoringTaskConfig != null && operationMonitoringTaskConfig.isEnabled()) {
if (deviceTaskManagerService == null) { if (deviceTaskManagerService == null) {
@ -206,10 +217,10 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
private void unregisterMonitoringTask(DeviceManagementService deviceManagementService) private void unregisterMonitoringTask(DeviceManagementService deviceManagementService)
throws DeviceManagementException { throws DeviceManagementException {
try { try {
DeviceTaskManagerService deviceTaskManagerService = DeviceManagementDataHolder.getInstance() DeviceTaskManagerService deviceTaskManagerService = DeviceManagementDataHolder.getInstance().
.getDeviceTaskManagerService(); getDeviceTaskManagerService();
OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementService OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementService.
.getOperationMonitoringConfig(); getOperationMonitoringConfig();
if (operationMonitoringTaskConfig != null) { if (operationMonitoringTaskConfig != null) {
deviceTaskManagerService.stopTask(deviceManagementService.getType(), deviceTaskManagerService.stopTask(deviceManagementService.getType(),
deviceManagementService.getOperationMonitoringConfig()); deviceManagementService.getOperationMonitoringConfig());
@ -220,6 +231,42 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
} }
} }
private void registerDeviceStatusMonitoringTask(DeviceManagementService deviceManagementService) throws
DeviceManagementException {
DeviceTaskManagerService deviceTaskManagerService = DeviceManagementDataHolder.getInstance().
getDeviceTaskManagerService();
DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig = deviceManagementService.getDeviceStatusTaskPluginConfig();
if (deviceStatusTaskPluginConfig != null && deviceStatusTaskPluginConfig.isRequireStatusMonitoring()) {
if (deviceTaskManagerService == null) {
DeviceManagementDataHolder.getInstance().addDeviceStatusTaskPluginConfig(deviceManagementService.getType(),
deviceStatusTaskPluginConfig);
} else {
try {
new DeviceStatusTaskManagerServiceImpl().startTask(deviceManagementService.getType(), deviceStatusTaskPluginConfig);
} catch (DeviceStatusTaskException e) {
throw new DeviceManagementException("Error occurred while adding Device Status task service for '" +
deviceManagementService.getType() + "'", e);
}
}
}
}
private void unregisterDeviceStatusMonitoringTask(DeviceManagementService deviceManagementService) throws
DeviceManagementException {
DeviceStatusTaskManagerService deviceStatusTaskManagerService = DeviceManagementDataHolder.getInstance().
getDeviceStatusTaskManagerService();
DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig = deviceManagementService.getDeviceStatusTaskPluginConfig();
if (deviceStatusTaskPluginConfig != null && deviceStatusTaskPluginConfig.isRequireStatusMonitoring()) {
try {
DeviceManagementDataHolder.getInstance().removeDeviceStatusTaskPluginConfig(deviceManagementService.getType());
deviceStatusTaskManagerService.stopTask(deviceManagementService.getType(), deviceStatusTaskPluginConfig);
} catch (DeviceStatusTaskException e) {
throw new DeviceManagementException("Error occurred while stopping Device Status task service for '" +
deviceManagementService.getType() + "'", e);
}
}
}
public OperationManager getOperationManager(String deviceType, int tenantId) { public OperationManager getOperationManager(String deviceType, int tenantId) {
//Priority need to be given to the tenant before public. //Priority need to be given to the tenant before public.
DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType.toLowerCase(), tenantId); DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType.toLowerCase(), tenantId);
@ -245,6 +292,7 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
provisioningConfig.isSharedWithAllTenants()); provisioningConfig.isSharedWithAllTenants());
registerPushNotificationStrategy(provider); registerPushNotificationStrategy(provider);
registerMonitoringTask(provider); registerMonitoringTask(provider);
//TODO: //TODO:
//This is a temporory fix. //This is a temporory fix.
//windows and IOS cannot resolve user info by extracting certs //windows and IOS cannot resolve user info by extracting certs
@ -260,7 +308,7 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
provider.getType() + "'", e); provider.getType() + "'", e);
} }
} }
this.isInited = true; this.isInitiated = true;
} }
} }
} }

@ -21,6 +21,7 @@ import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations;
import org.wso2.carbon.device.mgt.core.config.pagination.PaginationConfiguration; import org.wso2.carbon.device.mgt.core.config.pagination.PaginationConfiguration;
import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration;
import org.wso2.carbon.device.mgt.core.config.push.notification.PushNotificationConfiguration; import org.wso2.carbon.device.mgt.core.config.push.notification.PushNotificationConfiguration;
import org.wso2.carbon.device.mgt.core.config.status.task.DeviceStatusTaskConfig;
import org.wso2.carbon.device.mgt.core.config.task.TaskConfiguration; import org.wso2.carbon.device.mgt.core.config.task.TaskConfiguration;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
@ -41,6 +42,7 @@ public final class DeviceManagementConfig {
private PolicyConfiguration policyConfiguration; private PolicyConfiguration policyConfiguration;
private PaginationConfiguration paginationConfiguration; private PaginationConfiguration paginationConfiguration;
private PushNotificationConfiguration pushNotificationConfiguration; private PushNotificationConfiguration pushNotificationConfiguration;
private DeviceStatusTaskConfig deviceStatusTaskConfig;
@XmlElement(name = "ManagementRepository", required = true) @XmlElement(name = "ManagementRepository", required = true)
@ -97,5 +99,14 @@ public final class DeviceManagementConfig {
public void setPushNotificationConfiguration(PushNotificationConfiguration pushNotificationConfiguration) { public void setPushNotificationConfiguration(PushNotificationConfiguration pushNotificationConfiguration) {
this.pushNotificationConfiguration = pushNotificationConfiguration; this.pushNotificationConfiguration = pushNotificationConfiguration;
} }
@XmlElement(name = "DeviceStatusTaskConfig", required = true)
public DeviceStatusTaskConfig getDeviceStatusTaskConfig() {
return deviceStatusTaskConfig;
}
public void setDeviceStatusTaskConfig(DeviceStatusTaskConfig deviceStatusTaskConfig) {
this.deviceStatusTaskConfig = deviceStatusTaskConfig;
}
} }

@ -0,0 +1,38 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.config.status.task;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "DeviceStatusTaskConfig")
public class DeviceStatusTaskConfig {
private boolean enabled;
@XmlElement(name = "Enable", required = true)
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}

@ -32,11 +32,15 @@ public interface EnrollmentDAO {
int updateEnrollment(EnrolmentInfo enrolmentInfo) throws DeviceManagementDAOException; int updateEnrollment(EnrolmentInfo enrolmentInfo) throws DeviceManagementDAOException;
boolean updateEnrollmentStatus(List<EnrolmentInfo> enrolmentInfos) throws DeviceManagementDAOException;
int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException; int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException;
boolean setStatus(int enrolmentId, String currentOwner, Status status, boolean setStatus(int enrolmentId, String currentOwner, Status status,
int tenantId) throws DeviceManagementDAOException; int tenantId) throws DeviceManagementDAOException;
boolean setStatus(int enrolmentId, Status status, int tenantId) throws DeviceManagementDAOException;
Status getStatus(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException; Status getStatus(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException;
EnrolmentInfo getEnrollment(int deviceId, String currentUser, int tenantId) throws DeviceManagementDAOException; EnrolmentInfo getEnrollment(int deviceId, String currentUser, int tenantId) throws DeviceManagementDAOException;

@ -23,6 +23,7 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO; import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping;
import java.sql.*; import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
@ -115,6 +116,42 @@ public class EnrollmentDAOImpl implements EnrollmentDAO {
} }
} }
@Override
public boolean updateEnrollmentStatus(List<EnrolmentInfo> enrolmentInfos) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
boolean status = false;
int updateStatus = -1;
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE ID = ?";
stmt = conn.prepareStatement(sql);
if (conn.getMetaData().supportsBatchUpdates()) {
for (EnrolmentInfo enrolmentInfo : enrolmentInfos) {
stmt.setString(1, enrolmentInfo.getStatus().toString());
stmt.setInt(2, enrolmentInfo.getId());
stmt.addBatch();
}
updateStatus = stmt.executeBatch().length;
} else {
for (EnrolmentInfo enrolmentInfo : enrolmentInfos) {
stmt.setString(1, enrolmentInfo.getStatus().toString());
stmt.setInt(2, enrolmentInfo.getId());
updateStatus = stmt.executeUpdate();
}
}
if (updateStatus > 0) {
status = true;
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while updating enrolment status of given device-list.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return status;
}
@Override @Override
public int removeEnrollment(int deviceId, String currentOwner, public int removeEnrollment(int deviceId, String currentOwner,
@ -166,6 +203,26 @@ public class EnrollmentDAOImpl implements EnrollmentDAO {
return true; return true;
} }
@Override
public boolean setStatus(int enrolmentID, EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, status.toString());
stmt.setInt(2, enrolmentID);
stmt.setInt(3, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return true;
}
@Override @Override
public EnrolmentInfo.Status getStatus(int deviceId, String currentOwner, public EnrolmentInfo.Status getStatus(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException { int tenantId) throws DeviceManagementDAOException {

@ -18,6 +18,7 @@
package org.wso2.carbon.device.mgt.core.internal; package org.wso2.carbon.device.mgt.core.internal;
import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
@ -28,6 +29,7 @@ import org.wso2.carbon.device.mgt.core.config.license.LicenseConfig;
import org.wso2.carbon.device.mgt.core.push.notification.mgt.PushNotificationProviderRepository; import org.wso2.carbon.device.mgt.core.push.notification.mgt.PushNotificationProviderRepository;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskManagerService;
import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService;
import org.wso2.carbon.email.sender.core.service.EmailSenderService; import org.wso2.carbon.email.sender.core.service.EmailSenderService;
import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.ntask.core.service.TaskService;
@ -36,6 +38,7 @@ import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.user.core.tenant.TenantManager;
import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.ConfigurationContextService;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -59,6 +62,9 @@ public class DeviceManagementDataHolder {
private EmailSenderService emailSenderService; private EmailSenderService emailSenderService;
private PushNotificationProviderRepository pushNotificationProviderRepository; private PushNotificationProviderRepository pushNotificationProviderRepository;
private DeviceTaskManagerService deviceTaskManagerService; private DeviceTaskManagerService deviceTaskManagerService;
private DeviceStatusTaskManagerService deviceStatusTaskManagerService;
private Map<String, DeviceStatusTaskPluginConfig> deviceStatusTaskPluginConfigs = Collections.synchronizedMap(
new HashMap<String, DeviceStatusTaskPluginConfig>());
private Map<String, OperationMonitoringTaskConfig> map = new HashMap<>(); private Map<String, OperationMonitoringTaskConfig> map = new HashMap<>();
@ -191,7 +197,6 @@ public class DeviceManagementDataHolder {
this.deviceAccessAuthorizationService = deviceAccessAuthorizationService; this.deviceAccessAuthorizationService = deviceAccessAuthorizationService;
} }
public TaskService getTaskService() { public TaskService getTaskService() {
return taskService; return taskService;
} }
@ -224,4 +229,28 @@ public class DeviceManagementDataHolder {
public void setDeviceTaskManagerService(DeviceTaskManagerService deviceTaskManagerService) { public void setDeviceTaskManagerService(DeviceTaskManagerService deviceTaskManagerService) {
this.deviceTaskManagerService = deviceTaskManagerService; this.deviceTaskManagerService = deviceTaskManagerService;
} }
public DeviceStatusTaskManagerService getDeviceStatusTaskManagerService() {
return deviceStatusTaskManagerService;
}
public void setDeviceStatusTaskManagerService(DeviceStatusTaskManagerService deviceStatusTaskManagerService) {
this.deviceStatusTaskManagerService = deviceStatusTaskManagerService;
}
public void addDeviceStatusTaskPluginConfig(String deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig) {
this.deviceStatusTaskPluginConfigs.put(deviceType, deviceStatusTaskPluginConfig);
}
public DeviceStatusTaskPluginConfig getDeviceStatusTaskPluginConfig(String deviceType) {
return this.deviceStatusTaskPluginConfigs.get(deviceType);
}
public Map<String, DeviceStatusTaskPluginConfig> getDeviceStatusTaskPluginConfigs() {
return this.deviceStatusTaskPluginConfigs;
}
public void removeDeviceStatusTaskPluginConfig(String deviceType) {
this.deviceStatusTaskPluginConfigs.remove(deviceType);
}
} }

@ -22,11 +22,17 @@ package org.wso2.carbon.device.mgt.core.internal;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl; import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
import org.wso2.carbon.device.mgt.core.search.mgt.impl.SearchManagerServiceImpl; import org.wso2.carbon.device.mgt.core.search.mgt.impl.SearchManagerServiceImpl;
import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskException;
import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskManagerService;
import org.wso2.carbon.device.mgt.core.status.task.impl.DeviceStatusTaskManagerServiceImpl;
import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException; import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException;
import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService;
import org.wso2.carbon.device.mgt.core.task.impl.DeviceTaskManagerServiceImpl; import org.wso2.carbon.device.mgt.core.task.impl.DeviceTaskManagerServiceImpl;
@ -47,24 +53,21 @@ import java.util.Map;
public class DeviceTaskManagerServiceComponent { public class DeviceTaskManagerServiceComponent {
private static Log log = LogFactory.getLog(DeviceManagementServiceComponent.class); private static Log log = LogFactory.getLog(DeviceTaskManagerServiceComponent.class);
@SuppressWarnings("unused") @SuppressWarnings("unused")
protected void activate(ComponentContext componentContext) { protected void activate(ComponentContext componentContext) {
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Initializing device details retrieving task manager bundle."); log.debug("Initializing device task manager bundle.");
} }
// This will start the device details retrieving task.
// DeviceTaskManagerService deviceTaskManagerService = new DeviceTaskManagerServiceImpl();
// DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(
// deviceTaskManagerService);
// componentContext.getBundleContext().registerService(DeviceTaskManagerService.class,
// deviceTaskManagerService, null);
getDeviceOperationMonitoringConfig(componentContext); getDeviceOperationMonitoringConfig(componentContext);
//Start the DeviceStatusMonitoringTask for registered DeviceTypes
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig();
if (deviceManagementConfig != null && deviceManagementConfig.getDeviceStatusTaskConfig().isEnabled()) {
startDeviceStatusMonitoringTask();
}
componentContext.getBundleContext().registerService(DeviceInformationManager.class, componentContext.getBundleContext().registerService(DeviceInformationManager.class,
new DeviceInformationManagerImpl(), null); new DeviceInformationManagerImpl(), null);
@ -72,29 +75,39 @@ public class DeviceTaskManagerServiceComponent {
componentContext.getBundleContext().registerService(SearchManagerService.class, componentContext.getBundleContext().registerService(SearchManagerService.class,
new SearchManagerServiceImpl(), null); new SearchManagerServiceImpl(), null);
} catch (Throwable e) { } catch (Throwable e) {
log.error("Error occurred while initializing device details retrieving task manager service.", e); log.error("Error occurred while initializing device task manager service.", e);
} }
} }
private void getDeviceOperationMonitoringConfig(ComponentContext componentContext) private void getDeviceOperationMonitoringConfig(ComponentContext componentContext)
throws DeviceMgtTaskException { throws DeviceMgtTaskException {
DeviceTaskManagerService deviceTaskManagerService = new DeviceTaskManagerServiceImpl(); DeviceTaskManagerService deviceTaskManagerService = new DeviceTaskManagerServiceImpl();
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(deviceTaskManagerService); DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(deviceTaskManagerService);
componentContext.getBundleContext().registerService(DeviceTaskManagerService.class, componentContext.getBundleContext().registerService(DeviceTaskManagerService.class,
deviceTaskManagerService, null); deviceTaskManagerService, null);
Map<String, OperationMonitoringTaskConfig> deviceConfigMap = DeviceMonitoringOperationDataHolder Map<String, OperationMonitoringTaskConfig> deviceConfigMap = DeviceMonitoringOperationDataHolder
.getInstance().getOperationMonitoringConfigFromMap(); .getInstance().getOperationMonitoringConfigFromMap();
for (String platformType : new ArrayList<>(deviceConfigMap.keySet())) { for (String platformType : new ArrayList<>(deviceConfigMap.keySet())) {
deviceTaskManagerService.startTask(platformType, deviceConfigMap.get(platformType)); deviceTaskManagerService.startTask(platformType, deviceConfigMap.get(platformType));
deviceConfigMap.remove(platformType); deviceConfigMap.remove(platformType);
} }
} }
private void startDeviceStatusMonitoringTask() {
DeviceStatusTaskManagerService deviceStatusTaskManagerService = new DeviceStatusTaskManagerServiceImpl();
Map<String, DeviceStatusTaskPluginConfig> deviceStatusTaskPluginConfigs = DeviceManagementDataHolder.
getInstance().getDeviceStatusTaskPluginConfigs();
for (String deviceType : new ArrayList<>(deviceStatusTaskPluginConfigs.keySet())) {
try {
deviceStatusTaskManagerService.startTask(deviceType, deviceStatusTaskPluginConfigs.get(deviceType));
} catch (DeviceStatusTaskException e) {
log.error("Exception occurred while starting the DeviceStatusMonitoring Task for deviceType '" +
deviceType + "'", e);
}
}
}
@SuppressWarnings("unused") @SuppressWarnings("unused")
protected void deactivate(ComponentContext componentContext) { protected void deactivate(ComponentContext componentContext) {
try { try {
@ -105,7 +118,6 @@ public class DeviceTaskManagerServiceComponent {
} }
} }
protected void setTaskService(TaskService taskService) { protected void setTaskService(TaskService taskService) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting the task service."); log.debug("Setting the task service.");
@ -119,7 +131,4 @@ public class DeviceTaskManagerServiceComponent {
} }
DeviceManagementDataHolder.getInstance().setTaskService(null); DeviceManagementDataHolder.getInstance().setTaskService(null);
} }
} }

@ -0,0 +1,82 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.operation.mgt;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
/**
* This holds results of Pending-operations to enrolment mappings.
*/
public class OperationEnrolmentMapping {
int enrolmentId;
int deviceId;
int tenantId;
long createdTime;
String owner;
EnrolmentInfo.Status deviceStatus;
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public int getEnrolmentId() {
return enrolmentId;
}
public void setEnrolmentId(int enrolmentId) {
this.enrolmentId = enrolmentId;
}
public int getDeviceId() {
return deviceId;
}
public void setDeviceId(int deviceId) {
this.deviceId = deviceId;
}
public long getCreatedTime() {
return createdTime;
}
public void setCreatedTime(long createdTime) {
this.createdTime = createdTime;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public EnrolmentInfo.Status getDeviceStatus() {
return deviceStatus;
}
public void setDeviceStatus(String deviceStatus) {
this.deviceStatus = EnrolmentInfo.Status.valueOf(deviceStatus);
}
}

@ -418,12 +418,8 @@ public class OperationManagerImpl implements OperationManager {
int enrolmentId = enrolmentInfo.getId(); int enrolmentId = enrolmentInfo.getId();
//Changing the enrollment status & attempt count if the device is marked as inactive or unreachable //Changing the enrollment status & attempt count if the device is marked as inactive or unreachable
switch (enrolmentInfo.getStatus()) { switch (enrolmentInfo.getStatus()) {
case ACTIVE:
this.resetAttemptCount(enrolmentId);
break;
case INACTIVE: case INACTIVE:
case UNREACHABLE: case UNREACHABLE:
this.resetAttemptCount(enrolmentId);
this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE); this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE);
break; break;
} }
@ -479,12 +475,8 @@ public class OperationManagerImpl implements OperationManager {
int enrolmentId = enrolmentInfo.getId(); int enrolmentId = enrolmentInfo.getId();
//Changing the enrollment status & attempt count if the device is marked as inactive or unreachable //Changing the enrollment status & attempt count if the device is marked as inactive or unreachable
switch (enrolmentInfo.getStatus()) { switch (enrolmentInfo.getStatus()) {
case ACTIVE:
this.resetAttemptCount(enrolmentId);
break;
case INACTIVE: case INACTIVE:
case UNREACHABLE: case UNREACHABLE:
this.resetAttemptCount(enrolmentId);
this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE); this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE);
break; break;
} }
@ -1040,24 +1032,6 @@ public class OperationManagerImpl implements OperationManager {
return updateStatus; return updateStatus;
} }
private boolean resetAttemptCount(int enrolmentId) throws OperationManagementException {
boolean resetStatus;
try {
OperationManagementDAOFactory.beginTransaction();
resetStatus = operationDAO.resetAttemptCount(enrolmentId);
OperationManagementDAOFactory.commitTransaction();
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
throw new OperationManagementException("Error occurred while resetting attempt count of device id : '" +
enrolmentId + "'", e);
} catch (TransactionManagementException e) {
throw new OperationManagementException("Error occurred while initiating a transaction", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
return resetStatus;
}
private boolean isTaskScheduledOperation(Operation operation, List<DeviceIdentifier> deviceIds) { private boolean isTaskScheduledOperation(Operation operation, List<DeviceIdentifier> deviceIds) {
DeviceManagementProviderService deviceManagementProviderService = DeviceManagementDataHolder.getInstance(). DeviceManagementProviderService deviceManagementProviderService = DeviceManagementDataHolder.getInstance().
getDeviceManagementProvider(); getDeviceManagementProvider();

@ -18,6 +18,7 @@
*/ */
package org.wso2.carbon.device.mgt.core.operation.mgt.dao; package org.wso2.carbon.device.mgt.core.operation.mgt.dao;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation;
@ -34,4 +35,14 @@ public interface OperationMappingDAO {
void updateOperationMapping(List<OperationMapping> operationMappingList) throws void updateOperationMapping(List<OperationMapping> operationMappingList) throws
OperationManagementDAOException; OperationManagementDAOException;
/**
* This method returns first pending/repeated operation available for each active enrolment where the operation was
* created after the given timestamp.
*
* @param createdTimeStamp - Operation created time
* @throws OperationManagementDAOException
*/
List<OperationEnrolmentMapping> getFirstPendingOperationMappingsForActiveEnrolments(long createdTimeStamp)
throws OperationManagementDAOException;
} }

@ -18,6 +18,7 @@
*/ */
package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl; package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException;
@ -27,7 +28,9 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationMappingDAO;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class OperationMappingDAOImpl implements OperationMappingDAO { public class OperationMappingDAOImpl implements OperationMappingDAO {
@ -129,4 +132,46 @@ public class OperationMappingDAOImpl implements OperationMappingDAO {
OperationManagementDAOUtil.cleanupResources(stmt, null); OperationManagementDAOUtil.cleanupResources(stmt, null);
} }
} }
@Override
public List<OperationEnrolmentMapping> getFirstPendingOperationMappingsForActiveEnrolments(long createdTimeStamp)
throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<OperationEnrolmentMapping> enrolmentOperationMappingList = null;
try {
Connection conn = OperationManagementDAOFactory.getConnection();
//We are specifically looking for operation mappings in 'Pending' & 'Repeated' states. Further we want
//devices to be active at that moment. Hence filtering by 'ACTIVE' & 'UNREACHABLE' device states.
String sql = "SELECT E.ID AS ENROLMENT_ID, E.DEVICE_ID, E.OWNER, E.STATUS, E.TENANT_ID, OP.CREATED_TIMESTAMP " +
"FROM DM_ENROLMENT E, (SELECT ENROLMENT_ID AS EID, MIN(CREATED_TIMESTAMP) AS CREATED_TIMESTAMP FROM " +
"DM_ENROLMENT_OP_MAPPING WHERE STATUS IN ('PENDING','REPEATED') AND CREATED_TIMESTAMP >= ? " +
"GROUP BY EID) OP WHERE OP.EID=E.ID AND E.STATUS IN ('ACTIVE','UNREACHABLE')";
stmt = conn.prepareStatement(sql);
stmt.setLong(1, createdTimeStamp);
rs = stmt.executeQuery();
enrolmentOperationMappingList = new ArrayList<>();
while (rs.next()) {
OperationEnrolmentMapping enrolmentOperationMapping = this.getEnrolmentOpMapping(rs);
enrolmentOperationMappingList.add(enrolmentOperationMapping);
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while fetching pending operation mappings for " +
"active devices ", e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
return enrolmentOperationMappingList;
}
private OperationEnrolmentMapping getEnrolmentOpMapping(ResultSet rs) throws SQLException {
OperationEnrolmentMapping enrolmentOperationMapping = new OperationEnrolmentMapping();
enrolmentOperationMapping.setEnrolmentId(rs.getInt("ENROLMENT_ID"));
enrolmentOperationMapping.setDeviceId(rs.getInt("DEVICE_ID"));
enrolmentOperationMapping.setTenantId(rs.getInt("TENANT_ID"));
enrolmentOperationMapping.setOwner(rs.getString("OWNER"));
enrolmentOperationMapping.setCreatedTime(rs.getLong("CREATED_TIMESTAMP"));
enrolmentOperationMapping.setDeviceStatus(rs.getString("STATUS"));
return enrolmentOperationMapping;
}
} }

@ -351,8 +351,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
return false; return false;
} }
DeviceType deviceType = deviceTypeDAO.getDeviceType(device.getType(), tenantId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.getEnrolmentInfo().setStatus(EnrolmentInfo.Status.REMOVED); device.getEnrolmentInfo().setStatus(EnrolmentInfo.Status.REMOVED);
enrollmentDAO.updateEnrollment(device.getId(), device.getEnrolmentInfo(), tenantId); enrollmentDAO.updateEnrollment(device.getId(), device.getEnrolmentInfo(), tenantId);
@ -2052,21 +2050,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return CarbonContext.getThreadLocalCarbonContext().getTenantId(); return CarbonContext.getThreadLocalCarbonContext().getTenantId();
} }
// private int getTenantId(String tenantDomain) throws DeviceManagementException {
// RealmService realmService =
// (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null);
// if (realmService == null) {
// throw new IllegalStateException("");
// }
// try {
// return realmService.getTenantManager().getTenantId(tenantDomain);
// } catch (UserStoreException e) {
// throw new DeviceManagementException("");
// }
// }
private DeviceManager getDeviceManager(String deviceType) { private DeviceManager getDeviceManager(String deviceType) {
DeviceManagementService deviceManagementService = DeviceManagementService deviceManagementService =
pluginRepository.getDeviceManagementService(deviceType, this.getTenantId()); pluginRepository.getDeviceManagementService(deviceType, this.getTenantId());
if (deviceManagementService == null) { if (deviceManagementService == null) {

@ -0,0 +1,63 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.status.task;
/**
* This exception class defines the custom exceptions thrown by the DeviceStatusMonitoringTask related components.
*/
public class DeviceStatusTaskException extends Exception {
private static final long serialVersionUID = -31222242646464497L;
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public DeviceStatusTaskException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public DeviceStatusTaskException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public DeviceStatusTaskException(String msg) {
super(msg);
setErrorMessage(msg);
}
public DeviceStatusTaskException() {
super();
}
public DeviceStatusTaskException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,60 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.status.task;
import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig;
import org.wso2.carbon.device.mgt.core.config.status.task.DeviceStatusTaskConfig;
/**
* This interface defines the methods that should be implemented by the management service of
* DeviceStatusMonitoringTask.
*/
public interface DeviceStatusTaskManagerService {
/**
* This method will start the task.
* @param deviceStatusTaskConfig - DeviceStatusTaskConfig
* @throws DeviceStatusTaskException
*/
void startTask(String deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskConfig)
throws DeviceStatusTaskException;
/**
* This method will stop the task.
* @param deviceStatusTaskConfig - DeviceStatusTaskConfig
* @throws DeviceStatusTaskException
*/
void stopTask(String deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskConfig)
throws DeviceStatusTaskException;
/**
* This will update the task frequency which it runs.
* @param deviceStatusTaskConfig - DeviceStatusTaskConfig
* @throws DeviceStatusTaskException
*/
void updateTask(String deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskConfig)
throws DeviceStatusTaskException;
/**
* This will check weather the task is scheduled.
* @param deviceType - Device Type
* @throws DeviceStatusTaskException
*/
boolean isTaskScheduled(String deviceType) throws DeviceStatusTaskException;
}

@ -0,0 +1,148 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.status.task.impl;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.core.encryption.SymmetricEncryption;
import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig;
import org.wso2.carbon.device.mgt.core.config.status.task.DeviceStatusTaskConfig;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskException;
import org.wso2.carbon.ntask.core.Task;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* This implements the Task service which monitors the device activity periodically & update the device-status if
* necessary.
*/
public class DeviceStatusMonitoringTask implements Task {
private static Log log = LogFactory.getLog(DeviceStatusMonitoringTask.class);
private String deviceType;
private DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig;
@Override
public void setProperties(Map<String, String> properties) {
deviceType = properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE);
String deviceStatusTaskConfigStr = properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_STATUS_TASK_CONFIG);
Gson gson = new Gson();
deviceStatusTaskPluginConfig = gson.fromJson(deviceStatusTaskConfigStr, DeviceStatusTaskPluginConfig.class);
}
@Override
public void init() {
}
@Override
public void execute() {
List<OperationEnrolmentMapping> operationEnrolmentMappings = null;
List<EnrolmentInfo> enrolmentInfoTobeUpdated = new ArrayList<>();
EnrolmentInfo enrolmentInfo;
try {
operationEnrolmentMappings = this.getOperationEnrolmentMappings();
} catch (DeviceStatusTaskException e) {
log.error("Error occurred while fetching OperationEnrolment mappings of deviceType '" + deviceType + "'", e);
}
for (OperationEnrolmentMapping mapping:operationEnrolmentMappings) {
EnrolmentInfo.Status newStatus = this.determineDeviceStatus(mapping);
if (newStatus != mapping.getDeviceStatus()) {
enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setId(mapping.getEnrolmentId());
enrolmentInfo.setStatus(newStatus);
enrolmentInfoTobeUpdated.add(enrolmentInfo);
}
}
if (enrolmentInfoTobeUpdated.size() > 0) {
try {
this.updateDeviceStatus(enrolmentInfoTobeUpdated);
} catch (DeviceStatusTaskException e) {
log.error("Error occurred while updating non-responsive device-status of devices of type '" + deviceType + "'",e);
}
}
}
private EnrolmentInfo.Status determineDeviceStatus(OperationEnrolmentMapping opMapping) {
long lastContactedBefore = (System.currentTimeMillis()/1000) - opMapping.getCreatedTime();
EnrolmentInfo.Status status = opMapping.getDeviceStatus();
if (lastContactedBefore >= this.deviceStatusTaskPluginConfig.getIdleTimeToMarkInactive()) {
status = EnrolmentInfo.Status.INACTIVE;
} else if (lastContactedBefore >= this.deviceStatusTaskPluginConfig.getIdleTimeToMarkUnreachable()) {
status = EnrolmentInfo.Status.UNREACHABLE;
}
return status;
}
private long getTimeWindow() {
return (System.currentTimeMillis()/1000) - this.deviceStatusTaskPluginConfig.getIdleTimeToMarkInactive();
}
private boolean updateDeviceStatus(List<EnrolmentInfo> enrolmentInfos) throws
DeviceStatusTaskException {
boolean updateStatus;
try {
DeviceManagementDAOFactory.beginTransaction();
updateStatus = DeviceManagementDAOFactory.getEnrollmentDAO().updateEnrollmentStatus(enrolmentInfos);
DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceStatusTaskException("Error occurred while updating enrollment status of devices of type '"
+ deviceType + "'", e);
} catch (TransactionManagementException e) {
throw new DeviceStatusTaskException("Error occurred while initiating a transaction for updating the device " +
"status of type '" + deviceType +"'", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
return updateStatus;
}
private List<OperationEnrolmentMapping> getOperationEnrolmentMappings() throws DeviceStatusTaskException {
List<OperationEnrolmentMapping> operationEnrolmentMappings = null;
try {
OperationManagementDAOFactory.openConnection();
operationEnrolmentMappings = OperationManagementDAOFactory.
getOperationMappingDAO().getFirstPendingOperationMappingsForActiveEnrolments(this.getTimeWindow());
} catch (SQLException e) {
throw new DeviceStatusTaskException("Error occurred while getting Enrolment operation mappings for " +
"determining device status of deviceType '" + deviceType + "'", e);
} catch (OperationManagementDAOException e) {
throw new DeviceStatusTaskException("Error occurred obtaining a DB connection for fetching " +
"operation-enrolment mappings for status monitoring of deviceType '" + deviceType + "'", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
return operationEnrolmentMappings;
}
}

@ -0,0 +1,165 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.status.task.impl;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskException;
import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskManagerService;
import org.wso2.carbon.ntask.common.TaskException;
import org.wso2.carbon.ntask.core.TaskInfo;
import org.wso2.carbon.ntask.core.TaskManager;
import org.wso2.carbon.ntask.core.service.TaskService;
import java.util.HashMap;
import java.util.Map;
/**
* Implementation of DeviceStatusTaskManagerService.
*/
public class DeviceStatusTaskManagerServiceImpl implements DeviceStatusTaskManagerService {
private static Log log = LogFactory.getLog(DeviceStatusTaskManagerServiceImpl.class);
public static final String DEVICE_STATUS_MONITORING_TASK_TYPE = "DEVICE_STATUS_MONITORING";
static final String DEVICE_TYPE = "DEVICE_TYPE";
static final String DEVICE_STATUS_TASK_CONFIG = "DEVICE_STATUS_TASK_CONFIG";
private static String TASK_CLASS = DeviceStatusMonitoringTask.class.getName();
@Override
public void startTask(String deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskConfig)
throws DeviceStatusTaskException {
log.info("Device Status monitoring Task adding for " + deviceType);
try {
TaskService taskService = DeviceManagementDataHolder.getInstance().getTaskService();
taskService.registerTaskType(DEVICE_STATUS_MONITORING_TASK_TYPE);
if (log.isDebugEnabled()) {
log.debug("Device Status monitoring task is started for the device type " + deviceType);
log.debug(
"Device Status monitoring task is at frequency of : " + deviceStatusTaskConfig.getFrequency());
}
TaskManager taskManager = taskService.getTaskManager(DEVICE_STATUS_MONITORING_TASK_TYPE);
TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo();
//Convert to milli seconds
triggerInfo.setIntervalMillis(deviceStatusTaskConfig.getFrequency()*1000);
triggerInfo.setRepeatCount(-1);
Gson gson = new Gson();
String deviceStatusTaskConfigs = gson.toJson(deviceStatusTaskConfig);
Map<String, String> properties = new HashMap<>();
properties.put(DEVICE_TYPE, deviceType);
properties.put(DEVICE_STATUS_TASK_CONFIG, deviceStatusTaskConfigs);
String taskName = DEVICE_STATUS_MONITORING_TASK_TYPE + "_" + deviceType;
if (!taskManager.isTaskScheduled(deviceType)) {
TaskInfo taskInfo = new TaskInfo(taskName, TASK_CLASS, properties, triggerInfo);
taskManager.registerTask(taskInfo);
taskManager.rescheduleTask(taskInfo.getName());
} else {
throw new DeviceStatusTaskException(
"Device Status monitoring task is already started for this device-type : " + deviceType);
}
} catch (TaskException e) {
throw new DeviceStatusTaskException("Error occurred while creating the Device Status monitoring task " +
"for device-type : " + deviceType, e);
}
}
@Override
public void stopTask(String deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskConfig)
throws DeviceStatusTaskException {
try {
TaskService taskService = DeviceManagementDataHolder.getInstance().getTaskService();
if (taskService.isServerInit()) {
TaskManager taskManager = taskService.getTaskManager(DEVICE_STATUS_MONITORING_TASK_TYPE);
taskManager.deleteTask(deviceType);
}
} catch (TaskException e) {
throw new DeviceStatusTaskException("Error occurred while deleting the Device Status monitoring task " +
"for tenant " + getTenantId(), e);
}
}
@Override
public void updateTask(String deviceType, DeviceStatusTaskPluginConfig deviceStatusTaskConfig)
throws DeviceStatusTaskException {
int tenantId = getTenantId();
try {
TaskService taskService = DeviceManagementDataHolder.getInstance().getTaskService();
TaskManager taskManager = taskService.getTaskManager(DEVICE_STATUS_MONITORING_TASK_TYPE);
String taskName = DEVICE_STATUS_MONITORING_TASK_TYPE + "_" + deviceType + "_" + String.valueOf(tenantId);
if (taskManager.isTaskScheduled(taskName)) {
taskManager.deleteTask(taskName);
TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo();
triggerInfo.setIntervalMillis(deviceStatusTaskConfig.getFrequency());
triggerInfo.setRepeatCount(-1);
Map<String, String> properties = new HashMap<>();
properties.put(DEVICE_TYPE, deviceType);
Gson gson = new Gson();
String deviceStatusTaskConfigs = gson.toJson(deviceStatusTaskConfig);
properties.put(DEVICE_STATUS_TASK_CONFIG, deviceStatusTaskConfigs);
TaskInfo taskInfo = new TaskInfo(deviceType, TASK_CLASS, properties, triggerInfo);
taskManager.registerTask(taskInfo);
taskManager.rescheduleTask(taskInfo.getName());
} else {
throw new DeviceStatusTaskException(
"Device details retrieving Device Status monitoring task has not been started for this tenant " +
tenantId + ". Please start the task first.");
}
} catch (TaskException e) {
throw new DeviceStatusTaskException("Error occurred while updating the Device Status monitoring task for tenant " + tenantId,
e);
}
}
@Override
public boolean isTaskScheduled(String deviceType) throws DeviceStatusTaskException {
int tenantId = getTenantId();
String taskName = DEVICE_STATUS_MONITORING_TASK_TYPE + "_" + deviceType + "_" + String.valueOf(tenantId);
TaskService taskService = DeviceManagementDataHolder.getInstance().getTaskService();
TaskManager taskManager;
try {
taskManager = taskService.getTaskManager(DEVICE_STATUS_MONITORING_TASK_TYPE);
return taskManager.isTaskScheduled(taskName);
} catch (TaskException e) {
throw new DeviceStatusTaskException("Error occurred while checking Device Status monitoring task for tenant " +
tenantId, e);
}
}
private int getTenantId() {
return PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
}
}

@ -45,7 +45,7 @@ public interface DeviceTaskManager {
// String getTaskImplementedClazz() throws DeviceMgtTaskException; // String getTaskImplementedClazz() throws DeviceMgtTaskException;
/** /**
* This method checks wheather task is enabled in config file. * This method checks weather task is enabled in config file.
* @return - return true or false * @return - return true or false
* @throws DeviceMgtTaskException * @throws DeviceMgtTaskException
*/ */

@ -77,4 +77,7 @@ public class TestDeviceManagementService implements DeviceManagementService {
return null; return null;
} }
public DeviceStatusTaskPluginConfig getDeviceStatusTaskPluginConfig() {
return null;
}
} }

@ -59,8 +59,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
private static final Log log = LogFactory.getLog(MonitoringManagerImpl.class); private static final Log log = LogFactory.getLog(MonitoringManagerImpl.class);
private static final String OPERATION_MONITOR = "MONITOR"; private static final String OPERATION_MONITOR = "MONITOR";
private static final String OPERATION_INFO = "DEVICE_INFO";
private static final String OPERATION_APP_LIST = "APPLICATION_LIST";
public MonitoringManagerImpl() { public MonitoringManagerImpl() {
this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO(); this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO();
@ -273,9 +272,6 @@ public class MonitoringManagerImpl implements MonitoringManager {
Map<Integer, Device> deviceIdsToAddOperation = new HashMap<>(); Map<Integer, Device> deviceIdsToAddOperation = new HashMap<>();
Map<Integer, Device> deviceIdsWithExistingOperation = new HashMap<>(); Map<Integer, Device> deviceIdsWithExistingOperation = new HashMap<>();
Map<Integer, Device> inactiveDeviceIds = new HashMap<>();
Map<Integer, Device> devicesToMarkUnreachable = new HashMap<>();
//Map<Integer, Integer> firstTimeDeviceIdsWithPolicyIds = new HashMap<>();
List<PolicyDeviceWrapper> firstTimeDevices = new ArrayList<>(); List<PolicyDeviceWrapper> firstTimeDevices = new ArrayList<>();
@ -293,14 +289,6 @@ public class MonitoringManagerImpl implements MonitoringManager {
} else { } else {
deviceIdsWithExistingOperation.put(complianceData.getDeviceId(), deviceIdsWithExistingOperation.put(complianceData.getDeviceId(),
deviceIds.get(complianceData.getDeviceId())); deviceIds.get(complianceData.getDeviceId()));
if (complianceData.getAttempts() >= policyConfiguration.getMinRetriesToMarkUnreachable()) {
devicesToMarkUnreachable.put(complianceData.getDeviceId(),
deviceIds.get(complianceData.getDeviceId()));
}
}
if (complianceData.getAttempts() >= policyConfiguration.getMinRetriesToMarkInactive()) {
inactiveDeviceIds.put(complianceData.getDeviceId(),
deviceIds.get(complianceData.getDeviceId()));
} }
} }
} }
@ -360,22 +348,6 @@ public class MonitoringManagerImpl implements MonitoringManager {
throw new PolicyComplianceException("Error occurred while adding monitoring operation to devices", e); throw new PolicyComplianceException("Error occurred while adding monitoring operation to devices", e);
} }
} }
// TODO : This should be uncommented, this is to mark the device as unreachable, But given the current
// implementation we are not able to do so.
if (!devicesToMarkUnreachable.isEmpty()) {
ComplianceDecisionPoint decisionPoint = new ComplianceDecisionPointImpl();
decisionPoint.setDevicesAsUnreachable(this.getDeviceIdentifiersFromDevices(
new ArrayList<>(devicesToMarkUnreachable.values())));
}
if (!inactiveDeviceIds.isEmpty()) {
ComplianceDecisionPoint decisionPoint = new ComplianceDecisionPointImpl();
decisionPoint.setDevicesAsInactive(this.getDeviceIdentifiersFromDevices(
new ArrayList<>(inactiveDeviceIds.values())));
}
} }
@Override @Override

@ -66,5 +66,8 @@
<ActivityListPageSize>20</ActivityListPageSize> <ActivityListPageSize>20</ActivityListPageSize>
<OperationListPageSize>20</OperationListPageSize> <OperationListPageSize>20</OperationListPageSize>
</PaginationConfiguration> </PaginationConfiguration>
<DeviceStatusTaskConfig>
<Enable>true</Enable>
</DeviceStatusTaskConfig>
</DeviceMgtConfiguration> </DeviceMgtConfiguration>

Loading…
Cancel
Save