Unit tests for service layer

revert-70aa11f8
manoj 10 years ago
commit 6daa71771c

@ -24,13 +24,6 @@ import java.util.List;
* device type plugin implementation intended to be managed through CDM.
*/
public interface DeviceManager {
/**
* Method to retrieve the provider type that implements DeviceManager interface.
*
* @return Returns provider type
*/
String getProviderType();
/**
* Method to return feature manager implementation associated with a particular platform-specific plugin.
*

@ -18,6 +18,7 @@
*/
package org.wso2.carbon.device.mgt.common.spi;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
@ -25,6 +26,19 @@ import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
* Composite interface that acts as the SPI exposing all device management as well as application management
* functionalities
*/
public interface DeviceManagementService extends DeviceManager, ApplicationManager {
public interface DeviceManagementService extends ApplicationManager {
/**
* Method to retrieve the provider type that implements DeviceManager interface.
*
* @return Returns provider type
*/
String getType();
void init() throws DeviceManagementException;
DeviceManager getDeviceManager();
ApplicationManager getApplicationManager();
}

@ -34,22 +34,28 @@ public class DeviceManagementPluginRepository {
}
public void addDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException {
String deviceType = provider.getProviderType();
String deviceType = provider.getType();
try {
/* Initializing Device Management Service Provider */
provider.init();
DeviceManagerUtil.registerDeviceType(deviceType);
} catch (DeviceManagementException e) {
throw new DeviceManagementException("Error occurred while adding device management provider '" +
deviceType + "'");
}
providers.put(deviceType, provider);
System.out.println("@plugin Repo:"+deviceType);
System.out.println("@plugin Repo:"+providers.size());
}
public void removeDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException {
String deviceType = provider.getProviderType();
String deviceType = provider.getType();
providers.remove(deviceType);
}
public DeviceManagementService getDeviceManagementService(String type) {
System.out.println("@plugin get:"+providers.get(type).toString());
return providers.get(type);
}

@ -226,7 +226,7 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
pluginRepository.addDeviceManagementProvider(deviceManagementService);
} catch (DeviceManagementException e) {
log.error("Error occurred while registering device management plugin '" +
deviceManagementService.getProviderType() + "'", e);
deviceManagementService.getType() + "'", e);
}
}
@ -236,7 +236,7 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
pluginRepository.removeDeviceManagementProvider(deviceManagementService);
} catch (DeviceManagementException e) {
log.error("Error occurred while un-registering device management plugin '" +
deviceManagementService.getProviderType() + "'", e);
deviceManagementService.getType() + "'", e);
}
}
}

@ -242,7 +242,7 @@ public class DeviceManagementServiceComponent {
protected void setDeviceManagementService(DeviceManagementService deviceManagementService) {
if (log.isDebugEnabled()) {
log.debug("Setting Device Management Service Provider: '" +
deviceManagementService.getProviderType() + "'");
deviceManagementService.getType() + "'");
}
synchronized (LOCK) {
deviceManagers.add(deviceManagementService);
@ -260,7 +260,7 @@ public class DeviceManagementServiceComponent {
protected void unsetDeviceManagementService(DeviceManagementService deviceManagementService) {
if (log.isDebugEnabled()) {
log.debug("Un setting Device Management Service Provider : '" +
deviceManagementService.getProviderType() + "'");
deviceManagementService.getType() + "'");
}
for (PluginInitializationListener listener : listeners) {
listener.unregisterDeviceManagementService(deviceManagementService);

@ -21,7 +21,6 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
@ -37,6 +36,7 @@ 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.EmailServiceDataHolder;
import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.user.api.UserStoreException;
import java.io.IOException;
@ -72,7 +72,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
* This constructor calls from unit tests
* @param pluginRepo
*/
public DeviceManagementProviderServiceImpl(DeviceManagementPluginRepository pluginRepo, boolean test){
DeviceManagementProviderServiceImpl(DeviceManagementPluginRepository pluginRepo, boolean test){
this.pluginRepository = pluginRepo;
initDataAccessObjects();
isTest = test;
@ -84,11 +84,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
this.enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
}
@Override
public String getProviderType() {
return null;
}
@Override
public FeatureManager getFeatureManager() {
return null;
@ -97,14 +92,17 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
@Override
public FeatureManager getFeatureManager(String type) {
DeviceManager dms =
this.getPluginRepository().getDeviceManagementService(type);
this.getPluginRepository().getDeviceManagementService(type).getDeviceManager();
return dms.getFeatureManager();
}
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
DeviceManager dms = this.getPluginRepository().getDeviceManagementService(device.getType());
DeviceManager dms =
this.getPluginRepository().getDeviceManagementService(device.getType()).getDeviceManager();
System.out.println("dms________"+device.getType());
boolean status = dms.enrollDevice(device);
try {
if (dms.isClaimable(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()))) {
@ -150,7 +148,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
DeviceManager dms =
this.getPluginRepository().getDeviceManagementService(device.getType());
this.getPluginRepository().getDeviceManagementService(device.getType()).getDeviceManager();
boolean status = dms.modifyEnrollment(device);
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
@ -183,7 +181,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
DeviceManager dms =
this.getPluginRepository().getDeviceManagementService(deviceId.getType());
this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager();
try {
Device device = deviceDAO.getDevice(deviceId,tenantId);
DeviceType deviceType = deviceTypeDAO.getDeviceType(device.getType());
@ -204,14 +202,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
DeviceManager dms =
this.getPluginRepository().getDeviceManagementService(deviceId.getType());
this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager();
return dms.isEnrolled(deviceId);
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
DeviceManager dms =
this.getPluginRepository().getDeviceManagementService(deviceId.getType());
this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager();
return dms.isActive(deviceId);
}
@ -219,7 +217,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
public boolean setActive(DeviceIdentifier deviceId, boolean status)
throws DeviceManagementException {
DeviceManager dms =
this.getPluginRepository().getDeviceManagementService(deviceId.getType());
this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager();
return dms.setActive(deviceId, status);
}
@ -243,7 +241,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
for (Device device : allDevices) {
Device dmsDevice =
this.getPluginRepository().getDeviceManagementService(device.getType()).getDevice(
this.getPluginRepository().getDeviceManagementService(
device.getType()).getDeviceManager().getDevice(
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
device.setFeatures(dmsDevice.getFeatures());
device.setProperties(dmsDevice.getProperties());
@ -273,7 +272,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
for (Device device : allDevices) {
Device dmsDevice =
this.getPluginRepository().getDeviceManagementService(device.getType()).getDevice(
this.getPluginRepository().getDeviceManagementService(
device.getType()).getDeviceManager().getDevice(
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
device.setFeatures(dmsDevice.getFeatures());
device.setProperties(dmsDevice.getProperties());
@ -423,7 +423,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
}
if (device != null) {
DeviceManager dms = this.getPluginRepository().getDeviceManagementService(deviceId.getType());
DeviceManager dms =
this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager();
Device pluginSpecificInfo = dms.getDevice(deviceId);
device.setProperties(pluginSpecificInfo.getProperties());
device.setFeatures(pluginSpecificInfo.getFeatures());
@ -434,7 +435,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException {
DeviceManager dms =
this.getPluginRepository().getDeviceManagementService(device.getType());
this.getPluginRepository().getDeviceManagementService(device.getType()).getDeviceManager();
return dms.updateDeviceInfo(deviceIdentifier, device);
}
@ -442,14 +443,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
DeviceManager dms =
this.getPluginRepository().getDeviceManagementService(deviceId.getType());
this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager();
return dms.setOwnership(deviceId, ownershipType);
}
@Override
public boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException {
DeviceManager dms =
this.getPluginRepository().getDeviceManagementService(deviceId.getType());
this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager();
return dms.isClaimable(deviceId);
}
@ -568,7 +569,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
for (Device device : userDevices) {
Device dmsDevice =
this.getPluginRepository().getDeviceManagementService(device.getType()).getDevice(
this.getPluginRepository().getDeviceManagementService(
device.getType()).getDeviceManager().getDevice(
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
device.setFeatures(dmsDevice.getFeatures());
device.setProperties(dmsDevice.getProperties());
@ -585,9 +587,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
String[] users;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
users =
DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(
tenantId).getUserStoreManager().getUserListOfRole(role);
users = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager().getUserListOfRole(role);
} catch (UserStoreException e) {
throw new DeviceManagementException("Error occurred while obtaining the users, who are assigned " +
"with the role '" + role + "'", e);
@ -610,7 +611,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
for (Device device : userDevices) {
Device dmsDevice =
this.getPluginRepository().getDeviceManagementService(device.getType()).getDevice(
this.getPluginRepository().getDeviceManagementService(
device.getType()).getDeviceManager().getDevice(
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
device.setFeatures(dmsDevice.getFeatures());
device.setProperties(dmsDevice.getProperties());
@ -657,7 +659,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
for (Device device : allDevices) {
Device dmsDevice =
this.getPluginRepository().getDeviceManagementService(device.getType()).getDevice(
this.getPluginRepository().getDeviceManagementService(
device.getType()).getDeviceManager().getDevice(
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
device.setFeatures(dmsDevice.getFeatures());
device.setProperties(dmsDevice.getProperties());
@ -689,7 +692,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
pluginRepository.addDeviceManagementProvider(deviceManagementService);
} catch (DeviceManagementException e) {
log.error("Error occurred while registering device management plugin '" +
deviceManagementService.getProviderType() + "'", e);
deviceManagementService.getType() + "'", e);
}
}
@ -699,7 +702,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
pluginRepository.removeDeviceManagementProvider(deviceManagementService);
} catch (DeviceManagementException e) {
log.error("Error occurred while un-registering device management plugin '" +
deviceManagementService.getProviderType() + "'", e);
deviceManagementService.getType() + "'", e);
}
}
@ -709,7 +712,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
int tenant = 0;
if (isTest){
tenant = org.wso2.carbon.device.mgt.core.common.;
tenant = DeviceManagerUtil.currentTenant.get();
}else{
tenant = CarbonContext.getThreadLocalCarbonContext().getTenantId();
}

@ -49,6 +49,7 @@ import java.util.*;
public final class DeviceManagerUtil {
private static final Log log = LogFactory.getLog(DeviceManagerUtil.class);
public static ThreadLocal<Integer> currentTenant = new ThreadLocal<Integer>();
enum HTTPMethod {
GET, POST, DELETE, PUT, OPTIONS
@ -215,4 +216,5 @@ public final class DeviceManagerUtil {
return uriTemplates;
}
}

@ -23,6 +23,7 @@ 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.TestDataHolder;
public class DeviceManagementRepositoryTests {
@ -35,27 +36,27 @@ public class DeviceManagementRepositoryTests {
@Test
public void testAddDeviceManagementService() {
DeviceManagementService sourceProvider = new TestDeviceManagementService();
DeviceManagementService sourceProvider = new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE);
try {
this.getRepository().addDeviceManagementProvider(sourceProvider);
} catch (DeviceManagementException e) {
Assert.fail("Unexpected error occurred while invoking addDeviceManagementProvider functionality", e);
}
DeviceManager targetProvider =
this.getRepository().getDeviceManagementService(TestDeviceManagementService.DEVICE_TYPE_TEST);
Assert.assertEquals(targetProvider.getProviderType(), sourceProvider.getProviderType());
DeviceManagementService targetProvider =
this.getRepository().getDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE);
Assert.assertEquals(targetProvider.getType(), sourceProvider.getType());
}
@Test(dependsOnMethods = "testAddDeviceManagementService")
public void testRemoveDeviceManagementService() {
DeviceManagementService sourceProvider = new TestDeviceManagementService();
DeviceManagementService sourceProvider = new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE);
try {
this.getRepository().removeDeviceManagementProvider(sourceProvider);
} catch (DeviceManagementException e) {
Assert.fail("Unexpected error occurred while invoking removeDeviceManagementProvider functionality", e);
}
DeviceManager targetProvider =
this.getRepository().getDeviceManagementService(TestDeviceManagementService.DEVICE_TYPE_TEST);
DeviceManagementService targetProvider =
this.getRepository().getDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE);
Assert.assertNull(targetProvider);
}

@ -20,108 +20,73 @@ package org.wso2.carbon.device.mgt.core;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
import java.util.List;
public class TestDeviceManagementService implements DeviceManagementService {
public class TestDeviceManagementService implements DeviceManager {
public static final String DEVICE_TYPE_TEST = TestDataHolder.TEST_DEVICE_TYPE;
private String providerType;
@Override
public String getProviderType() {
return TestDeviceManagementService.DEVICE_TYPE_TEST;
public TestDeviceManagementService(String deviceType){
providerType = deviceType;
}
@Override
public FeatureManager getFeatureManager() {
@Override public FeatureManager getFeatureManager() {
return null;
}
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
@Override public boolean enrollDevice(Device device) throws DeviceManagementException {
return false;
}
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
@Override public boolean modifyEnrollment(Device device) throws DeviceManagementException {
return false;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
@Override public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
return false;
}
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
@Override public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
return false;
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
@Override public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
return false;
}
@Override
public boolean setActive(DeviceIdentifier deviceId, boolean status) throws DeviceManagementException {
@Override public boolean setActive(DeviceIdentifier deviceId, boolean status) throws DeviceManagementException {
return false;
}
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
@Override public List<Device> getAllDevices() throws DeviceManagementException {
return null;
}
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
@Override public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
return null;
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceId, Device device) throws DeviceManagementException {
@Override public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device)
throws DeviceManagementException {
return false;
}
@Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) throws DeviceManagementException {
@Override public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
return false;
}
@Override
public boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException {
@Override public boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException {
@Override public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, EnrolmentInfo.Status status)
throws DeviceManagementException {
return false;
}
@Override
public Application[] getApplications(String domain, int pageNumber,
int size) throws ApplicationManagementException {
return new Application[0];
}
@Override
public void updateApplicationStatus(DeviceIdentifier deviceId, Application application,
String status) throws ApplicationManagementException {
}
@Override
public String getApplicationStatus(DeviceIdentifier deviceId,
Application application) throws ApplicationManagementException {
return null;
}
@Override
public void installApplication(Operation operation, List<DeviceIdentifier> deviceIdentifiers)
throws ApplicationManagementException {
}
}

@ -27,7 +27,7 @@ public class TestDataHolder {
enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED);
device.setEnrolmentInfo(enrolmentInfo);
device.setDescription("Test Description");
device.setDeviceIdentifier("1234");
device.setDeviceIdentifier("12345");
device.setType(deviceType);
return device;

@ -64,7 +64,7 @@ public class DevicePersistTests extends BaseDeviceManagementTest {
}
}
int targetTypeId = -1;
Integer targetTypeId = null;
try {
targetTypeId = this.getDeviceTypeId(TestDataHolder.TEST_DEVICE_TYPE);
} catch (DeviceManagementDAOException e) {
@ -72,7 +72,6 @@ public class DevicePersistTests extends BaseDeviceManagementTest {
log.error(msg, e);
Assert.fail(msg, e);
}
Assert.assertNotNull(targetTypeId, "Device Type Id is null");
deviceType.setId(targetTypeId);
TestDataHolder.initialTestDeviceType = deviceType;
@ -82,7 +81,7 @@ public class DevicePersistTests extends BaseDeviceManagementTest {
public void testAddDeviceTest() {
int tenantId = TestDataHolder.SUPER_TENANT_ID;
Device device = TestDataHolder.generateDummyDeviceData("ios");
Device device = TestDataHolder.generateDummyDeviceData(TestDataHolder.TEST_DEVICE_TYPE);
try {
DeviceManagementDAOFactory.openConnection();
@ -143,18 +142,17 @@ public class DevicePersistTests extends BaseDeviceManagementTest {
}
}
private int getDeviceTypeId(String deviceName) throws DeviceManagementDAOException {
private int getDeviceTypeId(String deviceTypeName) throws DeviceManagementDAOException {
int id = -1;
Connection conn = null;
PreparedStatement stmt = null;
String sql = "SELECT ID, NAME FROM DM_DEVICE_TYPE WHERE NAME = ?";
DeviceType deviceType = TestDataHolder.generateDeviceTypeData("ios");
try {
Assert.assertNotNull(getDataSource(), "Data Source is not initialized properly");
conn = getDataSource().getConnection();
stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceType.getName());
stmt.setString(1, deviceTypeName);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {

@ -31,11 +31,6 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes
@Override
public void init() throws Exception {
initDatSource();
DeviceManagementPluginRepository deviceManagementPluginRepository = new DeviceManagementPluginRepository();
TestDeviceManagementService testDeviceManagementService = new TestDeviceManagementService();
deviceManagementPluginRepository.addDeviceManagementProvider(testDeviceManagementService);
deviceManagementProviderService = new DeviceManagementProviderServiceImpl(deviceManagementPluginRepository,
true);
}
@ -44,6 +39,12 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes
public void testEnrollment() {
try {
DeviceManagementPluginRepository deviceManagementPluginRepository = new DeviceManagementPluginRepository();
TestDeviceManagementService testDeviceManagementService = new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE);
deviceManagementPluginRepository.addDeviceManagementProvider(testDeviceManagementService);
deviceManagementProviderService = new DeviceManagementProviderServiceImpl(deviceManagementPluginRepository,
true);
DeviceManagerUtil.registerDeviceType(TestDataHolder.TEST_DEVICE_TYPE);
TestDataHolder.tenant.set(TestDataHolder.SUPER_TENANT_ID);
Device device = TestDataHolder.generateDummyDeviceData(TestDataHolder.TEST_DEVICE_TYPE);

@ -18,8 +18,12 @@
*/
package org.wso2.carbon.identity.oauth.extension;
public class ApplicationConstants {
public final class ApplicationConstants {
public static class ClientMetadata {
private ClientMetadata() {
throw new AssertionError();
}
public static final String OAUTH_CLIENT_ID = "client_id"; //this means consumer key
public static final String OAUTH_CLIENT_SECRET = "client_secret";
public static final String OAUTH_REDIRECT_URIS = "redirect_uris";
@ -46,5 +50,6 @@ public class ApplicationConstants {
public static final String OAUTH_CLIENT_USERNAME = "username";
public static final String OAUTH_CLIENT_APPLICATION = "application";
public static final String VALIDITY_PERIOD = "validityPeriod";
}
}

@ -16,7 +16,7 @@
* under the License.
*
*/
package org.wso2.carbon.identity.oauth.extension.impl;
package org.wso2.carbon.identity.oauth.extension;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -35,66 +35,16 @@ import org.wso2.carbon.identity.application.mgt.ApplicationManagementService;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.oauth.OAuthAdminService;
import org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO;
import org.wso2.carbon.identity.oauth.extension.ApplicationConstants;
import org.wso2.carbon.identity.oauth.extension.OAuthApplicationInfo;
import org.wso2.carbon.identity.oauth.extension.RegistrationProfile;
import org.wso2.carbon.identity.oauth.extension.RegistrationService;
import org.wso2.carbon.identity.oauth.extension.UnregistrationProfile;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.identity.oauth.extension.profile.RegistrationProfile;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Arrays;
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ClientRegistrationServiceImpl implements RegistrationService {
public class DynamicClientRegistrationUtil {
private static final Log log = LogFactory.getLog(ClientRegistrationServiceImpl.class);
private static final Log log = LogFactory.getLog(DynamicClientRegistrationUtil.class);
@POST
@Override
public Response register(RegistrationProfile profile) {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
OAuthApplicationInfo info = this.registerApplication(profile);
return Response.status(Response.Status.ACCEPTED).entity(info.toString()).build();
} catch (APIManagementException e) {
String msg = "Error occurred while registering client '" + profile.getClientName() + "'";
log.error(msg, e);
return Response.serverError().entity(msg).build();
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@DELETE
@Override
public Response unregister(UnregistrationProfile profile) {
String applicationName = profile.getApplicationName();
String consumerKey = profile.getConsumerKey();
String userId = profile.getUserId();
try {
this.unregisterApplication(userId, applicationName, consumerKey);
return Response.status(Response.Status.ACCEPTED).build();
} catch (APIManagementException e) {
String msg = "Error occurred while unregistering client '" + applicationName + "'";
log.error(msg, e);
return Response.serverError().entity(msg).build();
}
}
private OAuthApplicationInfo registerApplication(RegistrationProfile profile) throws APIManagementException {
public static OAuthApplicationInfo registerApplication(RegistrationProfile profile) throws APIManagementException {
OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
//Subscriber's name should be passed as a parameter, since it's under the subscriber the OAuth App is created.
@ -115,7 +65,7 @@ public class ClientRegistrationServiceImpl implements RegistrationService {
oAuthApplicationInfo.addParameter("tokenScope", Arrays.toString(tokenScopes));
OAuthApplicationInfo info;
try {
info = this.createOAuthApplication(userId, applicationName, callBackURL, grantType);
info = createOAuthApplication(userId, applicationName, callBackURL, grantType);
} catch (Exception e) {
throw new APIManagementException("Can not create OAuth application : " + applicationName, e);
}
@ -131,26 +81,24 @@ public class ClientRegistrationServiceImpl implements RegistrationService {
try {
JSONObject jsonObject = new JSONObject(info.getJsonString());
if (jsonObject.has(ApplicationConstants.OAUTH_REDIRECT_URIS)) {
oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_REDIRECT_URIS, jsonObject.get(ApplicationConstants.OAUTH_REDIRECT_URIS));
if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)) {
oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS,
jsonObject.get(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS));
}
if (jsonObject.has(ApplicationConstants.OAUTH_CLIENT_GRANT)) {
oAuthApplicationInfo.addParameter(ApplicationConstants.
OAUTH_CLIENT_GRANT, jsonObject.get(ApplicationConstants.OAUTH_CLIENT_GRANT));
if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)) {
oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata.
OAUTH_CLIENT_GRANT, jsonObject.get(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT));
}
} catch (JSONException e) {
throw new APIManagementException("Can not retrieve information of the created OAuth application", e);
}
return oAuthApplicationInfo;
}
public OAuthApplicationInfo createOAuthApplication(
public static OAuthApplicationInfo createOAuthApplication(
String userId, String applicationName, String callbackUrl, String grantType)
throws APIManagementException, IdentityException {
if (userId == null || userId.isEmpty()) {
return null;
}
@ -167,7 +115,6 @@ public class ClientRegistrationServiceImpl implements RegistrationService {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName);
try {
// Append the username before Application name to make application name unique across two users.
applicationName = userName + "_" + applicationName;
@ -180,7 +127,6 @@ public class ClientRegistrationServiceImpl implements RegistrationService {
appMgtService.createApplication(serviceProvider);
ServiceProvider createdServiceProvider = appMgtService.getApplication(applicationName);
if (createdServiceProvider == null) {
throw new APIManagementException("Couldn't create Service Provider Application " + applicationName);
}
@ -189,17 +135,23 @@ public class ClientRegistrationServiceImpl implements RegistrationService {
OAuthAdminService oAuthAdminService = new OAuthAdminService();
OAuthConsumerAppDTO oAuthConsumerAppDTO = new OAuthConsumerAppDTO();
oAuthConsumerAppDTO.setApplicationName(applicationName);
oAuthConsumerAppDTO.setCallbackUrl(callbackUrl);
oAuthConsumerAppDTO.setGrantTypes(grantType);
if (log.isDebugEnabled()) {
log.debug("Creating OAuth App " + applicationName);
}
oAuthAdminService.registerOAuthApplicationData(oAuthConsumerAppDTO);
if (log.isDebugEnabled()) {
log.debug("Created OAuth App " + applicationName);
}
OAuthConsumerAppDTO createdApp = oAuthAdminService.getOAuthApplicationDataByAppName(oAuthConsumerAppDTO
.getApplicationName());
if (log.isDebugEnabled()) {
log.debug("Retrieved Details for OAuth App " + createdApp.getApplicationName());
}
// Set the OAuthApp in InboundAuthenticationConfig
InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig();
InboundAuthenticationRequestConfig[] inboundAuthenticationRequestConfigs = new
@ -225,20 +177,17 @@ public class ClientRegistrationServiceImpl implements RegistrationService {
// Update the Service Provider app to add OAuthApp as an Inbound Authentication Config
appMgtService.updateApplication(createdServiceProvider);
OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
oAuthApplicationInfo.setClientId(createdApp.getOauthConsumerKey());
oAuthApplicationInfo.setCallBackURL(createdApp.getCallbackUrl());
oAuthApplicationInfo.setClientSecret(createdApp.getOauthConsumerSecret());
oAuthApplicationInfo.setClientName(createdApp.getApplicationName());
oAuthApplicationInfo.addParameter(ApplicationConstants.
OAUTH_REDIRECT_URIS, createdApp.getCallbackUrl());
oAuthApplicationInfo.addParameter(ApplicationConstants.
OAUTH_CLIENT_GRANT, createdApp.getGrantTypes());
oAuthApplicationInfo.addParameter(
ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, createdApp.getCallbackUrl());
oAuthApplicationInfo.addParameter(
ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT, createdApp.getGrantTypes());
return oAuthApplicationInfo;
} catch (IdentityApplicationManagementException e) {
APIUtil.handleException("Error occurred while creating ServiceProvider for app " + applicationName, e);
} catch (Exception e) {
@ -250,9 +199,8 @@ public class ClientRegistrationServiceImpl implements RegistrationService {
return null;
}
public void unregisterApplication(String userId, String applicationName, String consumerKey)
throws APIManagementException {
public static void unregisterApplication(String userId, String applicationName,
String consumerKey) throws APIManagementException {
String tenantDomain = MultitenantUtils.getTenantDomain(userId);
String baseUser = CarbonContext.getThreadLocalCarbonContext().getUsername();
String userName = MultitenantUtils.getTenantAwareUsername(userId);
@ -262,7 +210,8 @@ public class ClientRegistrationServiceImpl implements RegistrationService {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName);
if (userId == null || userId.isEmpty()) {
throw new APIManagementException("Error occurred while unregistering Application: userId cannot be null/empty");
throw new APIManagementException("Error occurred while unregistering Application: userId cannot " +
"be null/empty");
}
try {
OAuthAdminService oAuthAdminService = new OAuthAdminService();
@ -291,4 +240,5 @@ public class ClientRegistrationServiceImpl implements RegistrationService {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(baseUser);
}
}
}

@ -0,0 +1,71 @@
/*
* 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.identity.oauth.extension;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class FaultMessageBodyWriter implements MessageBodyWriter<FaultResponse> {
private static final String UTF_8 = "UTF-8";
@Override
public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return (FaultResponse.class == type);
}
@Override
public long getSize(FaultResponse faultResponse, Class<?> aClass, Type type, Annotation[] annotations,
MediaType mediaType) {
return -1;
}
@Override
public void writeTo(FaultResponse faultResponse, Class<?> aClass, Type type, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> stringObjectMultivaluedMap,
OutputStream outputStream) throws IOException, WebApplicationException {
try (OutputStreamWriter writer = new OutputStreamWriter(outputStream, UTF_8)) {
JsonObject response = new JsonObject();
response.addProperty("error", faultResponse.getCode().getValue());
response.addProperty("error_description", faultResponse.getDescription());
getGson().toJson(response, type, writer);
}
}
private Gson getGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
return gsonBuilder.create();
}
}

@ -0,0 +1,39 @@
/*
* 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.identity.oauth.extension;
public class FaultResponse {
private RegistrationService.ErrorCode code;
private String description;
public FaultResponse(RegistrationService.ErrorCode code, String description) {
this.code = code;
this.description = description;
}
public RegistrationService.ErrorCode getCode() {
return code;
}
public String getDescription() {
return description;
}
}

@ -27,24 +27,16 @@ import java.util.Map;
public class OAuthApplicationInfo {
private String clientId;
private String clientName;
private String callBackURL;
private String clientSecret;
private Map<String,Object> parameters = new HashMap<String, Object>();
/**
* get client Id (consumer id)
* @return clientId
*/
public String getClientId() {
return clientId;
}
/**
* set client Id
* @param clientId
*/
public void setClientId(String clientId) {
this.clientId = clientId;
}
@ -57,18 +49,10 @@ public class OAuthApplicationInfo {
this.clientSecret = clientSecret;
}
/**
* Set client Name of OAuthApplication.
* @param clientName
*/
public void setClientName(String clientName){
this.clientName = clientName;
}
/**
* Set callback URL of OAuthapplication.
* @param callBackURL
*/
public void setCallBackURL(String callBackURL){
this.callBackURL = callBackURL;
}
@ -82,9 +66,7 @@ public class OAuthApplicationInfo {
}
public String getJsonString(){
return JSONObject.toJSONString(parameters);
}
public String getClientName(){

@ -18,6 +18,9 @@
*/
package org.wso2.carbon.identity.oauth.extension;
import org.wso2.carbon.identity.oauth.extension.profile.RegistrationProfile;
import org.wso2.carbon.identity.oauth.extension.profile.UnregistrationProfile;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
@ -29,6 +32,19 @@ import javax.ws.rs.core.Response;
@Consumes(MediaType.APPLICATION_JSON)
public interface RegistrationService {
enum ErrorCode {
INVALID_URI("invalid_redirect_uri"), INVALID_CLIENT_METADATA("invalid_client_metadata");
private String value;
private ErrorCode(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
@POST
Response register(RegistrationProfile profile);

@ -0,0 +1,33 @@
/*
* 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.identity.oauth.extension.impl;
import org.wso2.carbon.identity.oauth.extension.ConfigurationService;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
public class ConfigurationServiceImpl implements ConfigurationService {
@Override
public Response getProfile(@PathParam("client_id") String clientId) {
return null;
}
}

@ -0,0 +1,95 @@
/*
* 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.identity.oauth.extension.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException;
import org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.Property;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.application.mgt.ApplicationManagementService;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.oauth.OAuthAdminService;
import org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO;
import org.wso2.carbon.identity.oauth.extension.*;
import org.wso2.carbon.identity.oauth.extension.profile.RegistrationProfile;
import org.wso2.carbon.identity.oauth.extension.profile.UnregistrationProfile;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Arrays;
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class RegistrationServiceImpl implements RegistrationService {
private static final Log log = LogFactory.getLog(RegistrationServiceImpl.class);
@POST
@Override
public Response register(RegistrationProfile profile) {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
OAuthApplicationInfo info = DynamicClientRegistrationUtil.registerApplication(profile);
return Response.status(Response.Status.ACCEPTED).entity(info.toString()).build();
} catch (APIManagementException e) {
String msg = "Error occurred while registering client '" + profile.getClientName() + "'";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(
new FaultResponse(ErrorCode.INVALID_CLIENT_METADATA, msg)).build();
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@DELETE
@Override
public Response unregister(UnregistrationProfile profile) {
String applicationName = profile.getApplicationName();
String consumerKey = profile.getConsumerKey();
String userId = profile.getUserId();
try {
DynamicClientRegistrationUtil.unregisterApplication(userId, applicationName, consumerKey);
return Response.status(Response.Status.ACCEPTED).build();
} catch (APIManagementException e) {
String msg = "Error occurred while un-registering client '" + applicationName + "'";
log.error(msg, e);
return Response.serverError().entity(new FaultResponse(ErrorCode.INVALID_CLIENT_METADATA, msg)).build();
}
}
}

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.identity.oauth.extension;
package org.wso2.carbon.identity.oauth.extension.profile;
/**
* This bean class represents the data that are required to unregister
@ -48,4 +48,5 @@ public class UnregistrationProfile {
public void setUserId(String userId) {
this.userId = userId;
}
}

@ -33,10 +33,12 @@
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="faultResponseWriter"/>
</jaxrs:providers>
</jaxrs:server>
<bean id="RegistrationServiceBean" class="org.wso2.carbon.identity.oauth.extension.impl.ClientRegistrationServiceImpl"/>
<bean id="RegistrationServiceBean" class="org.wso2.carbon.identity.oauth.extension.impl.RegistrationServiceImpl"/>
<bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
<bean id="faultResponseWriter" class="org.wso2.carbon.identity.oauth.extension.FaultMessageBodyWriter"/>
</beans>

@ -19,6 +19,8 @@
package org.wso2.carbon.policy.mgt.common.monitor;
import org.wso2.carbon.policy.mgt.common.Policy;
import java.util.List;
public class ComplianceData {
@ -30,6 +32,13 @@ public class ComplianceData {
private boolean status;
private String message;
/**
* This parameter is to inform the policy core, weather related device type plugins does need the full policy or
* the part which is none compliance.
*/
private boolean completePolicy;
private Policy policy;
public int getId() {
return id;
}
@ -77,4 +86,20 @@ public class ComplianceData {
public void setMessage(String message) {
this.message = message;
}
public boolean isCompletePolicy() {
return completePolicy;
}
public void setCompletePolicy(boolean completePolicy) {
this.completePolicy = completePolicy;
}
public Policy getPolicy() {
return policy;
}
public void setPolicy(Policy policy) {
this.policy = policy;
}
}

@ -31,7 +31,8 @@ public interface ComplianceDecisionPoint {
void setDeviceAsReachable(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException;
void reEnforcePolicy(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException;
void reEnforcePolicy(DeviceIdentifier deviceIdentifier, ComplianceData complianceData) throws
PolicyComplianceException;
void markDeviceAsNoneCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException;
@ -41,7 +42,7 @@ public interface ComplianceDecisionPoint {
void activateDevice(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException;
void validateDevicePolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy) throws
void validateDevicePolicyCompliance(DeviceIdentifier deviceIdentifier, ComplianceData complianceData) throws
PolicyComplianceException;

@ -19,10 +19,11 @@
package org.wso2.carbon.policy.mgt.common;
import java.io.Serializable;
import org.wso2.carbon.device.mgt.common.Feature;
public class ProfileFeature implements Serializable {
private static final long serialVersionUID = 19981018L;
private int id;
private String featureCode;
private int profileId;

@ -21,6 +21,7 @@ package org.wso2.carbon.policy.mgt.common.spi;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature;
import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException;
import org.wso2.carbon.policy.mgt.common.Policy;
@ -31,6 +32,6 @@ public interface PolicyMonitoringService {
void notifyDevices(List<Device> devices) throws PolicyComplianceException;
List<ComplianceFeature> checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy, Object response)
ComplianceData checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy, Object response)
throws PolicyComplianceException;
}

@ -37,5 +37,9 @@ public interface MonitoringDAO {
List<ComplianceFeature> getNoneComplianceFeatures(int policyComplianceStatusId) throws MonitoringDAOException;
void deleteNoneComplianceData(int deviceId) throws MonitoringDAOException;
void deleteNoneComplianceData(int policyComplianceStatusId) throws MonitoringDAOException;
void updateAttempts(int deviceId, boolean reset) throws MonitoringDAOException;
}

@ -80,9 +80,10 @@ public class MonitoringDAOImpl implements MonitoringDAO {
PreparedStatement stmt = null;
try {
conn = this.getConnection();
String query = "DELETE FROM DM_POLICY_COMPLIANCE_STATUS WHERE DEVICE_ID = ?";
String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET STATUS = ? WHERE DEVICE_ID = ?";
stmt = conn.prepareStatement(query);
stmt.setInt(1, deviceId);
stmt.setInt(1, 1);
stmt.setInt(2, deviceId);
stmt.executeUpdate();
@ -193,15 +194,15 @@ public class MonitoringDAOImpl implements MonitoringDAO {
}
@Override
public void deleteNoneComplianceData(int deviceId) throws MonitoringDAOException {
public void deleteNoneComplianceData(int policyComplianceStatusId) throws MonitoringDAOException {
Connection conn;
PreparedStatement stmt = null;
try {
conn = this.getConnection();
String query = "DELETE FROM DM_POLICY_COMPLIANCE_STATUS WHERE DEVICE_ID = ?";
String query = "DELETE FROM DM_POLICY_COMPLIANCE_FEATURES WHERE COMPLIANCE_STATUS_ID = ?";
stmt = conn.prepareStatement(query);
stmt.setInt(1, deviceId);
stmt.setInt(1, policyComplianceStatusId);
stmt.executeUpdate();
} catch (SQLException e) {
@ -214,6 +215,11 @@ public class MonitoringDAOImpl implements MonitoringDAO {
}
@Override
public void updateAttempts(int deviceId, boolean reset) throws MonitoringDAOException {
}
private Connection getConnection() throws MonitoringDAOException {
try {

@ -21,15 +21,31 @@ package org.wso2.carbon.policy.mgt.core.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.EnrolmentDAO;
import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceDecisionPoint;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature;
import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import java.util.ArrayList;
import java.util.List;
public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint {
@ -54,41 +70,191 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint {
@Override
public void setDeviceAsUnreachable(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException {
try {
int tenantId = PolicyManagerUtil.getTenantId();
Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);
enrolmentDAO.setStatus(device.getId(), device.getEnrolmentInfo().getOwner(),
EnrolmentInfo.Status.UNREACHABLE, tenantId);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while setting the device as unreachable for " +
deviceIdentifier.getId() + " - " + deviceIdentifier.getType();
log.error(msg, e);
throw new PolicyComplianceException(msg, e);
}
}
@Override
public void setDeviceAsReachable(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException {
try {
int tenantId = PolicyManagerUtil.getTenantId();
Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);
enrolmentDAO.setStatus(device.getId(), device.getEnrolmentInfo().getOwner(),
EnrolmentInfo.Status.ACTIVE, tenantId);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while setting the device as reachable for " +
deviceIdentifier.getId() + " - " + deviceIdentifier.getType();
log.error(msg, e);
throw new PolicyComplianceException(msg, e);
}
}
@Override
public void reEnforcePolicy(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException {
public void reEnforcePolicy(DeviceIdentifier deviceIdentifier, ComplianceData complianceData) throws
PolicyComplianceException {
try {
Policy policy = complianceData.getPolicy();
if (policy != null) {
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<DeviceIdentifier>();
deviceIdentifiers.add(deviceIdentifier);
List<ProfileOperation> profileOperationList = new ArrayList<ProfileOperation>();
PolicyOperation policyOperation = new PolicyOperation();
policyOperation.setEnabled(true);
policyOperation.setType(Operation.Type.POLICY);
policyOperation.setCode(PolicyOperation.POLICY_OPERATION_CODE);
if (complianceData.isCompletePolicy()) {
List<ProfileFeature> effectiveFeatures = policy.getProfile().getProfileFeaturesList();
for (ProfileFeature feature : effectiveFeatures) {
ProfileOperation profileOperation = new ProfileOperation();
profileOperation.setCode(feature.getFeatureCode());
profileOperation.setEnabled(true);
profileOperation.setStatus(Operation.Status.PENDING);
profileOperation.setType(Operation.Type.PROFILE);
profileOperation.setPayLoad(feature.getContent());
profileOperationList.add(profileOperation);
}
} else {
List<ComplianceFeature> noneComplianceFeatures = complianceData.getComplianceFeatures();
for (ComplianceFeature feature : noneComplianceFeatures) {
ProfileOperation profileOperation = new ProfileOperation();
profileOperation.setCode(feature.getFeatureCode());
profileOperation.setEnabled(true);
profileOperation.setStatus(Operation.Status.PENDING);
profileOperation.setType(Operation.Type.PROFILE);
profileOperation.setPayLoad(feature.getFeature().getContent());
profileOperationList.add(profileOperation);
}
}
policyOperation.setProfileOperations(profileOperationList);
policyOperation.setPayLoad(policyOperation.getProfileOperations());
PolicyManagementDataHolder.getInstance().getDeviceManagementService().
addOperation(policyOperation, deviceIdentifiers);
}
} catch (OperationManagementException e) {
String msg = "Error occurred while re-enforcing the policy to device " + deviceIdentifier.getId() + " - " +
deviceIdentifier.getType();
log.error(msg, e);
throw new PolicyComplianceException(msg, e);
}
}
@Override
public void markDeviceAsNoneCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException {
try {
int tenantId = PolicyManagerUtil.getTenantId();
Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);
enrolmentDAO.setStatus(device.getId(), device.getEnrolmentInfo().getOwner(),
EnrolmentInfo.Status.BLOCKED, tenantId);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while marking device as none compliance " + deviceIdentifier.getId() + " - " +
deviceIdentifier.getType();
log.error(msg, e);
throw new PolicyComplianceException(msg, e);
}
}
@Override
public void markDeviceAsCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException {
try {
int tenantId = PolicyManagerUtil.getTenantId();
Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);
enrolmentDAO.setStatus(device.getId(), device.getEnrolmentInfo().getOwner(),
EnrolmentInfo.Status.ACTIVE, tenantId);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while marking device as compliance " + deviceIdentifier.getId() + " - " +
deviceIdentifier.getType();
log.error(msg, e);
throw new PolicyComplianceException(msg, e);
}
}
@Override
public void deactivateDevice(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException {
try {
int tenantId = PolicyManagerUtil.getTenantId();
Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);
enrolmentDAO.setStatus(device.getId(), device.getEnrolmentInfo().getOwner(),
EnrolmentInfo.Status.INACTIVE, tenantId);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while deactivating the device " + deviceIdentifier.getId() + " - " +
deviceIdentifier.getType();
log.error(msg, e);
throw new PolicyComplianceException(msg, e);
}
}
@Override
public void activateDevice(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException {
try {
int tenantId = PolicyManagerUtil.getTenantId();
Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);
enrolmentDAO.setStatus(device.getId(), device.getEnrolmentInfo().getOwner(),
EnrolmentInfo.Status.ACTIVE, tenantId);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while activating the device " + deviceIdentifier.getId() + " - " +
deviceIdentifier.getType();
log.error(msg, e);
throw new PolicyComplianceException(msg, e);
}
}
@Override
public void validateDevicePolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy) throws
public void validateDevicePolicyCompliance(DeviceIdentifier deviceIdentifier, ComplianceData complianceData) throws
PolicyComplianceException {
Policy policy = complianceData.getPolicy();
String compliance = this.getNoneComplianceRule(policy);
if (compliance.equals("")) {
String msg = "Compliance rule is empty for the policy " + policy.getPolicyName() + ". Therefore " +
"Monitoring Engine cannot run.";
throw new PolicyComplianceException(msg);
}
if (PolicyManagementConstants.ENFORCE.equalsIgnoreCase(compliance)) {
this.reEnforcePolicy(deviceIdentifier, complianceData);
}
if (PolicyManagementConstants.WARN.equalsIgnoreCase(compliance)) {
this.markDeviceAsNoneCompliance(deviceIdentifier);
}
if (PolicyManagementConstants.BLOCK.equalsIgnoreCase(compliance)) {
this.markDeviceAsNoneCompliance(deviceIdentifier);
}
}
}

@ -27,6 +27,7 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceDecisionPoint;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature;
import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException;
import org.wso2.carbon.policy.mgt.common.Policy;
@ -37,6 +38,7 @@ import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAOException;
import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
import org.wso2.carbon.policy.mgt.core.impl.ComplianceDecisionPointImpl;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
@ -48,6 +50,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
private PolicyDAO policyDAO;
private DeviceDAO deviceDAO;
private MonitoringDAO monitoringDAO;
private ComplianceDecisionPoint complianceDecisionPoint;
private static final Log log = LogFactory.getLog(MonitoringManagerImpl.class);
@ -55,6 +58,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO();
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
this.monitoringDAO = PolicyManagementDAOFactory.getMonitoringDAO();
this.complianceDecisionPoint = new ComplianceDecisionPointImpl();
}
@Override
@ -71,13 +75,15 @@ public class MonitoringManagerImpl implements MonitoringManager {
PolicyMonitoringService monitoringService = PolicyManagementDataHolder.getInstance().
getPolicyMonitoringService(deviceIdentifier.getType());
complianceFeatures = monitoringService.checkPolicyCompliance(deviceIdentifier,
ComplianceData complianceData = monitoringService.checkPolicyCompliance(deviceIdentifier,
policy, deviceResponse);
complianceData.setPolicy(policy);
complianceFeatures = complianceData.getComplianceFeatures();
if (!complianceFeatures.isEmpty()) {
int complianceId = monitoringDAO.setDeviceAsNoneCompliance(device.getId(), policy.getId());
monitoringDAO.addNoneComplianceFeatures(complianceId, device.getId(), complianceFeatures);
complianceDecisionPoint.validateDevicePolicyCompliance(deviceIdentifier, complianceData);
List<ProfileFeature> profileFeatures = policy.getProfile().getProfileFeaturesList();
for (ComplianceFeature compFeature : complianceFeatures) {
for (ProfileFeature profFeature : profileFeatures) {

@ -19,12 +19,22 @@
package org.wso2.carbon.policy.mgt.core.task;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.ntask.core.Task;
import org.wso2.carbon.policy.mgt.common.spi.PolicyMonitoringService;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import java.util.List;
import java.util.Map;
public class MonitoringTask implements Task {
private DeviceTypeDAO deviceTypeDAO;
@Override
public void setProperties(Map<String, String> map) {
@ -32,11 +42,29 @@ public class MonitoringTask implements Task {
@Override
public void init() {
deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
}
@Override
public void execute() {
try {
List<DeviceType> deviceTypes = deviceTypeDAO.getDeviceTypes();
DeviceManagementProviderService deviceManagementProviderService =
PolicyManagementDataHolder.getInstance().getDeviceManagementService();
for (DeviceType deviceType : deviceTypes) {
PolicyMonitoringService monitoringService =
PolicyManagementDataHolder.getInstance().getPolicyMonitoringService(deviceType.getName());
List<Device> devices = deviceManagementProviderService.getAllDevices(deviceType.getName());
monitoringService.notifyDevices(devices);
}
} catch (Exception e) {
}
}
}

@ -24,4 +24,10 @@ public final class PolicyManagementConstants {
public static final String ANY = "ANY";
public static final String POLICY_BUNDLE = "POLICY_BUNDLE";
public static final String MONITOR = "MONITOR";
public static final String ENFORCE = "ENFORCE";
public static final String WARN = "WARN";
public static final String BLOCK = "BLOCK";
}

@ -945,16 +945,16 @@
</execution>
</executions>
</plugin>
<!--<plugin>-->
<!--<groupId>org.apache.maven.plugins</groupId>-->
<!--<artifactId>maven-compiler-plugin</artifactId>-->
<!--<version>2.3.1</version>-->
<!--<configuration>-->
<!--<encoding>UTF-8</encoding>-->
<!--<source>1.6</source>-->
<!--<target>1.6</target>-->
<!--</configuration>-->
<!--</plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<encoding>UTF-8</encoding>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>

Loading…
Cancel
Save