revert-70aa11f8
geethkokila 10 years ago
commit 524ce44036

@ -32,6 +32,19 @@ public class Device {
private List<Feature> features;
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() {
return id;
}
@ -118,4 +131,19 @@ public class Device {
}
}
@Override
public String toString() {
return "Device[" +
"name=" + name + ";" +
"type=" + type + ";" +
"description=" + description + ";" +
"identifier=" + deviceIdentifier + ";" +
// "EnrolmentInfo[" +
// "owner=" + enrolmentInfo.getOwner() + ";" +
// "ownership=" + enrolmentInfo.getOwnership() + ";" +
// "status=" + enrolmentInfo.getStatus() + ";" +
// "]" +
"]";
}
}

@ -24,11 +24,6 @@ import java.util.List;
* device type plugin implementation intended to be managed through CDM.
*/
public interface DeviceManager {
enum EnrollmentStatus {
CREATED, ACTIVE, INACTIVE, SUSPENDED, BLOCKED, REMOVED
}
/**
* Method to retrieve the provider type that implements DeviceManager interface.
*
@ -138,6 +133,6 @@ public interface DeviceManager {
boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException;
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 enum Status {
CREATED, ACTIVE, INACTIVE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED
}
public enum OwnerShip {
BYOD, COPE
}
private Device device;
private Long dateOfEnrolment;
private Long dateOfLastUpdate;
private OwnerShip ownership;
private Status status;
private String owner;
public static enum Status {
CREATED, ACTIVE, INACTIVE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED
}
public EnrolmentInfo() {}
public static enum OwnerShip {
BYOD, COPE
public EnrolmentInfo(Device device, String owner, OwnerShip ownership, Status status) {
this.device = device;
this.owner = owner;
this.ownership = ownership;
this.status = status;
}
public Long getDateOfEnrolment() {
@ -74,4 +84,12 @@ public class EnrolmentInfo {
this.owner = owner;
}
public Device getDevice() {
return device;
}
public void setDevice(Device device) {
this.device = device;
}
}

@ -18,12 +18,12 @@
*/
package org.wso2.carbon.device.mgt.common.app.mgt;
import java.util.List;
import java.io.Serializable;
import java.util.Properties;
public class Application {
public class Application implements Serializable {
private String id;
private int id;
private String packageName;
private String platform;
private String category;
@ -51,11 +51,11 @@ public class Application {
}
public String getId() {
public int getId() {
return id;
}
public void setId(String id) {
public void setId(int id) {
this.id = id;
}
@ -109,6 +109,14 @@ public class Application {
this.category = category;
}
public boolean equals(Object o) {
if (!(o instanceof Application)) {
return false;
}
Application target = (Application)o;
return packageName.equals(target.getPackageName());
}
public Properties getAppProperties() {
return appProperties;
}
@ -117,5 +125,4 @@ public class Application {
this.appProperties = appProperties;
}
}

@ -1,14 +1,7 @@
package org.wso2.carbon.device.mgt.core.api.mgt;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import java.util.List;
public interface ApplicationManagementProviderService extends ApplicationManager {
void updateApplicationListInstallInDevice(DeviceIdentifier deviceIdentifier, List<Application> applications)
throws ApplicationManagementException;
}

@ -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.config.DeviceConfigurationManager;
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.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.*;
import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceException;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
@ -52,7 +50,6 @@ import java.util.List;
/**
* Implements Application Manager interface
*
*/
public class ApplicationManagerProviderServiceImpl implements ApplicationManagementProviderService,
PluginInitializationListener {
@ -62,13 +59,15 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
private String oAuthAdminServiceUrl;
private DeviceManagementPluginRepository pluginRepository;
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 Log log = LogFactory.getLog(ApplicationManagerProviderServiceImpl.class);
public ApplicationManagerProviderServiceImpl(AppManagementConfig appManagementConfig,
DeviceManagementPluginRepository pluginRepository) {
DeviceManagementPluginRepository pluginRepository) {
IdentityConfigurations identityConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().
getDeviceManagementConfigRepository().getIdentityConfigurations();
@ -84,6 +83,8 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
}
this.pluginRepository = pluginRepository;
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
this.applicationDAO = DeviceManagementDAOFactory.getApplicationDAO();
this.applicationMappingDAO = DeviceManagementDAOFactory.getApplicationMappingDAO();
}
@Override
@ -100,7 +101,7 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
@Override
public String getApplicationStatus(DeviceIdentifier deviceId,
Application application) throws ApplicationManagementException {
Application application) throws ApplicationManagementException {
return null;
}
@ -159,17 +160,17 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
return pluginRepository;
}
@Override
public void updateApplicationListInstallInDevice(DeviceIdentifier deviceIdentifier,List<Application> applications)
throws ApplicationManagementException {
public void updateApplicationListInstallInDevice(
DeviceIdentifier deviceIdentifier, List<Application> applications) throws ApplicationManagementException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);
deviceDAO.addDeviceApplications(device.getId(), applications);
}catch (DeviceManagementDAOException deviceDaoEx){
Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);
List<Integer> applicationIds = applicationDAO.addApplications(applications, tenantId);
applicationMappingDAO.addApplicationMappings(device.getId(), applicationIds, tenantId);
} catch (DeviceManagementDAOException deviceDaoEx) {
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);
}
}

@ -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;
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;
boolean setStatus(int deviceId, String currentOwner, String status) throws DeviceManagementDAOException;
boolean getStatus() throws DeviceManagementDAOException;
int removeApplicationMapping(int deviceId, int applicationId, int tenantId) 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.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.app.mgt.Application;
@ -30,50 +31,50 @@ import java.util.List;
*/
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 tenantId) throws DeviceManagementDAOException;
int removeDevice(DeviceIdentifier deviceId, 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;
int getDeviceCount(int tenantId) throws DeviceManagementDAOException;
List<Device> getDevicesByName(String deviceName, int tenantId) 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;
/**
* @param type - The device type id.
* @return a list of devices based on the type id.
* Get the list of devices that matches with the given device name.
*
* @param id Name of the device
* @param applications List of applications
* @throws DeviceManagementDAOException
*/
List<Device> getDevices(String type, int tenantId) throws DeviceManagementDAOException;
void addDeviceApplications(int id, Object applications) throws DeviceManagementDAOException;
/**
* Get the list of devices belongs to a user.
* @param username Requested user.
* @return List of devices of the user.
* Get the list of devices that matches with the given device name.
*
* @param deviceId device id of the device
* @return List of Applications that are installed on the given device.
* @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;
/**
* 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;
void addDeviceApplications(int id, Object applications) throws DeviceManagementDAOException;
List<Application> getInstalledApplications(int deviceId) throws DeviceManagementDAOException;
}

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

@ -18,92 +18,96 @@
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.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.Status;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo.OwnerShip;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DeviceDAOImpl implements DeviceDAO {
private static final Log log = LogFactory.getLog(DeviceDAOImpl.class);
@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;
PreparedStatement stmt = null;
ResultSet rs = null;
int deviceId = -1;
try {
conn = this.getConnection();
String sql =
"INSERT INTO DM_DEVICE(DESCRIPTION, NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, " +
"OWNERSHIP, STATUS, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, OWNER, TENANT_ID) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql);
"INSERT INTO DM_DEVICE(DESCRIPTION, NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, TENANT_ID) " +
"VALUES (?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, device.getDescription());
stmt.setString(2, device.getName());
stmt.setLong(3, new Date().getTime());
stmt.setLong(4, new Date().getTime());
stmt.setString(5, device.getEnrolmentInfo().getOwnership().toString());
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.setInt(3, typeId);
stmt.setString(4, device.getDeviceIdentifier());
stmt.setInt(5, tenantId);
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
deviceId = rs.getInt(1);
}
return deviceId;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while enrolling device " +
"'" + device.getName() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@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;
PreparedStatement stmt = null;
ResultSet rs = null;
int deviceId = -1;
try {
conn = this.getConnection();
String sql = "UPDATE DM_DEVICE SET STATUS = ?, OWNER = ?, DATE_OF_ENROLLMENT=?, " +
"DATE_OF_LAST_UPDATE=? WHERE DEVICE_IDENTIFICATION = ? AND TENANT_ID = ? AND DEVICE_TYPE_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, device.getEnrolmentInfo().getStatus().toString());
stmt.setString(2, device.getEnrolmentInfo().getOwner());
stmt.setLong(3, device.getEnrolmentInfo().getDateOfEnrolment());
stmt.setLong(4, device.getEnrolmentInfo().getDateOfLastUpdate());
stmt.setString(5, device.getDeviceIdentifier());
stmt.setInt(6, typeId);
stmt.setInt(7, tenantId);
String sql = "UPDATE DM_DEVICE SET DESCRIPTION = ?, NAME = ? WHERE DEVICE_IDENTIFICATION = ? AND " +
"DEVICE_TYPE_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, device.getDescription());
stmt.setString(2, device.getName());
stmt.setString(3, device.getDeviceIdentifier());
stmt.setInt(4, typeId);
stmt.setInt(5, tenantId);
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
deviceId = rs.getInt(1);
}
return deviceId;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while enrolling device '" +
device.getName() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public void updateDeviceStatus(DeviceIdentifier deviceId, Status status,
int tenantId) throws DeviceManagementDAOException {
}
@Override
public void deleteDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException {
public int removeDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException {
return 0;
}
@Override
@ -115,13 +119,15 @@ public class DeviceDAOImpl implements DeviceDAO {
try {
conn = this.getConnection();
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, " +
"d.DEVICE_TYPE_ID, d.DEVICE_IDENTIFICATION, d.OWNER, d.TENANT_ID, dt.NAME AS DEVICE_TYPE_NAME FROM DM_DEVICE d, DM_DEVICE_TYPE dt WHERE " +
"dt.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?";
"SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " +
"t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " +
"t.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceId.getType());
stmt.setString(2, deviceId.getId());
stmt.setInt(3, tenantId);
stmt.setInt(4, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
device = this.loadDevice(rs);
@ -143,12 +149,13 @@ public class DeviceDAOImpl implements DeviceDAO {
List<Device> devices = null;
try {
conn = this.getConnection();
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, d.DEVICE_TYPE_ID, " +
"d.DEVICE_IDENTIFICATION, d.OWNER, d.TENANT_ID, t.NAME AS DEVICE_TYPE_NAME FROM DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ";
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME," +
"d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DEVICE_TYPE t " +
"WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
devices = new ArrayList<Device>();
while (rs.next()) {
@ -172,12 +179,14 @@ public class DeviceDAOImpl implements DeviceDAO {
List<Device> devices = null;
try {
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, " +
"d.OWNERSHIP, d.STATUS, d.DEVICE_TYPE_ID, d.DEVICE_IDENTIFICATION, d.OWNER, d.TENANT_ID,t.NAME AS DEVICE_TYPE_NAME FROM DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE d.DM_DEVICE.DEVICE_TYPE_ID = t.ID AND t.NAME = ? AND d.TENANT_ID = ?";
String selectDBQueryForType = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " +
"d.DEVICE_IDENTIFICATION, d.OWNER, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE d.DM_DEVICE.DEVICE_TYPE_ID = t.ID AND t.NAME = ? AND d.TENANT_ID = ?) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?";
stmt = conn.prepareStatement(selectDBQueryForType);
stmt.setString(1, type);
stmt.setInt(2, tenantId);
stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
devices = new ArrayList<Device>();
while (rs.next()) {
@ -193,21 +202,20 @@ public class DeviceDAOImpl implements DeviceDAO {
}
@Override
public List<Device> getDeviceListOfUser(String username, int tenantId) throws DeviceManagementDAOException {
public List<Device> getDevicesOfUser(String username, int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
List<Device> devices = new ArrayList<Device>();
try {
conn = this.getConnection();
stmt = conn.prepareStatement(
"SELECT t.NAME AS DEVICE_TYPE_NAME, 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, 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 " +
"AND d.OWNER =? AND d.TENANT_ID = ?");
"SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d.DEVICE_IDENTIFICATION" +
" e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e, (SELECT t.NAME AS DEVICE_TYPE, d.ID, d.DESCRIPTION, " +
"d.NAME, d.DEVICE_IDENTIFICATION FROM " +
"DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.OWNER =? AND d.TENANT_ID = ?) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?");
stmt.setString(1, username);
stmt.setInt(2, tenantId);
stmt.setInt(3, tenantId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
@ -259,8 +267,8 @@ public class DeviceDAOImpl implements DeviceDAO {
/**
* Get the list of devices that matches with the given device name.
*
* @param deviceName Name of the device.
* @param tenantId Id of the current tenant
* @param deviceName Name of the device.
* @param tenantId Id of the current tenant
* @return device list
* @throws DeviceManagementDAOException
*/
@ -272,14 +280,15 @@ public class DeviceDAOImpl implements DeviceDAO {
try {
conn = this.getConnection();
stmt = conn.prepareStatement(
"SELECT d.ID AS DEVICE_ID, d.NAME AS DEVICE_NAME, t.ID AS DEVICE_TYPE_ID, d.DESCRIPTION, " +
"t.NAME AS DEVICE_TYPE_NAME, d.DATE_OF_ENROLLMENT, d.DATE_OF_LAST_UPDATE, " +
"d.OWNERSHIP, d.STATUS, d.DEVICE_TYPE_ID, " +
"d.DEVICE_IDENTIFICATION, d.OWNER, d.TENANT_ID FROM " +
"SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d.DEVICE_IDENTIFICATION " +
"e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, d.NAME, d.DESCRIPTION, " +
"t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM " +
"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 = ?) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?");
stmt.setString(1, deviceName + "%");
stmt.setInt(2, tenantId);
stmt.setInt(3, tenantId);
stmt.setInt(4, tenantId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
@ -296,47 +305,187 @@ public class DeviceDAOImpl implements DeviceDAO {
}
@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;
PreparedStatement stmt = null;
try {
conn = this.getConnection();
String sql = "INSERT INTO DM_DEVICE_APPLICATIONS(DEVICE_ID, APPLICATIONS) " +
"VALUES (?, ?)";
String sql = "UPDATE DM_ENROLMENT SET STATUS = ? 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.setInt(1, deviceId);
stmt.setObject(2, appList);
stmt.setString(1, status.toString());
stmt.setString(2, deviceId.getId());
stmt.setString(3, deviceId.getType());
stmt.setInt(4, tenantId);
stmt.setString(5, currentOwner);
stmt.setInt(6, 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 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);
}
}
@Override
public void addDeviceApplications(int id, Object applications) throws DeviceManagementDAOException {
}
@Override
public List<Application> getInstalledApplications(int deviceId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
List<Application> applications = new ArrayList<Application>();
Application application;
ByteArrayInputStream bais;
ObjectInputStream ois;
try {
conn = this.getConnection();
stmt = conn.prepareStatement(
"SELECT DEVICE_ID, APPLICATIONS FROM DM_DEVICE_APPLICATIONS WHERE DEVICE_ID = ?");
stmt.setInt(1, deviceId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
byte[] applicationDetails = rs.getBytes("APPLICATIONS");
bais = new ByteArrayInputStream(applicationDetails);
ois = new ObjectInputStream(bais);
application = (Application) ois.readObject();
applications.add(application);
}
} catch (IOException e) {
throw new DeviceManagementDAOException("IO Error occurred while de serialize the Application object", e);
} catch (ClassNotFoundException e) {
throw new DeviceManagementDAOException("Class not found error occurred while de serialize the " +
"Application object", e);
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while update application list for device " +
"'" + deviceId + "'", e);
throw new DeviceManagementDAOException("SQL Error occurred while retrieving the list of Applications " +
"installed in device id '" + deviceId, e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return applications;
}
private Device loadDevice(ResultSet rs) throws SQLException {
Device device = new Device();
DeviceType deviceType = new DeviceType();
deviceType.setId(rs.getInt("DEVICE_TYPE_ID"));
deviceType.setName(rs.getString("DEVICE_TYPE_NAME"));
device.setId(rs.getInt("DEVICE_ID"));
device.setName(rs.getString("DEVICE_NAME"));
device.setDescription(rs.getString("DESCRIPTION"));
device.setType(rs.getString("DEVICE_TYPE_NAME"));
device.setType(rs.getString("DEVICE_TYPE"));
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.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"));
device.setEnrolmentInfo(enrolmentInfo);
return device;
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;
}
}

@ -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 String name;
public DeviceType() {
}
public DeviceType(String name) {
this.name = name;
}
public int getId() {
return id;
}

@ -74,7 +74,7 @@ public class OperationManagementDAOFactory {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while retrieving datasource connection", e);
throw new OperationManagementDAOException("Error occurred while retrieving config.datasource connection", e);
}
}

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

@ -82,10 +82,22 @@ public interface DeviceManagementProviderService extends DeviceManager, LicenseM
* The method to get application list installed for the device.
*
* @param deviceIdentifier
* @return
* @return List of applications installed on the device
* @throws DeviceManagementException
*/
List<Application> getApplicationListForDevice(DeviceIdentifier deviceIdentifier) throws DeviceManagementException;
/**
* The method to get application list installed for the device.
*
* @param deviceIdentifier device identifier of the device
* @param applications List of installed Applications
*
* @throws DeviceManagementException
*/
void updateInstalledApplicationListOfDevice(DeviceIdentifier deviceIdentifier, List<Application> applications)
throws DeviceManagementException;
void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status active) throws DeviceManagementException;
}

@ -21,7 +21,6 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
@ -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.email.NotificationMessages;
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.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
@ -51,7 +50,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
private DeviceDAO deviceDAO;
private DeviceTypeDAO deviceTypeDAO;
private EnrollmentDAO enrollmentDAO;
private EnrolmentDAO enrolmentDAO;
private DeviceManagementPluginRepository pluginRepository;
private static Log log = LogFactory.getLog(DeviceManagementProviderServiceImpl.class);
@ -61,7 +60,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
this.pluginRepository = new DeviceManagementPluginRepository();
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
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
* the component is done getting initialized */
@ -101,16 +100,21 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
DeviceManagementDAOFactory.beginTransaction();
DeviceType type = deviceTypeDAO.getDeviceType(device.getType());
device.getEnrolmentInfo().setDateOfEnrolment(new Date().getTime());
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
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();
} catch (DeviceManagementDAOException e) {
try {
DeviceManagementDAOFactory.rollbackTransaction();
} 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 " +
"'" + device.getId() + "'", e);
@ -133,16 +137,17 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
boolean status = dms.modifyEnrollment(device);
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
DeviceManagementDAOFactory.beginTransaction();
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();
} catch (DeviceManagementDAOException e) {
try {
DeviceManagementDAOFactory.rollbackTransaction();
} 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 " +
"'" + device.getId() + "'", e);
@ -433,13 +438,13 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrollmentStatus status) throws DeviceManagementException {
EnrolmentInfo.Status status) throws DeviceManagementException {
try {
DeviceManagementDAOFactory.beginTransaction();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
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();
return success;
@ -532,7 +537,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
try {
DeviceManagementDAOFactory.getConnection();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userDevices = deviceDAO.getDeviceListOfUser(username, tenantId);
userDevices = deviceDAO.getDevicesOfUser(username, tenantId);
} catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving the list of devices that " +
"belong to the user '" + username + "'", e);
@ -568,7 +573,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
tenantId).getUserStoreManager().getUserListOfRole(role);
} catch (UserStoreException e) {
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;
@ -576,7 +581,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
userDevices = new ArrayList<Device>();
try {
DeviceManagementDAOFactory.getConnection();
userDevices = deviceDAO.getDeviceListOfUser(user, tenantId);
userDevices = deviceDAO.getDevicesOfUser(user, tenantId);
} catch (DeviceManagementDAOException e) {
log.error("Error occurred while obtaining the devices of user '" + user + "'", e);
} finally {
@ -648,7 +653,30 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
@Override
public List<Application> getApplicationListForDevice(DeviceIdentifier deviceIdentifier)
throws DeviceManagementException {
return null;
Device device = null;
try {
device = this.getDevice(deviceIdentifier);
return deviceDAO.getInstalledApplications(device.getId());
}catch (DeviceManagementDAOException deviceDaoEx){
String errorMsg = "Error occured while fetching the Application List of device : " + device.getId();
log.error(errorMsg, deviceDaoEx);
throw new DeviceManagementException(errorMsg, deviceDaoEx);
}
}
@Override
public void updateInstalledApplicationListOfDevice(DeviceIdentifier deviceIdentifier,
List<Application> applications)
throws DeviceManagementException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);
deviceDAO.addDeviceApplications(device.getId(), applications);
}catch (DeviceManagementDAOException deviceDaoEx){
String errorMsg = "Error occurred saving application list to the device";
log.error(errorMsg+":"+deviceIdentifier.toString());
throw new DeviceManagementException(errorMsg, deviceDaoEx);
}
}
@Override
@ -661,7 +689,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
device.getEnrolmentInfo().setStatus(status);
deviceDAO.updateDevice(deviceType.getId(), device, tenantId);
}catch (DeviceManagementDAOException deviceDaoEx){
String errorMsg = "Error occured update device enrolment status:"+device.getId();
String errorMsg = "Error occured update device enrolment status : "+device.getId();
log.error(errorMsg, deviceDaoEx);
throw new DeviceManagementException(errorMsg, deviceDaoEx);
}

@ -1,105 +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;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.jdbc.pool.PoolProperties;
import org.testng.annotations.BeforeClass;
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.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.dao.DeviceManagementDAOException;
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.Statement;
public class DeviceManagementBaseTest {
private DataSource dataSource;
private static final Log log = LogFactory.getLog(DeviceManagementBaseTest.class);
@BeforeClass(alwaysRun = true)
@Parameters("dbType")
public void setupDatabase(String dbTypeName) throws Exception {
DBTypes type = DBTypes.valueOf(dbTypeName);
TestDBConfiguration config = getTestDBConfiguration(type);
switch (type) {
case H2:
PoolProperties properties = new PoolProperties();
properties.setUrl(config.getConnectionUrl());
properties.setDriverClassName(config.getDriverClass());
properties.setUsername(config.getUserName());
properties.setPassword(config.getPwd());
dataSource = new org.apache.tomcat.jdbc.pool.DataSource(properties);
this.initSQLScript();
default:
}
}
private TestDBConfiguration getTestDBConfiguration(DBTypes dbType) throws DeviceManagementDAOException,
DeviceManagementException {
File dbConfig = new File("src/test/resources/testdbconfig.xml");
Document doc = DeviceManagerUtil.convertToDocument(dbConfig);
TestDBConfigurations dbConfigs;
JAXBContext testDBContext;
try {
testDBContext = JAXBContext.newInstance(TestDBConfigurations.class);
Unmarshaller unmarshaller = testDBContext.createUnmarshaller();
dbConfigs = (TestDBConfigurations) unmarshaller.unmarshal(doc);
for (TestDBConfiguration config : dbConfigs.getDbTypesList()) {
if (config.getDbType().equals(dbType.toString())) {
return config;
}
}
return null;
} 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'");
} catch(Exception e){
log.error(e);
throw e;
}finally {
TestUtils.cleanupResources(conn, stmt, null);
}
}
protected DataSource getDataSource() {
return dataSource;
}
}

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

@ -1,104 +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;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import java.util.ArrayList;
import java.util.List;
public class DeviceOperationManagementTests extends DeviceManagementBaseTest {
private OperationManager operationManager;
private static final Log log = LogFactory.getLog(DeviceOperationManagementTests.class);
@BeforeClass(alwaysRun = true)
public void init() throws Exception{
OperationManagementDAOFactory.init(this.getDataSource());
this.initOperationManager();
this.setupData();
}
private void setupData() throws Exception {
String deviceSql = "INSERT INTO DM_DEVICE(DESCRIPTION, NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, " +
"OWNERSHIP, STATUS, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, OWNER, TENANT_ID) " +
"VALUES ('Galaxy Tab', 'Samsung', 1425467382, 1425467382, 'BYOD', 'ACTIVE', 1, " +
"'4892813d-0b18-4a02-b7b1-61775257400e', 'admin@wso2.com', '-1234');";
String typeSql = "Insert into DM_DEVICE_TYPE (ID,NAME) VALUES (1, 'android');";
this.getDataSource().getConnection().createStatement().execute(typeSql);
this.getDataSource().getConnection().createStatement().execute(deviceSql);
}
private void initOperationManager() {
this.operationManager = new OperationManagerImpl();
DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(new DeviceManagementProviderServiceImpl());
}
// @Test
// public void testAddOperation() throws Exception {
// CommandOperation op = new CommandOperation();
// op.setEnabled(true);
// op.setType(Operation.Type.COMMAND);
// op.setCode("OPCODE1");
//
// List<DeviceIdentifier> deviceIds = new ArrayList<DeviceIdentifier>();
// DeviceIdentifier deviceId = new DeviceIdentifier();
// deviceId.setId("4892813d-0b18-4a02-b7b1-61775257400e");
// deviceId.setType("android");
// deviceIds.add(deviceId);
//
// try {
// boolean isAdded = operationManager.addOperation(op, deviceIds);
// Assert.assertTrue(isAdded);
// } catch (OperationManagementException e) {
// e.printStackTrace();
// throw new Exception(e);
// }
// }
public void testGetOperations() {
try {
//TODO:- operationManager.getOperations is not implemented
DeviceIdentifier deviceId = new DeviceIdentifier();
deviceId.setId("4892813d-0b18-4a02-b7b1-61775257400e");
deviceId.setType("android");
List<? extends Operation> operations = operationManager.getOperations(deviceId);
Assert.assertNotNull(operations);
boolean notEmpty = operations.size() > 0;
Assert.assertTrue(notEmpty);
} catch (OperationManagementException e) {
e.printStackTrace();
}
}
}

@ -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.ApplicationManagementException;
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 java.util.List;
public class TestDeviceManager implements DeviceManagementService {
public class TestDeviceManagementService implements DeviceManagementService {
public static final String DEVICE_TYPE_TEST = "Test";
@Override
public String getProviderType() {
return TestDeviceManager.DEVICE_TYPE_TEST;
return TestDeviceManagementService.DEVICE_TYPE_TEST;
}
@Override
@ -97,7 +95,8 @@ public class TestDeviceManager implements DeviceManagementService {
}
@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;
}

@ -1,29 +0,0 @@
/*
* Copyright (c) 2014, 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.common;
public enum DBTypes {
Oracle("Oracle"),H2("H2"),MySql("MySql");
String dbName ;
DBTypes(String dbStrName) {
dbName = dbStrName;
}
}

@ -0,0 +1,76 @@
/*
* Copyright (c) 2014, 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.common;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "DataSourceConfig")
public class DataSourceConfig {
private String url;
private String driverClassName;
private String user;
private String password;
@Override public String toString() {
return "DataSourceConfig[" +
" Url ='" + url + '\'' +
", DriverClassName ='" + driverClassName + '\'' +
", UserName ='" + user + '\'' +
", Password ='" + password + '\'' +
"]";
}
@XmlElement(name = "Url", nillable = false)
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@XmlElement(name = "DriverClassName", nillable = false)
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
@XmlElement(name = "User", nillable = false)
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
@XmlElement(name = "Password", nillable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

@ -1,90 +0,0 @@
/*
* Copyright (c) 2014, 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.common;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "DBType")
public class TestDBConfiguration {
private String connectionUrl;
private String driverClass;
private String userName;
private String pwd;
@Override public String toString() {
return "TestDBConfiguration{" +
"connectionUrl='" + connectionUrl + '\'' +
", driverClass='" + driverClass + '\'' +
", userName='" + userName + '\'' +
", pwd='" + pwd + '\'' +
", dbType='" + dbType + '\'' +
'}';
}
private String dbType;
@XmlElement(name = "connectionurl", nillable = false)
public String getConnectionUrl() {
return connectionUrl;
}
public void setConnectionUrl(String connectionUrl) {
this.connectionUrl = connectionUrl;
}
@XmlElement(name = "driverclass", nillable = false)
public String getDriverClass() {
return driverClass;
}
public void setDriverClass(String driverClass) {
this.driverClass = driverClass;
}
@XmlElement(name = "userName", nillable = false)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@XmlElement(name = "pwd", nillable = false)
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@XmlAttribute(name = "typeName")
public String getDbType() {
return dbType;
}
public void setDbType(String dbType) {
this.dbType = dbType;
}
}

@ -1,39 +0,0 @@
/*
* Copyright (c) 2014, 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.common;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "DeviceMgtTestDBConfigurations")
public class TestDBConfigurations {
private List<TestDBConfiguration> dbTypesList;
@XmlElement(name = "DBType")
public List<TestDBConfiguration> getDbTypesList() {
return dbTypesList;
}
public void setDbTypesList(List<TestDBConfiguration> dbTypesList) {
this.dbTypesList = dbTypesList;
}
}

@ -0,0 +1,89 @@
/*
* 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.BeforeClass;
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);
}
}
}
@BeforeClass
@Override
public void init() throws Exception {
this.initDatSource();
}
}

@ -0,0 +1,170 @@
/*
* 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.BeforeClass;
import org.testng.annotations.BeforeSuite;
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.DataSourceConfig;
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 abstract class BaseDeviceManagementDAOTest {
private DataSource dataSource;
private static final Log log = LogFactory.getLog(BaseDeviceManagementDAOTest.class);
@BeforeSuite
public void setupDataSource() throws Exception {
this.initDatSource();
this.initSQLScript();
}
public void initDatSource() throws Exception {
this.dataSource = this.getDataSource(this.readDataSourceConfig());
DeviceManagementDAOFactory.init(dataSource);
}
@BeforeClass
public abstract void init() throws Exception;
private DataSource getDataSource(DataSourceConfig config) {
PoolProperties properties = new PoolProperties();
properties.setUrl(config.getUrl());
properties.setDriverClassName(config.getDriverClassName());
properties.setUsername(config.getUser());
properties.setPassword(config.getPassword());
return new org.apache.tomcat.jdbc.pool.DataSource(properties);
}
private DataSourceConfig readDataSourceConfig() throws DeviceManagementException {
try {
File file = new File("src/test/resources/config/datasource/data-source-config.xml");
Document doc = DeviceManagerUtil.convertToDocument(file);
JAXBContext testDBContext = JAXBContext.newInstance(DataSourceConfig.class);
Unmarshaller unmarshaller = testDBContext.createUnmarshaller();
return (DataSourceConfig) unmarshaller.unmarshal(doc);
} catch (JAXBException e) {
throw new DeviceManagementException("Error occurred while reading data source configuration", 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,243 @@ 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.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
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.DeviceIdentifier;
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.Status;
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.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.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);
@AfterClass
public void deleteData() throws Exception {
Connection connection = dataSource.getConnection();
connection.createStatement().execute("DELETE FROM DM_DEVICE");
connection.createStatement().execute("DELETE FROM DM_DEVICE_TYPE");
@BeforeClass
@Override
public void init() throws Exception {
initDatSource();
}
@BeforeClass
@Parameters("dbType")
public void setUpDB(String dbTypeStr) throws Exception {
DBTypes dbType = DBTypes.valueOf(dbTypeStr);
TestDBConfiguration dbConfig = getTestDBConfiguration(dbType);
switch (dbType) {
case H2:
PoolProperties properties = new PoolProperties();
properties.setUrl(dbConfig.getConnectionUrl());
properties.setDriverClassName(dbConfig.getDriverClass());
properties.setUsername(dbConfig.getUserName());
properties.setPassword(dbConfig.getPwd());
dataSource = new org.apache.tomcat.jdbc.pool.DataSource(properties);
this.initSQLScript();
DeviceManagementDAOFactory.init(dataSource);
default:
@Test
public void testAddDeviceTypeTest() {
DeviceType deviceType = this.loadDummyDeviceType();
try {
DeviceManagementDAOFactory.openConnection();
deviceTypeDAO.addDeviceType(deviceType);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while adding device type '" + deviceType.getName() + "'";
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 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,
DeviceManagementException {
File deviceMgtConfig = new File("src/test/resources/testdbconfig.xml");
Document doc;
TestDBConfigurations dbConfigs;
@Test(dependsOnMethods = {"testAddDeviceTypeTest"})
public void testAddDeviceTest() {
DeviceType deviceType = this.loadDummyDeviceType();
deviceType.setId(1);
doc = DeviceManagerUtil.convertToDocument(deviceMgtConfig);
JAXBContext testDBContext;
int tenantId = -1234;
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 {
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);
targetId = this.getDeviceId();
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving device id";
log.error(msg, e);
Assert.fail(msg, e);
}
for (TestDBConfiguration config : dbConfigs.getDbTypesList()) {
if (config.getDbType().equals(dbType.toString())) {
return config;
Assert.assertNotNull(targetId, "Device Id persisted in device management metadata repository upon '" +
device.getType() + "' carrying the identifier '" + device.getDeviceIdentifier() + "', is null");
}
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;
Statement stmt = null;
PreparedStatement stmt = null;
ResultSet rs = null;
int id = -1;
try {
conn = this.getDataSource().getConnection();
stmt = conn.createStatement();
stmt.executeUpdate("RUNSCRIPT FROM './src/test/resources/sql/h2.sql'");
Assert.assertNotNull(getDataSource(), "Data Source is not initialized properly");
conn = getDataSource().getConnection();
String sql = "SELECT ID FROM DM_DEVICE WHERE DEVICE_IDENTIFICATION = ? AND TENANT_ID = ?";
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 {
TestUtils.cleanupResources(conn, stmt, null);
TestUtils.cleanupResources(conn, stmt, rs);
}
}
@Test
public void addDeviceTypeTest() throws DeviceManagementDAOException, DeviceManagementException {
DeviceTypeDAO deviceTypeMgtDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
DeviceType deviceType = new DeviceType();
deviceType.setName("IOS");
deviceTypeMgtDAO.addDeviceType(deviceType);
private int getDeviceTypeId() throws DeviceManagementDAOException {
int id = -1;
Connection conn = 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 {
conn = this.getDataSource().getConnection();
Assert.assertNotNull(getDataSource(), "Data Source is not initialized properly");
conn = getDataSource().getConnection();
stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceType.getName());
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
id = rs.getInt("ID");
}
return id;
} 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 {
TestUtils.cleanupResources(conn, stmt, null);
}
Assert.assertNotNull(id, "Device Type Id is null");
deviceType.setId(id);
}
@Test(dependsOnMethods = {"addDeviceTypeTest"})
public void addDeviceTest() throws DeviceManagementDAOException, DeviceManagementException {
DeviceDAO deviceMgtDAO = DeviceManagementDAOFactory.getDeviceDAO();
@Test(dependsOnMethods = "testAddDeviceTest")
public void testSetEnrolmentStatus() {
System.out.println("ENROLLLLLLLLLLLLLL");
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();
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setOwner("admin");
enrolmentInfo.setOwnership(OwnerShip.BYOD);
enrolmentInfo.setStatus(Status.CREATED);
device.setEnrolmentInfo(enrolmentInfo);
device.setDescription("test description");
device.getEnrolmentInfo().setStatus(Status.ACTIVE);
device.setDeviceIdentifier("111");
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");
device.setDescription("Test Description");
device.setDeviceIdentifier("1234");
device.setType(this.loadDummyDeviceType().getName());
return device;
}
private DataSource getDataSource() {
return dataSource;
private DeviceType loadDummyDeviceType() {
return new DeviceType("iOS");
}
}

@ -0,0 +1,91 @@
/*
* 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.BeforeClass;
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);
}
}
}
@BeforeClass
@Override
public void init() throws Exception {
this.initDatSource();
}
}

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

@ -8,13 +8,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE (
ID INTEGER auto_increment NOT NULL,
DESCRIPTION TEXT 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_IDENTIFICATION VARCHAR(300) NULL DEFAULT NULL,
OWNER VARCHAR(45) NULL DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (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
);
CREATE TABLE IF NOT EXISTS DM_ENROLLMENT (
CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
OWNER VARCHAR(50) NOT NULL,
OWNERSHIP VARCHAR(45) NULL DEFAULT NULL,
STATUS VARCHAR(50) NULL,
DATE_OF_ENROLLMENT BIGINT NULL DEFAULT NULL,
DATE_OF_LAST_UPDATE BIGINT NULL DEFAULT NULL,
DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL,
TENANT_ID INT NOT NULL,
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
);
);
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,16 @@
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="EMM-core-initializer">
<suite name="DeviceManagementCore">
<parameter name="useDefaultListeners" value="false"/>
<test name="DAO Unit Tests" preserve-order="true">
<parameter name="dbType" value="H2"/>
<classes>
<class name="org.wso2.carbon.device.mgt.core.dao.BaseDeviceManagementDAOTest"/>
<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.DeviceManagementConfigTests"/>
<class name="org.wso2.carbon.device.mgt.core.DeviceOperationManagementTests"/>
<class name="org.wso2.carbon.device.mgt.core.dao.ApplicationPersistenceDAOTests"/>
</classes>
</test>
</suite>

@ -112,7 +112,7 @@ public class PolicyManagementDAOFactory {
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while retrieving datasource connection", e);
throw new PolicyManagerDAOException("Error occurred while retrieving config.datasource connection", e);
}
}

@ -466,7 +466,7 @@ public class FeatureDAOImpl implements FeatureDAO {
return PolicyManagementDAOFactory.getConnection();
} catch (PolicyManagerDAOException e) {
throw new FeatureManagerDAOException("Error occurred while obtaining a connection from the policy " +
"management metadata repository datasource", e);
"management metadata repository config.datasource", e);
}
}

@ -220,7 +220,7 @@ public class MonitoringDAOImpl implements MonitoringDAO {
return PolicyManagementDAOFactory.getConnection();
} catch (PolicyManagerDAOException e) {
throw new MonitoringDAOException("Error occurred while obtaining a connection from the policy " +
"management metadata repository datasource", e);
"management metadata repository config.datasource", e);
}
}

@ -279,7 +279,7 @@ public class ProfileDAOImpl implements ProfileDAO {
return PolicyManagementDAOFactory.getConnection();
} catch (PolicyManagerDAOException e) {
throw new ProfileManagerDAOException("Error occurred while obtaining a connection from the policy " +
"management metadata repository datasource", e);
"management metadata repository config.datasource", e);
}
}

@ -0,0 +1,98 @@
/*
* 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.policy.mgt.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.jdbc.pool.PoolProperties;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
import org.w3c.dom.Document;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.common.DataSourceConfig;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
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.Statement;
public abstract class BasePolicyManagementDAOTest {
private DataSource dataSource;
private static final Log log = LogFactory.getLog(BasePolicyManagementDAOTest.class);
@BeforeSuite
public void setupDataSource() throws Exception {
this.initDatSource();
this.initSQLScript();
}
public void initDatSource() throws Exception {
this.dataSource = this.getDataSource(this.readDataSourceConfig());
DeviceManagementDAOFactory.init(dataSource);
PolicyManagementDAOFactory.init(dataSource);
}
@BeforeClass
public abstract void init() throws Exception;
private DataSource getDataSource(DataSourceConfig config) {
PoolProperties properties = new PoolProperties();
properties.setUrl(config.getUrl());
properties.setDriverClassName(config.getDriverClassName());
properties.setUsername(config.getUser());
properties.setPassword(config.getPassword());
return new org.apache.tomcat.jdbc.pool.DataSource(properties);
}
private DataSourceConfig readDataSourceConfig() throws PolicyManagementException {
try {
File file = new File("src/test/resources/config/datasource/data-source-config.xml");
Document doc = PolicyManagerUtil.convertToDocument(file);
JAXBContext testDBContext = JAXBContext.newInstance(DataSourceConfig.class);
Unmarshaller unmarshaller = testDBContext.createUnmarshaller();
return (DataSourceConfig) unmarshaller.unmarshal(doc);
} catch (JAXBException e) {
throw new PolicyManagementException("Error occurred while reading data source configuration", 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/CreateH2TestDB.sql'");
} finally {
TestUtils.cleanupResources(conn, stmt, null);
}
}
public DataSource getDataSource() {
return dataSource;
}
}

@ -15,30 +15,21 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.policy.mgt.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.jdbc.pool.PoolProperties;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
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.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.core.common.DBTypes;
import org.wso2.carbon.policy.mgt.core.common.TestDBConfiguration;
import org.wso2.carbon.policy.mgt.core.common.TestDBConfigurations;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
import org.wso2.carbon.policy.mgt.core.impl.PolicyAdministratorPointImpl;
import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
@ -48,21 +39,12 @@ import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl;
import org.wso2.carbon.policy.mgt.core.mgt.impl.ProfileManagerImpl;
import org.wso2.carbon.policy.mgt.core.util.*;
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.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class PolicyDAOTestCase {
public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
private static DataSource dataSource;
private List<Feature> featureList;
private List<ProfileFeature> profileFeatureList;
private Profile profile;
@ -71,102 +53,13 @@ public class PolicyDAOTestCase {
private static final Log log = LogFactory.getLog(PolicyDAOTestCase.class);
@BeforeClass
@Parameters("dbType")
public void setUpDB(String dbTypeStr) throws Exception {
DBTypes dbType = DBTypes.valueOf(dbTypeStr);
TestDBConfiguration dbConfig = getTestDBConfiguration(dbType);
PoolProperties properties = new PoolProperties();
System.setProperty("GetTenantIDForTest","Super");
log.info("Database Type : " + dbTypeStr);
switch (dbType) {
case MySql:
log.info("Mysql Called..................................................." + dbTypeStr);
properties.setUrl(dbConfig.getConnectionUrl());
properties.setDriverClassName(dbConfig.getDriverClass());
properties.setUsername(dbConfig.getUserName());
properties.setPassword(dbConfig.getPwd());
dataSource = new org.apache.tomcat.jdbc.pool.DataSource(properties);
PolicyManagementDAOFactory.init(dataSource);
DeviceManagementDAOFactory.init(dataSource);
break;
case H2:
properties.setUrl(dbConfig.getConnectionUrl());
properties.setDriverClassName(dbConfig.getDriverClass());
properties.setUsername(dbConfig.getUserName());
properties.setPassword(dbConfig.getPwd());
dataSource = new org.apache.tomcat.jdbc.pool.DataSource(properties);
this.initH2SQLScript();
PolicyManagementDAOFactory.init(dataSource);
DeviceManagementDAOFactory.init(dataSource);
break;
default:
}
}
private TestDBConfiguration getTestDBConfiguration(DBTypes dbType) throws PolicyManagerDAOException,
PolicyManagementException {
File deviceMgtConfig = new File("src/test/resources/testdbconfig.xml");
Document doc;
TestDBConfigurations dbConfigs;
doc = PolicyManagerUtil.convertToDocument(deviceMgtConfig);
JAXBContext testDBContext;
try {
testDBContext = JAXBContext.newInstance(TestDBConfigurations.class);
Unmarshaller unmarshaller = testDBContext.createUnmarshaller();
dbConfigs = (TestDBConfigurations) unmarshaller.unmarshal(doc);
} catch (JAXBException e) {
throw new PolicyManagerDAOException("Error parsing test db configurations", e);
}
for (TestDBConfiguration config : dbConfigs.getDbTypesList()) {
if (config.getDbType().equals(dbType.toString())) {
return config;
}
}
return null;
}
private void initH2SQLScript() throws Exception {
Connection conn = null;
Statement stmt = null;
try {
conn = this.getDataSource().getConnection();
stmt = conn.createStatement();
stmt.executeUpdate("RUNSCRIPT FROM './src/test/resources/sql/CreateH2TestDB.sql'");
} finally {
TestUtils.cleanupResources(conn, stmt, null);
}
}
private void initMySQlSQLScript() throws Exception {
Connection conn = null;
Statement stmt = null;
try {
conn = this.getDataSource().getConnection();
stmt = conn.createStatement();
stmt.executeUpdate("RUNSCRIPT FROM './src/test/resources/sql/CreateMySqlTestDB.sql'");
} finally {
TestUtils.cleanupResources(conn, stmt, null);
}
}
private DataSource getDataSource() {
return dataSource;
@Override
public void init() throws Exception {
initDatSource();
}
@Test
public void addDeviceType() throws DeviceManagementDAOException {
DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
deviceTypeDAO.addDeviceType(DeviceTypeCreator.getDeviceType());
}

@ -1,29 +0,0 @@
/*
* Copyright (c) 2014, 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.policy.mgt.core.common;
public enum DBTypes {
Oracle("Oracle"),H2("H2"),MySql("MySql");
String dbName ;
DBTypes(String dbStrName) {
dbName = dbStrName;
}
}

@ -0,0 +1,76 @@
/*
* Copyright (c) 2014, 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.policy.mgt.core.common;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "DataSourceConfig")
public class DataSourceConfig {
private String url;
private String driverClassName;
private String user;
private String password;
@Override public String toString() {
return "DataSourceConfig[" +
" Url ='" + url + '\'' +
", DriverClassName ='" + driverClassName + '\'' +
", UserName ='" + user + '\'' +
", Password ='" + password + '\'' +
"]";
}
@XmlElement(name = "Url", nillable = false)
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@XmlElement(name = "DriverClassName", nillable = false)
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
@XmlElement(name = "User", nillable = false)
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
@XmlElement(name = "Password", nillable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

@ -1,90 +0,0 @@
/*
* Copyright (c) 2014, 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.policy.mgt.core.common;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "DBType")
public class TestDBConfiguration {
private String connectionUrl;
private String driverClass;
private String userName;
private String pwd;
@Override public String toString() {
return "TestDBConfiguration{" +
"connectionUrl='" + connectionUrl + '\'' +
", driverClass='" + driverClass + '\'' +
", userName='" + userName + '\'' +
", pwd='" + pwd + '\'' +
", dbType='" + dbType + '\'' +
'}';
}
private String dbType;
@XmlElement(name = "connectionurl", nillable = false)
public String getConnectionUrl() {
return connectionUrl;
}
public void setConnectionUrl(String connectionUrl) {
this.connectionUrl = connectionUrl;
}
@XmlElement(name = "driverclass", nillable = false)
public String getDriverClass() {
return driverClass;
}
public void setDriverClass(String driverClass) {
this.driverClass = driverClass;
}
@XmlElement(name = "userName", nillable = false)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@XmlElement(name = "pwd", nillable = false)
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@XmlAttribute(name = "typeName")
public String getDbType() {
return dbType;
}
public void setDbType(String dbType) {
this.dbType = dbType;
}
}

@ -1,39 +0,0 @@
/*
* Copyright (c) 2014, 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.policy.mgt.core.common;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "DeviceMgtTestDBConfigurations")
public class TestDBConfigurations {
private List<TestDBConfiguration> dbTypesList;
@XmlElement(name = "DBType")
public List<TestDBConfiguration> getDbTypesList() {
return dbTypesList;
}
public void setDbTypesList(List<TestDBConfiguration> dbTypesList) {
this.dbTypesList = dbTypesList;
}
}

@ -17,17 +17,9 @@
~ under the License.
-->
<DeviceMgtTestDBConfigurations>
<DBType typeName="MySql">
<connectionurl>jdbc:mysql://localhost:3306/WSO2CDM</connectionurl>
<driverclass>com.mysql.jdbc.Driver</driverclass>
<userName>root</userName>
<pwd></pwd>
</DBType>
<DBType typeName="H2">
<connectionurl>jdbc:h2:mem:WSO2_TEST_DB;DB_CLOSE_ON_EXIT=FALSE;LOCK_TIMEOUT=60000</connectionurl>
<driverclass>org.h2.Driver</driverclass>
<userName>wso2carbon</userName>
<pwd>wso2carbon</pwd>
</DBType>
</DeviceMgtTestDBConfigurations>
<DataSourceConfig>
<Url>jdbc:h2:mem:cdm-test-db;DB_CLOSE_DELAY=-1</Url>
<DriverClassName>org.h2.Driver</DriverClassName>
<User>wso2carbon</User>
<Password>wso2carbon</Password>
</DataSourceConfig>

@ -25,7 +25,7 @@
<test name="DAO Unit Tests" preserve-order="true">
<parameter name="dbType" value="H2"/>
<classes>
<class name="org.wso2.carbon.policy.mgt.core.PolicyDAOTestCase"/>
<!--<class name="org.wso2.carbon.policy.mgt.core.PolicyDAOTestCase"/>-->
</classes>
</test>
</suite>
Loading…
Cancel
Save