Committing initial version of supporting device life cycle management

revert-70aa11f8
prabathabey 10 years ago
parent 65620a7389
commit 8d348a358c

@ -32,6 +32,19 @@ public class Device {
private List<Feature> features; private List<Feature> features;
private List<Device.Property> properties; private List<Device.Property> properties;
public Device() {}
public Device(String name, String type, String description, String deviceId, EnrolmentInfo enrolmentInfo,
List<Feature> features, List<Property> properties) {
this.name = name;
this.type = type;
this.description = description;
this.deviceIdentifier = deviceId;
this.enrolmentInfo = enrolmentInfo;
this.features = features;
this.properties = properties;
}
public int getId() { public int getId() {
return id; return id;
} }

@ -24,11 +24,6 @@ import java.util.List;
* device type plugin implementation intended to be managed through CDM. * device type plugin implementation intended to be managed through CDM.
*/ */
public interface DeviceManager { public interface DeviceManager {
enum EnrollmentStatus {
CREATED, ACTIVE, INACTIVE, SUSPENDED, BLOCKED, REMOVED
}
/** /**
* Method to retrieve the provider type that implements DeviceManager interface. * Method to retrieve the provider type that implements DeviceManager interface.
* *
@ -138,6 +133,6 @@ public interface DeviceManager {
boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException; boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException;
boolean setStatus(DeviceIdentifier deviceId, String currentOwner, boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrollmentStatus status) throws DeviceManagementException; EnrolmentInfo.Status status) throws DeviceManagementException;
} }

@ -20,18 +20,28 @@ package org.wso2.carbon.device.mgt.common;
public class EnrolmentInfo { public class EnrolmentInfo {
public enum Status {
CREATED, ACTIVE, INACTIVE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED
}
public enum OwnerShip {
BYOD, COPE
}
private Device device;
private Long dateOfEnrolment; private Long dateOfEnrolment;
private Long dateOfLastUpdate; private Long dateOfLastUpdate;
private OwnerShip ownership; private OwnerShip ownership;
private Status status; private Status status;
private String owner; private String owner;
public enum Status { public EnrolmentInfo() {}
CREATED, ACTIVE, INACTIVE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED
}
public enum OwnerShip { public EnrolmentInfo(Device device, String owner, OwnerShip ownership, Status status) {
BYOD, COPE this.device = device;
this.owner = owner;
this.ownership = ownership;
this.status = status;
} }
public Long getDateOfEnrolment() { public Long getDateOfEnrolment() {
@ -74,4 +84,12 @@ public class EnrolmentInfo {
this.owner = owner; this.owner = owner;
} }
public Device getDevice() {
return device;
}
public void setDevice(Device device) {
this.device = device;
}
} }

@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.common.app.mgt;
public class Application { public class Application {
private String id; private int id;
private String packageName; private String packageName;
private String platform; private String platform;
private String category; private String category;
@ -47,11 +47,11 @@ public class Application {
} }
public String getId() { public int getId() {
return id; return id;
} }
public void setId(String id) { public void setId(int id) {
this.id = id; this.id = id;
} }
@ -105,4 +105,13 @@ public class Application {
this.category = category; this.category = category;
} }
public boolean equals(Object o) {
if (!(o instanceof Application)) {
return false;
}
Application target = (Application)o;
return packageName.equals(target.getPackageName());
}
} }

@ -39,9 +39,7 @@ import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig;
import org.wso2.carbon.device.mgt.core.app.mgt.oauth.ServiceAuthenticator; import org.wso2.carbon.device.mgt.core.app.mgt.oauth.ServiceAuthenticator;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations; import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.*;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener; import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceException; import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceException;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub; import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
@ -52,7 +50,6 @@ import java.util.List;
/** /**
* Implements Application Manager interface * Implements Application Manager interface
*
*/ */
public class ApplicationManagerProviderServiceImpl implements ApplicationManagementProviderService, public class ApplicationManagerProviderServiceImpl implements ApplicationManagementProviderService,
PluginInitializationListener { PluginInitializationListener {
@ -62,13 +59,15 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
private String oAuthAdminServiceUrl; private String oAuthAdminServiceUrl;
private DeviceManagementPluginRepository pluginRepository; private DeviceManagementPluginRepository pluginRepository;
private DeviceDAO deviceDAO; private DeviceDAO deviceDAO;
private ApplicationDAO applicationDAO;
private ApplicationMappingDAO applicationMappingDAO;
private static final String GET_APP_LIST_URL = "store/apis/assets/mobileapp?domain=carbon.super&page=1"; private static final String GET_APP_LIST_URL = "store/apis/assets/mobileapp?domain=carbon.super&page=1";
private static final Log log = LogFactory.getLog(ApplicationManagerProviderServiceImpl.class); private static final Log log = LogFactory.getLog(ApplicationManagerProviderServiceImpl.class);
public ApplicationManagerProviderServiceImpl(AppManagementConfig appManagementConfig, public ApplicationManagerProviderServiceImpl(AppManagementConfig appManagementConfig,
DeviceManagementPluginRepository pluginRepository) { DeviceManagementPluginRepository pluginRepository) {
IdentityConfigurations identityConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). IdentityConfigurations identityConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().
getDeviceManagementConfigRepository().getIdentityConfigurations(); getDeviceManagementConfigRepository().getIdentityConfigurations();
@ -84,6 +83,8 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
} }
this.pluginRepository = pluginRepository; this.pluginRepository = pluginRepository;
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
this.applicationDAO = DeviceManagementDAOFactory.getApplicationDAO();
this.applicationMappingDAO = DeviceManagementDAOFactory.getApplicationMappingDAO();
} }
@Override @Override
@ -100,7 +101,7 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
@Override @Override
public String getApplicationStatus(DeviceIdentifier deviceId, public String getApplicationStatus(DeviceIdentifier deviceId,
Application application) throws ApplicationManagementException { Application application) throws ApplicationManagementException {
return null; return null;
} }
@ -160,16 +161,17 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
} }
@Override @Override
public void updateApplicationListInstallInDevice(DeviceIdentifier deviceIdentifier,List<Application> applications) public void updateApplicationListInstallInDevice(
throws ApplicationManagementException { DeviceIdentifier deviceIdentifier, List<Application> applications) throws ApplicationManagementException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try { try {
Device device = deviceDAO.getDevice(deviceIdentifier, tenantId); Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);
deviceDAO.addDeviceApplications(device.getId(), applications); List<Integer> applicationIds = applicationDAO.addApplications(applications, tenantId);
}catch (DeviceManagementDAOException deviceDaoEx){ applicationMappingDAO.addApplicationMappings(device.getId(), applicationIds, tenantId);
} catch (DeviceManagementDAOException deviceDaoEx) {
String errorMsg = "Error occurred saving application list to the device"; String errorMsg = "Error occurred saving application list to the device";
log.error(errorMsg+":"+deviceIdentifier.toString()); log.error(errorMsg + ":" + deviceIdentifier.toString());
throw new ApplicationManagementException(errorMsg, deviceDaoEx); throw new ApplicationManagementException(errorMsg, deviceDaoEx);
} }
} }

@ -0,0 +1,35 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.core.dao;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import java.util.List;
public interface ApplicationDAO {
int addApplication(Application application, int tenantId) throws DeviceManagementDAOException;
List<Integer> addApplications(List<Application> applications, int tenantId) throws DeviceManagementDAOException;
int removeApplication(String applicationName, int tenantId) throws DeviceManagementDAOException;
Application getApplication(String identifier, int tenantId) throws DeviceManagementDAOException;
}

@ -18,18 +18,15 @@
*/ */
package org.wso2.carbon.device.mgt.core.dao; package org.wso2.carbon.device.mgt.core.dao;
import org.wso2.carbon.device.mgt.common.DeviceManager; import java.util.List;
public interface EnrollmentDAO { public interface ApplicationMappingDAO {
boolean addEnrollment() throws DeviceManagementDAOException; int addApplicationMapping(int deviceId, int applicationId, int tenantId) throws DeviceManagementDAOException;
boolean updateEnrollment() throws DeviceManagementDAOException; List<Integer> addApplicationMappings(int deviceId, List<Integer> applicationIds,
int tenantId) throws DeviceManagementDAOException;
boolean removeEnrollment() throws DeviceManagementDAOException; int removeApplicationMapping(int deviceId, int applicationId, int tenantId) throws DeviceManagementDAOException;
boolean setStatus(int deviceId, String currentOwner, String status) throws DeviceManagementDAOException;
boolean getStatus() throws DeviceManagementDAOException;
} }

@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.dao;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo.Status; import org.wso2.carbon.device.mgt.common.EnrolmentInfo.Status;
import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.Application;
@ -30,50 +31,33 @@ import java.util.List;
*/ */
public interface DeviceDAO { public interface DeviceDAO {
void addDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException; int addDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException;
void updateDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException; int updateDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException;
void updateDeviceStatus(DeviceIdentifier deviceId, Status status, int removeDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException;
int tenantId) throws DeviceManagementDAOException;
void deleteDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException; Device getDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException;
Device getDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException; List<Device> getDevices(int tenantId) throws DeviceManagementDAOException;
List<Device> getDevices(int tenantId) throws DeviceManagementDAOException; List<Device> getDevices(String type, int tenantId) throws DeviceManagementDAOException;
/** List<Device> getDevicesOfUser(String username, int tenantId) throws DeviceManagementDAOException;
* @param type - The device type id.
* @return a list of devices based on the type id.
* @throws DeviceManagementDAOException
*/
List<Device> getDevices(String type, int tenantId) throws DeviceManagementDAOException;
/**
* Get the list of devices belongs to a user.
* @param username Requested user.
* @return List of devices of the user.
* @throws DeviceManagementDAOException
*/
List<Device> getDeviceListOfUser(String username, int tenantId) throws DeviceManagementDAOException;
/**
* Get the count of devices
*
* @return device count
* @throws DeviceManagementDAOException
*/
int getDeviceCount(int tenantId) throws DeviceManagementDAOException; int getDeviceCount(int tenantId) throws DeviceManagementDAOException;
/**
* Get the list of devices that matches with the given device name.
*
* @param deviceName Name of the device
* @return List of devices that matches with the given device name.
* @throws DeviceManagementDAOException
*/
List<Device> getDevicesByName(String deviceName, int tenantId) throws DeviceManagementDAOException; List<Device> getDevicesByName(String deviceName, int tenantId) throws DeviceManagementDAOException;
void addDeviceApplications(int id, Object applications) throws DeviceManagementDAOException; int addEnrollment(Device device, int tenantId) throws DeviceManagementDAOException;
boolean setEnrolmentStatus(DeviceIdentifier deviceId, String currentOwner, Status status,
int tenantId) throws DeviceManagementDAOException;
Status getEnrolmentStatus(DeviceIdentifier deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException;
EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, String currentUser,
int tenantId) throws DeviceManagementDAOException;
} }

@ -22,9 +22,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
import org.wso2.carbon.device.mgt.core.dao.impl.DeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.*;
import org.wso2.carbon.device.mgt.core.dao.impl.DeviceTypeDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.EnrollmentDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import javax.sql.DataSource; import javax.sql.DataSource;
@ -47,8 +45,16 @@ public class DeviceManagementDAOFactory {
return new DeviceTypeDAOImpl(); return new DeviceTypeDAOImpl();
} }
public static EnrollmentDAO getEnrollmentDAO() { public static EnrolmentDAO getEnrollmentDAO() {
return new EnrollmentDAOImpl(); return new EnrolmentDAOImpl();
}
public static ApplicationDAO getApplicationDAO() {
return new ApplicationDAOImpl();
}
public static ApplicationMappingDAO getApplicationMappingDAO() {
return new ApplicationMappingDAOImpl();
} }
public static void init(DataSourceConfig config) { public static void init(DataSourceConfig config) {
@ -61,19 +67,28 @@ public class DeviceManagementDAOFactory {
public static void beginTransaction() throws DeviceManagementDAOException { public static void beginTransaction() throws DeviceManagementDAOException {
try { try {
currentConnection.set(dataSource.getConnection()); Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving datasource connection", e); throw new DeviceManagementDAOException("Error occurred while retrieving datasource connection", e);
} }
} }
public static void openConnection() throws DeviceManagementDAOException {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while acquiring datasource connection", e);
}
}
public static Connection getConnection() throws DeviceManagementDAOException { public static Connection getConnection() throws DeviceManagementDAOException {
if (currentConnection.get() == null) { if (currentConnection.get() == null) {
try { try {
currentConnection.set(dataSource.getConnection()); currentConnection.set(dataSource.getConnection());
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving data source connection", throw new DeviceManagementDAOException("Error occurred while retrieving data source connection", e);
e);
} }
} }
return currentConnection.get(); return currentConnection.get();

@ -0,0 +1,40 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.core.dao;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo.Status;
public interface EnrolmentDAO {
int addEnrollment(int deviceId, EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementDAOException;
int updateEnrollment(int deviceId, EnrolmentInfo enrolmentInfo,
int tenantId) throws DeviceManagementDAOException;
int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException;
boolean setStatus(int deviceId, String currentOwner, Status status,
int tenantId) throws DeviceManagementDAOException;
Status getStatus(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException;
EnrolmentInfo getEnrolment(int deviceId, String currentUser, int tenantId) throws DeviceManagementDAOException;
}

@ -0,0 +1,186 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.core.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO;
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.util.DeviceManagementDAOUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ApplicationDAOImpl implements ApplicationDAO {
private static final Log log = LogFactory.getLog(ApplicationDAOImpl.class);
@Override
public int addApplication(Application application, int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int applicationId = -1;
try {
conn = this.getConnection();
stmt = conn.prepareStatement("INSERT INTO DM_APPLICATION (NAME, PACKAGE_NAME, PLATFORM, CATEGORY, " +
"VERSION, TYPE, LOCATION_URL, IMAGE_URL, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, application.getName());
stmt.setString(2, application.getPackageName());
stmt.setString(3, application.getPlatform());
stmt.setString(4, application.getCategory());
stmt.setString(5, application.getVersion());
stmt.setString(6, application.getType());
stmt.setString(7, application.getLocationUrl());
stmt.setString(8, application.getImageUrl());
stmt.setInt(9, tenantId);
stmt.execute();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
applicationId = rs.getInt(1);
}
return applicationId;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while adding application '" +
application.getName() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public List<Integer> addApplications(List<Application> applications,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs;
List<Integer> applicationIds = new ArrayList<Integer>();
try {
conn = this.getConnection();
stmt = conn.prepareStatement("INSERT INTO DM_APPLICATION (NAME, PACKAGE_NAME, PLATFORM, CATEGORY, " +
"VERSION, TYPE, LOCATION_URL, IMAGE_URL, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
for (Application application : applications) {
stmt.setString(1, application.getName());
stmt.setString(2, application.getPackageName());
stmt.setString(3, application.getPlatform());
stmt.setString(4, application.getCategory());
stmt.setString(5, application.getVersion());
stmt.setString(6, application.getType());
stmt.setString(7, application.getLocationUrl());
stmt.setString(8, application.getImageUrl());
stmt.setInt(9, tenantId);
stmt.addBatch();
}
stmt.executeBatch();
rs = stmt.getGeneratedKeys();
while (rs.next()) {
applicationIds.add(rs.getInt(1));
}
return applicationIds;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while adding bulk application list", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public int removeApplication(String applicationName, int tenantId) throws DeviceManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
int applicationId = -1;
try {
conn = this.getConnection();
conn.setAutoCommit(false);
stmt = conn.prepareStatement("DELETE DM_APPLICATION WHERE NAME = ? AND TENANT_ID = ?");
stmt.setString(1, applicationName);
stmt.setInt(2, tenantId);
stmt.execute();
conn.commit();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
applicationId = rs.getInt(1);
}
return applicationId;
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
log.warn("Error occurred while roll-backing the transaction", e);
}
throw new DeviceManagementDAOException("Error occurred while removing application '" +
applicationName + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public Application getApplication(String identifier, int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
Application application = null;
try {
conn = this.getConnection();
stmt = conn.prepareStatement("SELECT ID, NAME, PACKAGE_NAME, CATEGORY, PLATFORM, TYPE, VERSION, IMAGE_URL, " +
"LOCATION_URL FROM DM_APPLICATION WHERE PACKAGE_NAME = ? AND TENANT_ID = ?");
stmt.setString(1, identifier);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
application = this.loadApplication(rs);
}
return application;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving application application '" +
identifier + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
private Connection getConnection() throws DeviceManagementDAOException {
return DeviceManagementDAOFactory.getConnection();
}
private Application loadApplication(ResultSet rs) throws SQLException {
Application application = new Application();
application.setId(rs.getInt("ID"));
application.setName(rs.getString("NAME"));
application.setPackageName(rs.getString("PACKAGE_NAME"));
application.setCategory(rs.getString("CATEGORY"));
application.setType(rs.getString("TYPE"));
application.setVersion(rs.getString("VERSION"));
application.setImageUrl(rs.getString("IMAGE_URL"));
application.setLocationUrl(rs.getString("LOCATION_URL"));
application.setPlatform(rs.getString("PLATFORM"));
return application;
}
}

@ -0,0 +1,124 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.core.dao.impl;
import org.wso2.carbon.device.mgt.core.dao.ApplicationMappingDAO;
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.util.DeviceManagementDAOUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ApplicationMappingDAOImpl implements ApplicationMappingDAO {
@Override
public int addApplicationMapping(int deviceId, int applicationId,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int mappingId = -1;
try {
conn = this.getConnection();
String sql = "INSERT INTO DM_DEVICE_APPLICATION_MAPPING (DEVICE_ID, APPLICATION_ID, " +
"TENANT_ID) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, deviceId);
stmt.setInt(2, applicationId);
stmt.setInt(3, tenantId);
stmt.execute();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
mappingId = rs.getInt(1);
}
return mappingId;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while adding device application mapping", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public List<Integer> addApplicationMappings(int deviceId, List<Integer> applicationIds,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Integer> mappingIds = new ArrayList<Integer>();
try {
conn = this.getConnection();
String sql = "INSERT INTO DM_DEVICE_APPLICATION_MAPPING (DEVICE_ID, APPLICATION_ID, " +
"TENANT_ID) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
for (int applicationId : applicationIds) {
stmt.setInt(1, deviceId);
stmt.setInt(2, applicationId);
stmt.setInt(3, tenantId);
stmt.addBatch();
}
stmt.executeBatch();
rs = stmt.getGeneratedKeys();
while (rs.next()) {
mappingIds.add(rs.getInt(1));
}
return mappingIds;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while adding device application mappings", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public int removeApplicationMapping(int deviceId, int applicationId,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
ResultSet rs;
int mappingId = -1;
try {
conn = this.getConnection();
String sql = "DELETE DM_DEVICE_APPLICATION_MAPPING WHERE DEVICE_ID = ? AND " +
"APPLICATION_ID = ? AND TENANT_ID = ?";
PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, deviceId);
stmt.setInt(2, applicationId);
stmt.setInt(3, tenantId);
stmt.execute();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
mappingId = rs.getInt(1);
}
return mappingId;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while adding device application mapping", e);
}
}
private Connection getConnection() throws DeviceManagementDAOException {
return DeviceManagementDAOFactory.getConnection();
}
}

@ -30,10 +30,7 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
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.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import java.sql.Connection; import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -41,65 +38,71 @@ import java.util.List;
public class DeviceDAOImpl implements DeviceDAO { public class DeviceDAOImpl implements DeviceDAO {
@Override @Override
public void addDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException { public int addDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null;
int deviceId = -1;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql =
"INSERT INTO DM_DEVICE(DESCRIPTION, NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, " + "INSERT INTO DM_DEVICE(DESCRIPTION, NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, TENANT_ID) " +
"OWNERSHIP, STATUS, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, OWNER, TENANT_ID) " + "VALUES (?, ?, ?, ?, ?)";
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt = conn.prepareStatement(sql);
stmt.setString(1, device.getDescription()); stmt.setString(1, device.getDescription());
stmt.setString(2, device.getName()); stmt.setString(2, device.getName());
stmt.setLong(3, new Date().getTime()); stmt.setInt(3, typeId);
stmt.setLong(4, new Date().getTime()); stmt.setString(4, device.getDeviceIdentifier());
stmt.setString(5, device.getEnrolmentInfo().getOwnership().toString()); stmt.setInt(5, tenantId);
stmt.setString(6, device.getEnrolmentInfo().getStatus().toString());
stmt.setInt(7, typeId);
stmt.setString(8, device.getDeviceIdentifier());
stmt.setString(9, device.getEnrolmentInfo().getOwner());
stmt.setInt(10, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
deviceId = rs.getInt(1);
}
return deviceId;
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while enrolling device " + throw new DeviceManagementDAOException("Error occurred while enrolling device " +
"'" + device.getName() + "'", e); "'" + device.getName() + "'", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null); DeviceManagementDAOUtil.cleanupResources(stmt, rs);
} }
} }
@Override @Override
public void updateDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException { public int updateDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null;
int deviceId = -1;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "UPDATE DM_DEVICE SET STATUS = ?, OWNER = ? WHERE DEVICE_IDENTIFICATION = ? AND TENANT_ID = ?"; String sql = "UPDATE DM_DEVICE SET DESCRIPTION = ?, NAME = ? WHERE DEVICE_IDENTIFICATION = ? AND " +
stmt = conn.prepareStatement(sql); "DEVICE_TYPE_ID = ? AND TENANT_ID = ?";
stmt.setString(1, device.getEnrolmentInfo().getStatus().toString()); stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(2, device.getEnrolmentInfo().getOwner()); stmt.setString(1, device.getDescription());
stmt.setString(2, device.getName());
stmt.setString(3, device.getDeviceIdentifier()); stmt.setString(3, device.getDeviceIdentifier());
stmt.setInt(4, tenantId); stmt.setInt(4, typeId);
stmt.setInt(5, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
deviceId = rs.getInt(1);
}
return deviceId;
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while enrolling device '" + throw new DeviceManagementDAOException("Error occurred while enrolling device '" +
device.getName() + "'", e); device.getName() + "'", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null); DeviceManagementDAOUtil.cleanupResources(stmt, rs);
} }
} }
@Override @Override
public void updateDeviceStatus(DeviceIdentifier deviceId, Status status, public int removeDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException {
int tenantId) throws DeviceManagementDAOException { return 0;
}
@Override
public void deleteDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException {
} }
@Override @Override
@ -111,8 +114,8 @@ public class DeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql =
"SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DATE_OF_ENROLLMENT, d.DATE_OF_LAST_UPDATE, d.OWNERSHIP, d.STATUS, " + "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, " +
"d.DEVICE_TYPE_ID, d.DEVICE_IDENTIFICATION, d.OWNER, d.TENANT_ID FROM DM_DEVICE d, DM_DEVICE_TYPE dt WHERE " + "d.DEVICE_TYPE_ID, d.DEVICE_IDENTIFICATION, d.TENANT_ID FROM DM_DEVICE d, DM_DEVICE_TYPE dt WHERE " +
"dt.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?"; "dt.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceId.getType()); stmt.setString(1, deviceId.getType());
@ -139,9 +142,8 @@ public class DeviceDAOImpl implements DeviceDAO {
List<Device> devices = null; List<Device> devices = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DATE_OF_ENROLLMENT, " + String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_TYPE_ID, " +
"d.DATE_OF_LAST_UPDATE, d.OWNERSHIP, d.STATUS, d.DEVICE_TYPE_ID, " + "d.DEVICE_IDENTIFICATION, d.TENANT_ID, t.NAME AS DEVICE_TYPE_NAME FROM DM_DEVICE d, DEVICE_TYPE t " +
"d.DEVICE_IDENTIFICATION, d.OWNER, d.TENANT_ID, t.NAME AS DEVICE_TYPE_NAME FROM DM_DEVICE d, DEVICE_TYPE t " +
"WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? "; "WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
@ -168,8 +170,8 @@ public class DeviceDAOImpl implements DeviceDAO {
List<Device> devices = null; List<Device> devices = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String selectDBQueryForType = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DATE_OF_ENROLLMENT, d.DATE_OF_LAST_UPDATE, " + String selectDBQueryForType = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, " +
"d.OWNERSHIP, d.STATUS, d.DEVICE_TYPE_ID, d.DEVICE_IDENTIFICATION, d.OWNER, d.TENANT_ID FROM DM_DEVICE d, DM_DEVICE_TYPE t " + "d.DEVICE_TYPE_ID, d.DEVICE_IDENTIFICATION, d.OWNER, d.TENANT_ID FROM DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE d.DM_DEVICE.DEVICE_TYPE_ID = t.ID AND t.NAME = ? AND d.TENANT_ID = ?"; "WHERE d.DM_DEVICE.DEVICE_TYPE_ID = t.ID AND t.NAME = ? AND d.TENANT_ID = ?";
stmt = conn.prepareStatement(selectDBQueryForType); stmt = conn.prepareStatement(selectDBQueryForType);
stmt.setString(1, type); stmt.setString(1, type);
@ -189,7 +191,7 @@ public class DeviceDAOImpl implements DeviceDAO {
} }
@Override @Override
public List<Device> getDeviceListOfUser(String username, int tenantId) throws DeviceManagementDAOException { public List<Device> getDevicesOfUser(String username, int tenantId) throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
List<Device> devices = new ArrayList<Device>(); List<Device> devices = new ArrayList<Device>();
@ -197,11 +199,8 @@ public class DeviceDAOImpl implements DeviceDAO {
conn = this.getConnection(); conn = this.getConnection();
stmt = conn.prepareStatement( stmt = conn.prepareStatement(
"SELECT t.NAME AS DEVICE_TYPE, d.ID AS DEVICE_ID, d.DESCRIPTION, " + "SELECT t.NAME AS DEVICE_TYPE, d.ID AS DEVICE_ID, d.DESCRIPTION, " +
"d.NAME AS DEVICE_NAME, d.DATE_OF_ENROLLMENT, d.DATE_OF_LAST_UPDATE, " + "d.NAME AS DEVICE_NAME, d.DEVICE_TYPE_ID, d.DEVICE_IDENTIFICATION, d.TENANT_ID FROM " +
"d.OWNERSHIP, d.STATUS, d.DEVICE_TYPE_ID, " + "DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.OWNER =? AND d.TENANT_ID = ?");
"d.DEVICE_IDENTIFICATION, d.OWNER, d.TENANT_ID FROM " +
"DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " +
"AND d.OWNER =? AND d.TENANT_ID = ?");
stmt.setString(1, username); stmt.setString(1, username);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
ResultSet rs = stmt.executeQuery(); ResultSet rs = stmt.executeQuery();
@ -255,8 +254,8 @@ public class DeviceDAOImpl implements DeviceDAO {
/** /**
* Get the list of devices that matches with the given device name. * Get the list of devices that matches with the given device name.
* *
* @param deviceName Name of the device. * @param deviceName Name of the device.
* @param tenantId Id of the current tenant * @param tenantId Id of the current tenant
* @return device list * @return device list
* @throws DeviceManagementDAOException * @throws DeviceManagementDAOException
*/ */
@ -269,9 +268,7 @@ public class DeviceDAOImpl implements DeviceDAO {
conn = this.getConnection(); conn = this.getConnection();
stmt = conn.prepareStatement( stmt = conn.prepareStatement(
"SELECT d.ID AS DEVICE_ID, d.NAME AS DEVICE_NAME, t.ID AS DEVICE_TYPE_ID, d.DESCRIPTION, " + "SELECT d.ID AS DEVICE_ID, d.NAME AS DEVICE_NAME, t.ID AS DEVICE_TYPE_ID, d.DESCRIPTION, " +
"t.NAME AS DEVICE_TYPE, d.DATE_OF_ENROLLMENT, d.DATE_OF_LAST_UPDATE, " + "t.NAME AS DEVICE_TYPE, d.DEVICE_TYPE_ID, d.DEVICE_IDENTIFICATION, d.TENANT_ID FROM " +
"d.OWNERSHIP, d.STATUS, d.DEVICE_TYPE_ID, " +
"d.DEVICE_IDENTIFICATION, d.OWNER, d.TENANT_ID FROM " +
"DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " + "DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " +
"AND d.NAME LIKE ? AND d.TENANT_ID = ?"); "AND d.NAME LIKE ? AND d.TENANT_ID = ?");
stmt.setString(1, deviceName + "%"); stmt.setString(1, deviceName + "%");
@ -292,25 +289,124 @@ public class DeviceDAOImpl implements DeviceDAO {
} }
@Override @Override
public void addDeviceApplications(int deviceId, Object appList) throws DeviceManagementDAOException { public int addEnrollment(Device device, int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int enrolmentId = -1;
try {
conn = this.getConnection();
String sql = "INSERT INTO DM_ENROLMENT(DEVICE_ID, OWNER, OWNERSHIP, STATUS, " +
"DATE_OF_ENROLMENT, DATE_OF_LAST_UPDATE, TENANT_ID) VALUES(?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, device.getId());
stmt.setString(2, device.getEnrolmentInfo().getOwner());
stmt.setString(3, device.getEnrolmentInfo().getOwnership().toString());
stmt.setString(4, device.getEnrolmentInfo().getStatus().toString());
stmt.setTimestamp(5, new Timestamp(new Date().getTime()));
stmt.setTimestamp(6, new Timestamp(new Date().getTime()));
stmt.setInt(7, tenantId);
stmt.execute();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
enrolmentId = rs.getInt(1);
}
return enrolmentId;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while adding enrolment", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public boolean setEnrolmentStatus(DeviceIdentifier deviceId, String currentOwner, Status status,
int tenantId) throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "INSERT INTO DM_DEVICE_APPLICATIONS(DEVICE_ID, APPLICATIONS) " + String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE DEVICE_ID = " +
"VALUES (?, ?)"; "(SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND " +
"d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId); stmt.setString(1, status.toString());
stmt.setObject(2, appList); stmt.setString(2, deviceId.getId());
stmt.setString(3, deviceId.getType());
stmt.setInt(4, tenantId);
stmt.setString(5, currentOwner);
stmt.setInt(6, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while update application list for device " + throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e);
"'" + deviceId + "'", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null); DeviceManagementDAOUtil.cleanupResources(stmt, null);
} }
return true;
}
@Override
public Status getEnrolmentStatus(DeviceIdentifier deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
Status status = null;
try {
conn = this.getConnection();
String sql = "SELECT STATUS FROM DM_ENROLMENT WHERE DEVICE_ID = " +
"(SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND " +
"d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceId.getId());
stmt.setString(2, deviceId.getType());
stmt.setInt(3, tenantId);
stmt.setString(4, currentOwner);
stmt.setInt(5, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
status = Status.valueOf(rs.getString("STATUS"));
}
return status;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the status of device enrolment", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
EnrolmentInfo enrolmentInfo = null;
try {
conn = this.getConnection();
String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " +
"DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = " +
"(SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND" +
" d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceId.getId());
stmt.setString(2, deviceId.getType());
stmt.setInt(3, tenantId);
stmt.setString(4, currentOwner);
stmt.setInt(5, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
enrolmentInfo = this.loadEnrolment(rs);
}
return enrolmentInfo;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " +
"information of user '" + currentOwner + "' upon device '" + deviceId + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
} }
private Device loadDevice(ResultSet rs) throws SQLException { private Device loadDevice(ResultSet rs) throws SQLException {
@ -322,16 +418,19 @@ public class DeviceDAOImpl implements DeviceDAO {
device.setDescription(rs.getString("DESCRIPTION")); device.setDescription(rs.getString("DESCRIPTION"));
device.setType(rs.getString("DEVICE_TYPE")); device.setType(rs.getString("DEVICE_TYPE"));
device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION"));
device.setEnrolmentInfo(this.loadEnrolment(rs));
return device;
}
private EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(rs.getLong("DATE_OF_ENROLLMENT"));
enrolmentInfo.setDateOfLastUpdate(rs.getLong("DATE_OF_LAST_UPDATE"));
enrolmentInfo.setOwnership(OwnerShip.valueOf(rs.getString("OWNERSHIP")));
enrolmentInfo.setStatus(Status.valueOf(rs.getString("STATUS")));
enrolmentInfo.setOwner(rs.getString("OWNER")); enrolmentInfo.setOwner(rs.getString("OWNER"));
device.setEnrolmentInfo(enrolmentInfo); enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP")));
enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime());
return device; enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS")));
return enrolmentInfo;
} }
} }

@ -1,51 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.core.dao.impl;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO;
public class EnrollmentDAOImpl implements EnrollmentDAO {
@Override
public boolean addEnrollment() throws DeviceManagementDAOException {
return false;
}
@Override
public boolean updateEnrollment() throws DeviceManagementDAOException {
return false;
}
@Override
public boolean removeEnrollment() throws DeviceManagementDAOException {
return false;
}
@Override
public boolean setStatus(int deviceId, String currentOwner, String status) throws DeviceManagementDAOException {
return false;
}
@Override
public boolean getStatus() throws DeviceManagementDAOException {
return false;
}
}

@ -0,0 +1,216 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.core.dao.impl;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
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.dao.util.DeviceManagementDAOUtil;
import java.sql.*;
import java.util.Date;
public class EnrolmentDAOImpl implements EnrolmentDAO {
@Override
public int addEnrollment(int deviceId, EnrolmentInfo enrolmentInfo,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int enrolmentId = -1;
try {
conn = this.getConnection();
String sql = "INSERT INTO DM_ENROLMENT(DEVICE_ID, OWNER, OWNERSHIP, STATUS, " +
"DATE_OF_ENROLMENT, DATE_OF_LAST_UPDATE, TENANT_ID) VALUES(?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, deviceId);
stmt.setString(2, enrolmentInfo.getOwner());
stmt.setString(3, enrolmentInfo.getOwnership().toString());
stmt.setString(4, enrolmentInfo.getStatus().toString());
stmt.setTimestamp(5, new Timestamp(new Date().getTime()));
stmt.setTimestamp(6, new Timestamp(new Date().getTime()));
stmt.setInt(7, tenantId);
stmt.execute();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
enrolmentId = rs.getInt(1);
}
return enrolmentId;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while adding enrolment configuration", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public int updateEnrollment(int deviceId, EnrolmentInfo enrolmentInfo,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int enrolmentId = -1;
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, " +
"DATE_OF_ENROLMENT = ?, DATE_OF_LAST_UPDATE = ? WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, enrolmentInfo.getOwnership().toString());
stmt.setString(2, enrolmentInfo.getStatus().toString());
stmt.setTimestamp(3, new Timestamp(enrolmentInfo.getDateOfEnrolment()));
stmt.setTimestamp(4, new Timestamp(enrolmentInfo.getDateOfLastUpdate()));
stmt.setInt(5, deviceId);
stmt.setString(6, enrolmentInfo.getOwner());
stmt.setInt(7, tenantId);
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
enrolmentId = rs.getInt(1);
}
return enrolmentId;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public int removeEnrollment(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int enrolmentId = -1;
try {
conn = this.getConnection();
String sql = "DELETE DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, deviceId);
stmt.setString(2, currentOwner);
stmt.setInt(3, tenantId);
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
enrolmentId = rs.getInt(1);
}
return enrolmentId;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while removing device enrolment", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public boolean setStatus(int deviceId, String currentOwner, EnrolmentInfo.Status status,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, status.toString());
stmt.setInt(2, deviceId);
stmt.setString(3, currentOwner);
stmt.setInt(4, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return true;
}
@Override
public EnrolmentInfo.Status getStatus(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
EnrolmentInfo.Status status = null;
try {
conn = this.getConnection();
String sql = "SELECT STATUS FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(2, deviceId);
stmt.setString(3, currentOwner);
stmt.setInt(4, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
status = EnrolmentInfo.Status.valueOf(rs.getString("STATUS"));
}
return status;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public EnrolmentInfo getEnrolment(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
EnrolmentInfo enrolmentInfo = null;
try {
conn = this.getConnection();
String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " +
"DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setString(2, currentOwner);
stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
enrolmentInfo = this.loadEnrolment(rs);
}
return enrolmentInfo;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " +
"information of user '" + currentOwner + "' upon device '" + deviceId + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
private Connection getConnection() throws DeviceManagementDAOException {
return DeviceManagementDAOFactory.getConnection();
}
private EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setOwner(rs.getString("OWNER"));
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP")));
enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime());
enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS")));
return enrolmentInfo;
}
}

@ -26,6 +26,13 @@ public class DeviceType implements Serializable {
private int id; private int id;
private String name; private String name;
public DeviceType() {
}
public DeviceType(String name) {
this.name = name;
}
public int getId() { public int getId() {
return id; return id;
} }

@ -25,6 +25,7 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationDAO;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil;
import java.sql.*; import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
@ -40,9 +41,9 @@ public class OperationDAOImpl implements OperationDAO {
ResultSet rs = null; ResultSet rs = null;
try { try {
Connection connection = OperationManagementDAOFactory.getConnection(); Connection connection = OperationManagementDAOFactory.getConnection();
stmt = connection.prepareStatement( String sql = "INSERT INTO DM_OPERATION(TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE) " +
"INSERT INTO DM_OPERATION(TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE) " + "VALUES (?, ?, ?, ?)";
"VALUES (?, ?, ?, ?)"); stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, operation.getType().toString()); stmt.setString(1, operation.getType().toString());
stmt.setTimestamp(2, new Timestamp(new Date().getTime())); stmt.setTimestamp(2, new Timestamp(new Date().getTime()));
stmt.setTimestamp(3, null); stmt.setTimestamp(3, null);
@ -82,8 +83,8 @@ public class OperationDAOImpl implements OperationDAO {
} }
} }
public void updateOperationStatus(int deviceId, int operationId,Operation.Status status) public void updateOperationStatus(int deviceId, int operationId, Operation.Status status)
throws OperationManagementDAOException{ throws OperationManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
@ -231,7 +232,7 @@ public class OperationDAOImpl implements OperationDAO {
@Override @Override
public List<? extends Operation> getOperationsByDeviceAndStatus(int deviceId, public List<? extends Operation> getOperationsByDeviceAndStatus(int deviceId,
Operation.Status status) throws OperationManagementDAOException { Operation.Status status) throws OperationManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -370,7 +371,7 @@ public class OperationDAOImpl implements OperationDAO {
public List<? extends Operation> getOperationsByDeviceStatusAndType(int deviceId, public List<? extends Operation> getOperationsByDeviceStatusAndType(int deviceId,
Operation.Status status,Operation.Type type) throws OperationManagementDAOException { Operation.Status status, Operation.Type type) throws OperationManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -380,7 +381,7 @@ public class OperationDAOImpl implements OperationDAO {
try { try {
Connection conn = OperationManagementDAOFactory.getConnection(); Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE FROM "+ String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE FROM " +
"(SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE " + "(SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE " +
"FROM DM_OPERATION o WHERE o.TYPE=?) o " + "FROM DM_OPERATION o WHERE o.TYPE=?) o " +
"INNER JOIN (Select * from DM_DEVICE_OPERATION_MAPPING dm " + "INNER JOIN (Select * from DM_DEVICE_OPERATION_MAPPING dm " +

@ -21,7 +21,6 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.app.mgt.Application; 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.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
@ -32,7 +31,7 @@ import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.email.NotificationMessages; import org.wso2.carbon.device.mgt.core.config.email.NotificationMessages;
import org.wso2.carbon.device.mgt.core.dao.*; import org.wso2.carbon.device.mgt.core.dao.*;
import org.wso2.carbon.device.mgt.core.dto.*; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.email.EmailConstants; import org.wso2.carbon.device.mgt.core.email.EmailConstants;
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;
@ -50,7 +49,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
private DeviceDAO deviceDAO; private DeviceDAO deviceDAO;
private DeviceTypeDAO deviceTypeDAO; private DeviceTypeDAO deviceTypeDAO;
private EnrollmentDAO enrollmentDAO; private EnrolmentDAO enrolmentDAO;
private DeviceManagementPluginRepository pluginRepository; private DeviceManagementPluginRepository pluginRepository;
private static Log log = LogFactory.getLog(DeviceManagementProviderServiceImpl.class); private static Log log = LogFactory.getLog(DeviceManagementProviderServiceImpl.class);
@ -60,7 +59,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
this.pluginRepository = new DeviceManagementPluginRepository(); this.pluginRepository = new DeviceManagementPluginRepository();
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
this.enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); this.enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
/* Registering a listener to retrieve events when some device management service plugin is installed after /* Registering a listener to retrieve events when some device management service plugin is installed after
* the component is done getting initialized */ * the component is done getting initialized */
@ -100,14 +99,21 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
DeviceManagementDAOFactory.beginTransaction(); DeviceManagementDAOFactory.beginTransaction();
DeviceType type = deviceTypeDAO.getDeviceType(device.getType()); DeviceType type = deviceTypeDAO.getDeviceType(device.getType());
deviceDAO.addDevice(type.getId(), device, tenantId); int deviceId = deviceDAO.addDevice(type.getId(), device, tenantId);
int enrolmentId = enrolmentDAO.addEnrollment(deviceId, device.getEnrolmentInfo(), tenantId);
if (log.isDebugEnabled()) {
log.debug("An enrolment is successfully created with the id '" + enrolmentId + "' associated with " +
"the device identified by key '" + device.getDeviceIdentifier() + "', which belongs to " +
"platform '" + device.getType() + " upon the user '" +
device.getEnrolmentInfo().getOwner() + "'");
}
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
try { try {
DeviceManagementDAOFactory.rollbackTransaction(); DeviceManagementDAOFactory.rollbackTransaction();
} catch (DeviceManagementDAOException e1) { } catch (DeviceManagementDAOException e1) {
log.warn("Error occurred while rollbacking the current transaction", e); log.warn("Error occurred while roll-backing the current transaction", e);
} }
throw new DeviceManagementException("Error occurred while enrolling the device " + throw new DeviceManagementException("Error occurred while enrolling the device " +
"'" + device.getId() + "'", e); "'" + device.getId() + "'", e);
@ -128,18 +134,18 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
boolean status = dms.modifyEnrollment(device); boolean status = dms.modifyEnrollment(device);
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
DeviceManagementDAOFactory.beginTransaction(); DeviceManagementDAOFactory.beginTransaction();
DeviceType type = deviceTypeDAO.getDeviceType(device.getType()); DeviceType type = deviceTypeDAO.getDeviceType(device.getType());
deviceDAO.updateDevice(type.getId(), device, tenantId); int deviceId = deviceDAO.updateDevice(type.getId(), device, tenantId);
enrolmentDAO.updateEnrollment(deviceId, device.getEnrolmentInfo(), tenantId);
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
try { try {
DeviceManagementDAOFactory.rollbackTransaction(); DeviceManagementDAOFactory.rollbackTransaction();
} catch (DeviceManagementDAOException e1) { } catch (DeviceManagementDAOException e1) {
log.warn("Error occurred while rollbacking the current transaction", e); log.warn("Error occurred while roll-backing the current transaction", e);
} }
throw new DeviceManagementException("Error occurred while modifying the device " + throw new DeviceManagementException("Error occurred while modifying the device " +
"'" + device.getId() + "'", e); "'" + device.getId() + "'", e);
@ -414,13 +420,13 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
@Override @Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrollmentStatus status) throws DeviceManagementException { EnrolmentInfo.Status status) throws DeviceManagementException {
try { try {
DeviceManagementDAOFactory.beginTransaction(); DeviceManagementDAOFactory.beginTransaction();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
Device device = deviceDAO.getDevice(deviceId, tenantId); Device device = deviceDAO.getDevice(deviceId, tenantId);
boolean success = enrollmentDAO.setStatus(device.getId(), currentOwner, status.toString()); boolean success = enrolmentDAO.setStatus(device.getId(), currentOwner, status, tenantId);
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
return success; return success;
@ -513,7 +519,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
try { try {
DeviceManagementDAOFactory.getConnection(); DeviceManagementDAOFactory.getConnection();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userDevices = deviceDAO.getDeviceListOfUser(username, tenantId); userDevices = deviceDAO.getDevicesOfUser(username, tenantId);
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving the list of devices that " + throw new DeviceManagementException("Error occurred while retrieving the list of devices that " +
"belong to the user '" + username + "'", e); "belong to the user '" + username + "'", e);
@ -549,7 +555,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
tenantId).getUserStoreManager().getUserListOfRole(role); tenantId).getUserStoreManager().getUserListOfRole(role);
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new DeviceManagementException("Error occurred while obtaining the users, who are assigned " + throw new DeviceManagementException("Error occurred while obtaining the users, who are assigned " +
"with the role '"+ role + "'", e); "with the role '" + role + "'", e);
} }
List<Device> userDevices; List<Device> userDevices;
@ -557,7 +563,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
userDevices = new ArrayList<Device>(); userDevices = new ArrayList<Device>();
try { try {
DeviceManagementDAOFactory.getConnection(); DeviceManagementDAOFactory.getConnection();
userDevices = deviceDAO.getDeviceListOfUser(user, tenantId); userDevices = deviceDAO.getDevicesOfUser(user, tenantId);
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
log.error("Error occurred while obtaining the devices of user '" + user + "'", e); log.error("Error occurred while obtaining the devices of user '" + user + "'", e);
} finally { } finally {

@ -63,7 +63,7 @@ public class DeviceManagementBaseTest {
} }
private TestDBConfiguration getTestDBConfiguration(DBTypes dbType) throws DeviceManagementDAOException, private TestDBConfiguration getTestDBConfiguration(DBTypes dbType) throws DeviceManagementDAOException,
DeviceManagementException { DeviceManagementException {
File dbConfig = new File("src/test/resources/testdbconfig.xml"); File dbConfig = new File("src/test/resources/data-source-config.xml");
Document doc = DeviceManagerUtil.convertToDocument(dbConfig); Document doc = DeviceManagerUtil.convertToDocument(dbConfig);
TestDBConfigurations dbConfigs; TestDBConfigurations dbConfigs;
JAXBContext testDBContext; JAXBContext testDBContext;

@ -35,27 +35,27 @@ public class DeviceManagementRepositoryTests {
@Test @Test
public void testAddDeviceManagementService() { public void testAddDeviceManagementService() {
DeviceManagementService sourceProvider = new TestDeviceManager(); DeviceManagementService sourceProvider = new TestDeviceManagementService();
try { try {
this.getRepository().addDeviceManagementProvider(sourceProvider); this.getRepository().addDeviceManagementProvider(sourceProvider);
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
Assert.fail("Unexpected error occurred while invoking addDeviceManagementProvider functionality", e); Assert.fail("Unexpected error occurred while invoking addDeviceManagementProvider functionality", e);
} }
DeviceManager targetProvider = DeviceManager targetProvider =
this.getRepository().getDeviceManagementService(TestDeviceManager.DEVICE_TYPE_TEST); this.getRepository().getDeviceManagementService(TestDeviceManagementService.DEVICE_TYPE_TEST);
Assert.assertEquals(targetProvider.getProviderType(), sourceProvider.getProviderType()); Assert.assertEquals(targetProvider.getProviderType(), sourceProvider.getProviderType());
} }
@Test(dependsOnMethods = "testAddDeviceManagementService") @Test(dependsOnMethods = "testAddDeviceManagementService")
public void testRemoveDeviceManagementService() { public void testRemoveDeviceManagementService() {
DeviceManagementService sourceProvider = new TestDeviceManager(); DeviceManagementService sourceProvider = new TestDeviceManagementService();
try { try {
this.getRepository().removeDeviceManagementProvider(sourceProvider); this.getRepository().removeDeviceManagementProvider(sourceProvider);
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
Assert.fail("Unexpected error occurred while invoking removeDeviceManagementProvider functionality", e); Assert.fail("Unexpected error occurred while invoking removeDeviceManagementProvider functionality", e);
} }
DeviceManager targetProvider = DeviceManager targetProvider =
this.getRepository().getDeviceManagementService(TestDeviceManager.DEVICE_TYPE_TEST); this.getRepository().getDeviceManagementService(TestDeviceManagementService.DEVICE_TYPE_TEST);
Assert.assertNull(targetProvider); Assert.assertNull(targetProvider);
} }

@ -21,19 +21,17 @@ 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.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import java.util.List; import java.util.List;
public class TestDeviceManager implements DeviceManagementService { public class TestDeviceManagementService implements DeviceManagementService {
public static final String DEVICE_TYPE_TEST = "Test"; public static final String DEVICE_TYPE_TEST = "Test";
@Override @Override
public String getProviderType() { public String getProviderType() {
return TestDeviceManager.DEVICE_TYPE_TEST; return TestDeviceManagementService.DEVICE_TYPE_TEST;
} }
@Override @Override
@ -97,7 +95,8 @@ public class TestDeviceManager implements DeviceManagementService {
} }
@Override @Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, EnrollmentStatus status) throws DeviceManagementException { public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException {
return false; return false;
} }

@ -0,0 +1,83 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.core.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
public class ApplicationPersistenceDAOTests extends BaseDeviceManagementDAOTest {
private static final Log log = LogFactory.getLog(ApplicationPersistenceDAOTests.class);
private ApplicationDAO applicationDAO = DeviceManagementDAOFactory.getApplicationDAO();
@Test
public void testAddApplication() {
/* Initializing source application bean to be tested */
Application source = new Application();
source.setName("SimpleCalculator");
source.setCategory("TestCategory");
source.setPackageName("com.simple.calculator");
source.setType("TestType");
source.setVersion("1.0.0");
source.setImageUrl("http://test.org/image/");
source.setLocationUrl("http://test.org/location/");
/* Adding dummy application to the application store */
try {
DeviceManagementDAOFactory.openConnection();
applicationDAO.addApplication(source, -1234);
} catch (DeviceManagementDAOException e) {
log.error("Error occurred while adding application '" + source.getName() + "'", e);
} finally {
try {
DeviceManagementDAOFactory.closeConnection();
} catch (DeviceManagementDAOException e) {
log.warn("Error occurred while closing the connection", e);
}
}
/* Retrieving the application by its name */
Application target = null;
try {
target = this.getApplication(source.getPackageName(), -1234);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving application info";
log.error(msg, e);
Assert.fail(msg, e);
}
Assert.assertEquals(target, source, "Application added is not as same as what's retrieved");
}
private Application getApplication(String packageName, int tenantId) throws DeviceManagementDAOException {
try {
DeviceManagementDAOFactory.openConnection();
return applicationDAO.getApplication(packageName, tenantId);
} finally {
try {
DeviceManagementDAOFactory.closeConnection();
} catch (DeviceManagementDAOException e) {
log.warn("Error occurred while closing connection", e);
}
}
}
}

@ -0,0 +1,172 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.core.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.jdbc.pool.PoolProperties;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Parameters;
import org.w3c.dom.Document;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.TestUtils;
import org.wso2.carbon.device.mgt.core.common.DBTypes;
import org.wso2.carbon.device.mgt.core.common.TestDBConfiguration;
import org.wso2.carbon.device.mgt.core.common.TestDBConfigurations;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import javax.sql.DataSource;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class BaseDeviceManagementDAOTest {
private DataSource dataSource;
private static final Log log = LogFactory.getLog(BaseDeviceManagementDAOTest.class);
@BeforeSuite
public void setupDataSource() throws Exception {
this.dataSource = this.getDataSource(this.readDataSourceConfig());
this.initSQLScript();
DeviceManagementDAOFactory.init(dataSource);
}
private DataSource getDataSource(TestDBConfiguration config) {
PoolProperties properties = new PoolProperties();
properties.setUrl(config.getConnectionUrl());
properties.setDriverClassName(config.getDriverClass());
properties.setUsername(config.getUserName());
properties.setPassword(config.getPwd());
return new org.apache.tomcat.jdbc.pool.DataSource(properties);
}
private TestDBConfiguration readDataSourceConfig() throws DeviceManagementDAOException,
DeviceManagementException {
File config = new File("src/test/resources/data-source-config.xml");
Document doc;
TestDBConfigurations dbConfigs;
doc = DeviceManagerUtil.convertToDocument(config);
JAXBContext testDBContext;
try {
testDBContext = JAXBContext.newInstance(TestDBConfigurations.class);
Unmarshaller unmarshaller = testDBContext.createUnmarshaller();
dbConfigs = (TestDBConfigurations) unmarshaller.unmarshal(doc);
} catch (JAXBException e) {
throw new DeviceManagementDAOException("Error parsing test db configurations", e);
}
}
private void initSQLScript() throws Exception {
Connection conn = null;
Statement stmt = null;
try {
conn = this.getDataSource().getConnection();
stmt = conn.createStatement();
stmt.executeUpdate("RUNSCRIPT FROM './src/test/resources/sql/h2.sql'");
} finally {
TestUtils.cleanupResources(conn, stmt, null);
}
}
@AfterSuite
public void deleteData() {
Connection conn = null;
try {
conn = getDataSource().getConnection();
conn.setAutoCommit(false);
this.cleanupEnrolmentData(conn);
this.cleanupDeviceData(conn);
this.cleanupDeviceTypeData(conn);
conn.commit();
} catch (SQLException e) {
try {
if (conn != null) {
conn.rollback();
}
} catch (SQLException e1) {
log.error("Error occurred while roll-backing the transaction", e);
}
String msg = "Error occurred while cleaning up temporary data generated during test execution";
log.error(msg, e);
Assert.fail(msg, e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing the connection", e);
}
}
}
}
private void cleanupEnrolmentData(Connection conn) throws SQLException {
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement("DELETE FROM DM_ENROLMENT");
stmt.execute();
} finally {
if (stmt != null) {
stmt.close();
}
}
}
private void cleanupDeviceData(Connection conn) throws SQLException {
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement("DELETE FROM DM_DEVICE");
stmt.execute();
} finally {
if (stmt != null) {
stmt.close();
}
}
}
private void cleanupDeviceTypeData(Connection conn) throws SQLException {
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_TYPE");
stmt.execute();
} finally {
if (stmt != null) {
stmt.close();
}
}
}
public DataSource getDataSource() {
return dataSource;
}
}

@ -20,179 +20,238 @@ package org.wso2.carbon.device.mgt.core.dao;
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.apache.tomcat.jdbc.pool.PoolProperties;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.wso2.carbon.device.mgt.common.Device; 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.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo.OwnerShip; import org.wso2.carbon.device.mgt.common.EnrolmentInfo.OwnerShip;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo.Status; import org.wso2.carbon.device.mgt.common.EnrolmentInfo.Status;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.TestUtils; import org.wso2.carbon.device.mgt.core.TestUtils;
import org.wso2.carbon.device.mgt.core.common.DBTypes;
import org.wso2.carbon.device.mgt.core.common.TestDBConfiguration;
import org.wso2.carbon.device.mgt.core.common.TestDBConfigurations;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import javax.sql.DataSource;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.sql.*; import java.sql.*;
import java.util.Date; import java.util.Date;
public class DeviceManagementDAOTests { public class DeviceManagementDAOTests extends BaseDeviceManagementDAOTest {
DeviceDAO deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
private DataSource dataSource;
private static final Log log = LogFactory.getLog(DeviceManagementDAOTests.class); private static final Log log = LogFactory.getLog(DeviceManagementDAOTests.class);
@AfterClass @BeforeClass
public void deleteData() throws Exception { public void init() {
Connection connection = dataSource.getConnection();
connection.createStatement().execute("DELETE FROM DM_DEVICE");
connection.createStatement().execute("DELETE FROM DM_DEVICE_TYPE");
} }
@BeforeClass @Test
@Parameters("dbType") public void testAddDeviceTypeTest() {
public void setUpDB(String dbTypeStr) throws Exception { DeviceType deviceType = this.loadDummyDeviceType();
DBTypes dbType = DBTypes.valueOf(dbTypeStr); try {
TestDBConfiguration dbConfig = getTestDBConfiguration(dbType); DeviceManagementDAOFactory.openConnection();
deviceTypeDAO.addDeviceType(deviceType);
switch (dbType) { } catch (DeviceManagementDAOException e) {
case H2: String msg = "Error occurred while adding device type '" + deviceType.getName() + "'";
PoolProperties properties = new PoolProperties(); log.error(msg, e);
properties.setUrl(dbConfig.getConnectionUrl()); Assert.fail(msg, e);
properties.setDriverClassName(dbConfig.getDriverClass()); } finally {
properties.setUsername(dbConfig.getUserName()); try {
properties.setPassword(dbConfig.getPwd()); DeviceManagementDAOFactory.closeConnection();
dataSource = new org.apache.tomcat.jdbc.pool.DataSource(properties); } catch (DeviceManagementDAOException e) {
this.initSQLScript(); log.warn("Error occurred while closing the connection", e);
DeviceManagementDAOFactory.init(dataSource); }
default: }
int targetTypeId = -1;
try {
targetTypeId = this.getDeviceTypeId();
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving target device type id";
log.error(msg, e);
Assert.fail(msg, e);
} }
Assert.assertNotNull(targetTypeId, "Device Type Id is null");
deviceType.setId(targetTypeId);
} }
private TestDBConfiguration getTestDBConfiguration(DBTypes dbType) throws DeviceManagementDAOException, @Test(dependsOnMethods = {"testAddDeviceTypeTest"})
DeviceManagementException { public void testAddDeviceTest() {
File deviceMgtConfig = new File("src/test/resources/testdbconfig.xml"); DeviceType deviceType = this.loadDummyDeviceType();
Document doc; deviceType.setId(1);
TestDBConfigurations dbConfigs;
doc = DeviceManagerUtil.convertToDocument(deviceMgtConfig); int tenantId = -1234;
JAXBContext testDBContext; Device device = this.loadDummyDevice();
try {
DeviceManagementDAOFactory.openConnection();
int deviceId = deviceDAO.addDevice(deviceType.getId(), device, tenantId);
device.setId(deviceId);
deviceDAO.addEnrollment(device, tenantId);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while adding '" + device.getType() + "' device with the identifier '" +
device.getDeviceIdentifier() + "'";
log.error(msg, e);
Assert.fail(msg, e);
} finally {
try {
DeviceManagementDAOFactory.closeConnection();
} catch (DeviceManagementDAOException e) {
log.warn("Error occurred while closing the connection", e);
}
}
int targetId = -1;
try { try {
testDBContext = JAXBContext.newInstance(TestDBConfigurations.class); targetId = this.getDeviceId();
Unmarshaller unmarshaller = testDBContext.createUnmarshaller(); } catch (DeviceManagementDAOException e) {
dbConfigs = (TestDBConfigurations) unmarshaller.unmarshal(doc); String msg = "Error occurred while retrieving device id";
} catch (JAXBException e) { log.error(msg, e);
throw new DeviceManagementDAOException("Error parsing test db configurations", e); Assert.fail(msg, e);
} }
for (TestDBConfiguration config : dbConfigs.getDbTypesList()) { Assert.assertNotNull(targetId, "Device Id persisted in device management metadata repository upon '" +
if (config.getDbType().equals(dbType.toString())) { device.getType() + "' carrying the identifier '" + device.getDeviceIdentifier() + "', is null");
return config; }
private void addDeviceEnrolment() {
Device device = this.loadDummyDevice();
try {
DeviceManagementDAOFactory.openConnection();
deviceDAO.addEnrollment(device, -1234);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while adding enrolment configuration upon '" + device.getType() +
"' device with the identifier '" + device.getDeviceIdentifier() + "'";
log.error(msg, e);
Assert.fail(msg, e);
} finally {
try {
DeviceManagementDAOFactory.closeConnection();
} catch (DeviceManagementDAOException e) {
log.warn("Error occurred while closing the connection", e);
} }
} }
return null;
} }
private void initSQLScript() throws Exception { private int getDeviceId() throws DeviceManagementDAOException {
Connection conn = null; Connection conn = null;
Statement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null;
int id = -1;
try { try {
conn = this.getDataSource().getConnection(); conn = getDataSource().getConnection();
stmt = conn.createStatement(); String sql = "SELECT ID FROM DM_DEVICE WHERE DEVICE_IDENTIFICATION = ? AND TENANT_ID = ?";
stmt.executeUpdate("RUNSCRIPT FROM './src/test/resources/sql/h2.sql'"); stmt = conn.prepareStatement(sql);
stmt.setString(1, "111");
stmt.setInt(2, -1234);
rs = stmt.executeQuery();
if (rs.next()) {
id = rs.getInt("ID");
}
return id;
} catch (SQLException e) {
String msg = "Error in fetching device by device identification id";
throw new DeviceManagementDAOException(msg, e);
} finally { } finally {
TestUtils.cleanupResources(conn, stmt, null); TestUtils.cleanupResources(conn, stmt, rs);
} }
} }
@Test private int getDeviceTypeId() throws DeviceManagementDAOException {
public void addDeviceTypeTest() throws DeviceManagementDAOException, DeviceManagementException {
DeviceTypeDAO deviceTypeMgtDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
DeviceType deviceType = new DeviceType();
deviceType.setName("IOS");
deviceTypeMgtDAO.addDeviceType(deviceType);
int id = -1; int id = -1;
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
String sql = "SELECT dt.ID, dt.NAME FROM DM_DEVICE_TYPE dt where dt.NAME = 'IOS'"; String sql = "SELECT ID, NAME FROM DM_DEVICE_TYPE WHERE NAME = ?";
DeviceType deviceType = this.loadDummyDeviceType();
try { try {
conn = this.getDataSource().getConnection(); conn = getDataSource().getConnection();
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceType.getName());
ResultSet rs = stmt.executeQuery(); ResultSet rs = stmt.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt("ID"); id = rs.getInt("ID");
} }
return id;
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("error in fetch device type by name IOS", e); String msg = "Error in fetching device type by name IOS";
throw new DeviceManagementDAOException(msg, e);
} finally { } finally {
TestUtils.cleanupResources(conn, stmt, null); TestUtils.cleanupResources(conn, stmt, null);
} }
Assert.assertNotNull(id, "Device Type Id is null");
deviceType.setId(id);
} }
@Test(dependsOnMethods = {"addDeviceTypeTest"}) @Test(dependsOnMethods = "testAddDeviceTest")
public void addDeviceTest() throws DeviceManagementDAOException, DeviceManagementException { public void testSetEnrolmentStatus() {
DeviceDAO deviceMgtDAO = DeviceManagementDAOFactory.getDeviceDAO(); Device device = this.loadDummyDevice();
try {
DeviceManagementDAOFactory.openConnection();
DeviceIdentifier deviceId = new DeviceIdentifier(device.getDeviceIdentifier(), device.getType());
deviceDAO.setEnrolmentStatus(deviceId, device.getEnrolmentInfo().getOwner(), Status.ACTIVE, -1234);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while setting enrolment status";
log.error(msg, e);
Assert.fail(msg, e);
} finally {
try {
DeviceManagementDAOFactory.closeConnection();
} catch (DeviceManagementDAOException e) {
log.warn("Error occurred while closing the connection", e);
}
}
Status target = null;
try {
target = this.getEnrolmentStatus();
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving the target enrolment status";
log.error(msg, e);
Assert.fail(msg, e);
}
Assert.assertNotNull(target, "Enrolment status retrieved for the device carrying its identifier as '" +
device.getDeviceIdentifier() + "' is null");
Assert.assertEquals(target, Status.ACTIVE, "Enrolment status retrieved is not as same as what's configured");
}
private Status getEnrolmentStatus() throws DeviceManagementDAOException {
Device device = this.loadDummyDevice();
try {
DeviceManagementDAOFactory.openConnection();
DeviceIdentifier deviceId = new DeviceIdentifier(device.getDeviceIdentifier(), device.getType());
return deviceDAO.getEnrolmentStatus(deviceId, device.getEnrolmentInfo().getOwner(), -1234);
} catch (DeviceManagementDAOException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the current status of the " +
"enrolment", e);
} finally {
try {
DeviceManagementDAOFactory.closeConnection();
} catch (DeviceManagementDAOException e) {
log.warn("Error occurred while closing the connection", e);
}
}
}
private Device loadDummyDevice() {
Device device = new Device(); Device device = new Device();
EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime()); enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setOwner("admin");
enrolmentInfo.setOwnership(OwnerShip.BYOD);
enrolmentInfo.setStatus(Status.CREATED);
device.setEnrolmentInfo(enrolmentInfo); device.setEnrolmentInfo(enrolmentInfo);
device.setDescription("test description"); device.setDescription("Test Description");
device.getEnrolmentInfo().setStatus(Status.ACTIVE); device.setDeviceIdentifier("1234");
device.setDeviceIdentifier("111"); return device;
DeviceType deviceType = new DeviceType();
deviceType.setId(Integer.parseInt("1"));
device.getEnrolmentInfo().setOwnership(OwnerShip.BYOD);
device.getEnrolmentInfo().setOwner("111");
deviceMgtDAO.addDevice(deviceType.getId(), device, -1234);
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Long id = null;
String status = null;
try {
conn = this.getDataSource().getConnection();
String sql = "SELECT ID, STATUS FROM DM_DEVICE where DEVICE_IDENTIFICATION = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, "111");
rs = stmt.executeQuery();
if (rs.next()) {
id = rs.getLong("ID");
status = rs.getString("STATUS");
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error in fetch device by device identification id", e);
} finally {
TestUtils.cleanupResources(conn, stmt, rs);
}
Assert.assertNotNull(id, "Device Id is null");
Assert.assertNotNull(status, "Device status is null");
Assert.assertEquals(status, "ACTIVE", "Enroll device status should active");
} }
private DataSource getDataSource() { private DeviceType loadDummyDeviceType() {
return dataSource; return new DeviceType("iOS");
} }
} }

@ -0,0 +1,85 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.core.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import java.util.Date;
public class EnrolmentPersistenceDAOTests extends BaseDeviceManagementDAOTest {
private static final Log log = LogFactory.getLog(EnrolmentPersistenceDAOTests.class);
private EnrolmentDAO enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
@Test
public void testAddEnrolment() {
int deviceId = 1234;
String owner = "admin";
/* Initializing source enrolment configuration bean to be tested */
EnrolmentInfo source =
new EnrolmentInfo(null, owner, EnrolmentInfo.OwnerShip.BYOD,
EnrolmentInfo.Status.CREATED);
/* Adding dummy enrolment configuration to the device management metadata store */
try {
DeviceManagementDAOFactory.openConnection();
enrolmentDAO.addEnrollment(deviceId, source, -1234);
} catch (DeviceManagementDAOException e) {
log.error("Error occurred while adding enrollment", e);
} finally {
try {
DeviceManagementDAOFactory.closeConnection();
} catch (DeviceManagementDAOException e) {
log.warn("Error occurred while closing the connection", e);
}
}
/* Retrieving the enrolment associated with the given deviceId and owner */
EnrolmentInfo target = null;
try {
target = this.getEnrolmentConfig(deviceId, owner, -1234);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving application info";
log.error(msg, e);
Assert.fail(msg, e);
}
Assert.assertEquals(target, source, "Enrolment configuration added is not as same as what's retrieved");
}
private EnrolmentInfo getEnrolmentConfig(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
try {
DeviceManagementDAOFactory.openConnection();
return enrolmentDAO.getEnrolment(deviceId, currentOwner, tenantId);
} finally {
try {
DeviceManagementDAOFactory.closeConnection();
} catch (DeviceManagementDAOException e) {
log.warn("Error occurred while closing connection", e);
}
}
}
}

@ -17,11 +17,9 @@
~ under the License. ~ under the License.
--> -->
<DeviceMgtTestDBConfigurations> <DataSourceConfig>
<DBType typeName="H2"> <Url>jdbc:h2:mem:cdm-test-db;DB_CLOSE_DELAY=-1</Url>
<connectionurl>jdbc:h2:mem:cdm-test-db;DB_CLOSE_DELAY=-1</connectionurl> <DriverClassName>org.h2.Driver</DriverClassName>
<driverclass>org.h2.Driver</driverclass> <User>wso2carbon</User>
<userName>wso2carbon</userName> <Password>wso2carbon</Password>
<pwd>wso2carbon</pwd> </DataSourceConfig>
</DBType>
</DeviceMgtTestDBConfigurations>

@ -8,13 +8,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE (
ID INTEGER auto_increment NOT NULL, ID INTEGER auto_increment NOT NULL,
DESCRIPTION TEXT NULL DEFAULT NULL, DESCRIPTION TEXT NULL DEFAULT NULL,
NAME VARCHAR(100) NULL DEFAULT NULL, NAME VARCHAR(100) NULL DEFAULT NULL,
DATE_OF_ENROLLMENT BIGINT NULL DEFAULT NULL,
DATE_OF_LAST_UPDATE BIGINT NULL DEFAULT NULL,
OWNERSHIP VARCHAR(45) NULL DEFAULT NULL,
STATUS VARCHAR(15) NULL DEFAULT NULL,
DEVICE_TYPE_ID INT(11) NULL DEFAULT NULL, DEVICE_TYPE_ID INT(11) NULL DEFAULT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) NULL DEFAULT NULL, DEVICE_IDENTIFICATION VARCHAR(300) NULL DEFAULT NULL,
OWNER VARCHAR(45) NULL DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0, TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID ) CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID )
@ -67,15 +62,43 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_MAPPING (
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_ENROLLMENT ( CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
ID INTEGER AUTO_INCREMENT NOT NULL, ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL, DEVICE_ID INTEGER NOT NULL,
OWNER VARCHAR(50) NOT NULL, OWNER VARCHAR(50) NOT NULL,
OWNERSHIP VARCHAR(45) NULL DEFAULT NULL, OWNERSHIP VARCHAR(45) NULL DEFAULT NULL,
STATUS VARCHAR(50) NULL, STATUS VARCHAR(50) NULL,
DATE_OF_ENROLLMENT BIGINT NULL DEFAULT NULL, DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL,
DATE_OF_LAST_UPDATE BIGINT NULL DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL,
TENANT_ID INT NOT NULL,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_enrollment FOREIGN KEY (DEVICE_ID) REFERENCES CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_APPLICATION (
ID INTEGER AUTO_INCREMENT NOT NULL,
NAME VARCHAR(50) NOT NULL,
PACKAGE_NAME VARCHAR(50) NOT NULL,
PLATFORM VARCHAR(50) NULL DEFAULT NULL,
CATEGORY VARCHAR(50) NULL,
VERSION VARCHAR(50) NULL,
TYPE VARCHAR(50) NULL,
LOCATION_URL VARCHAR(100) NULL DEFAULT NULL,
IMAGE_URL VARCHAR(100) NULL DEFAULT NULL,
TENANT_ID INTEGER NOT NULL,
PRIMARY KEY (ID)
);
CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
APPLICATION_ID INTEGER NOT NULL,
TENANT_ID INTEGER NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_application FOREIGN KEY (APPLICATION_ID) REFERENCES
DM_APPLICATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);

@ -19,16 +19,18 @@
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="EMM-core-initializer"> <suite name="DeviceManagementCore">
<parameter name="useDefaultListeners" value="false"/> <parameter name="useDefaultListeners" value="false"/>
<test name="DAO Unit Tests" preserve-order="true"> <test name="DAO Unit Tests" preserve-order="true">
<parameter name="dbType" value="H2"/> <parameter name="databaseType" value="H2"/>
<classes> <classes>
<class name="org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOTests"/> <class name="org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOTests"/>
<class name="org.wso2.carbon.device.mgt.core.DeviceManagementRepositoryTests"/> <class name="org.wso2.carbon.device.mgt.core.DeviceManagementRepositoryTests"/>
<class name="org.wso2.carbon.device.mgt.core.DeviceManagementConfigTests"/> <class name="org.wso2.carbon.device.mgt.core.DeviceManagementConfigTests"/>
<class name="org.wso2.carbon.device.mgt.core.DeviceOperationManagementTests"/> <!--class name="org.wso2.carbon.device.mgt.core.DeviceOperationManagementTests"/-->
<class name="org.wso2.carbon.device.mgt.core.dao.ApplicationPersistenceDAOTests"/>
<!--class name="org.wso2.carbon.device.mgt.core.dao.EnrolmentPersistenceDAOTests"/-->
</classes> </classes>
</test> </test>
</suite> </suite>

@ -112,7 +112,7 @@ public class PolicyDAOTestCase {
private TestDBConfiguration getTestDBConfiguration(DBTypes dbType) throws PolicyManagerDAOException, private TestDBConfiguration getTestDBConfiguration(DBTypes dbType) throws PolicyManagerDAOException,
PolicyManagementException { PolicyManagementException {
File deviceMgtConfig = new File("src/test/resources/testdbconfig.xml"); File deviceMgtConfig = new File("src/test/resources/data-source-config.xml");
Document doc; Document doc;
TestDBConfigurations dbConfigs; TestDBConfigurations dbConfigs;

Loading…
Cancel
Save