Device Organization CRUD operations

pull/238/head
Isuri Mendis 1 year ago
parent eced345be8
commit 1e93dcce2b

@ -18,8 +18,10 @@
package io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DeviceOrganizationMgtDAOException;
import java.sql.Date;
import java.util.List;
public interface DeviceOrganizationDAO {
@ -27,4 +29,11 @@ public interface DeviceOrganizationDAO {
List<Device> getChildDevices(int parentId) throws DeviceOrganizationMgtDAOException;
List<Device> getParentDevices(Integer deviceID) throws DeviceOrganizationMgtDAOException;
boolean addDeviceOrganization(DeviceOrganization deviceOrganization) throws DeviceOrganizationMgtDAOException;
boolean updateDeviceOrganization(int deviceID, int parentDeviceID, Date timestamp, String status, int organizationId)
throws DeviceOrganizationMgtDAOException;
DeviceOrganization getDeviceOrganizationByID(int organizationId) throws DeviceOrganizationMgtDAOException;
}

@ -20,19 +20,17 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.DeviceOrganizationDAO;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.util.ConnectionManagerUtil;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.util.DeviceOrganizationDaoUtil;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DBConnectionException;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DeviceOrganizationMgtDAOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import static io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.util.DeviceOrganizationDaoUtil.generateParameterPlaceholders;
import static io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.util.DeviceOrganizationDaoUtil.getDeviceFromResultSet;
public class DeviceOrganizationDAOImpl implements DeviceOrganizationDAO {
@ -44,11 +42,11 @@ public class DeviceOrganizationDAOImpl implements DeviceOrganizationDAO {
List<Device> childDevices = null;
try {
Connection conn = ConnectionManagerUtil.getDBConnection();
String sql = "SELECT d.ID, d.DEVICE_IDENTIFICATION, d.NAME, t.NAME AS DEVICE_TYPE " +
String sql = "SELECT d.ID, d.DESCRIPTION, d.DEVICE_IDENTIFICATION, d.NAME, t.NAME AS DEVICE_TYPE_NAME " +
"FROM DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE d.PARENT_DEVICE_ID = ? AND d.DEVICE_TYPE_ID = t.ID";
"WHERE d.ID = ? AND d.DEVICE_TYPE_ID = t.ID";
try (PreparedStatement stmt = conn.prepareStatement(sql)){
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, parentId);
try (ResultSet rs = stmt.executeQuery()) {
childDevices = new ArrayList<>();
@ -77,12 +75,12 @@ public class DeviceOrganizationDAOImpl implements DeviceOrganizationDAO {
List<Device> parentDevices = null;
try {
Connection conn = ConnectionManagerUtil.getDBConnection();
String sql = "SELECT d.ID, d.DEVICE_IDENTIFICATION, d.NAME, t.NAME AS DEVICE_TYPE " +
String sql = "SELECT d.ID, d.DESCRIPTION,d.DEVICE_IDENTIFICATION, d.NAME, t.NAME AS DEVICE_TYPE_NAME " +
"FROM DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE d.ID IN (SELECT PARENT_DEVICE_ID FROM DM_DEVICE WHERE ID = ?) " +
"WHERE d.ID IN (SELECT ID FROM DM_DEVICE WHERE ID = ?) " +
"AND d.DEVICE_TYPE_ID = t.ID";
try (PreparedStatement stmt = conn.prepareStatement(sql)){
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, deviceID);
try (ResultSet rs = stmt.executeQuery()) {
parentDevices = new ArrayList<>();
@ -106,18 +104,92 @@ public class DeviceOrganizationDAOImpl implements DeviceOrganizationDAO {
}
}
@Override
public boolean addDeviceOrganization(DeviceOrganization deviceOrganization) throws DeviceOrganizationMgtDAOException {
try {
String sql = "INSERT INTO DM_DEVICE_ORGANIZATION (DEVICE_ID, PARENT_DEVICE_ID, LAST_UPDATED_TIMESTAMP, STATUS)" +
" VALUES (?, ?, ?, ?)";
Connection conn = ConnectionManagerUtil.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, deviceOrganization.getDeviceId());
stmt.setInt(2, deviceOrganization.getParentDeviceId());
stmt.setDate(3, deviceOrganization.getUpdateTime());
stmt.setString(4, deviceOrganization.getStatus().toString());
return stmt.executeUpdate() > 0;
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining DB connection to insert device organization for " +
deviceOrganization.getDeviceId();
log.error(msg);
throw new DeviceOrganizationMgtDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while processing SQL to insert device organization for " +
deviceOrganization.getDeviceId();
log.error(msg);
throw new DeviceOrganizationMgtDAOException(msg, e);
}
}
@Override
public boolean updateDeviceOrganization(int deviceID, int parentDeviceID, Date timestamp, String status, int organizationId)
throws DeviceOrganizationMgtDAOException {
try {
String sql = "UPDATE DM_DEVICE_ORGANIZATION SET DEVICE_ID = ? , PARENT_DEVICE_ID = ? , " +
"LAST_UPDATED_TIMESTAMP = ? , STATUS = ? WHERE ID = ? ";
Connection conn = ConnectionManagerUtil.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, deviceID);
stmt.setInt(2, parentDeviceID);
stmt.setDate(3, timestamp);
stmt.setString(4, status);
stmt.setInt(5, organizationId);
return stmt.executeUpdate() > 0;
}
// Simulated database storage
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining DB connection to update device organization for " +
organizationId;
log.error(msg);
throw new DeviceOrganizationMgtDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while processing SQL to update device organization for " +
organizationId;
log.error(msg);
throw new DeviceOrganizationMgtDAOException(msg, e);
}
}
@Override
public DeviceOrganization getDeviceOrganizationByID(int organizationId) throws DeviceOrganizationMgtDAOException {
try {
String sql = "SELECT do.ID,do.DEVICE_ID, do.PARENT_DEVICE_ID, do.LAST_UPDATED_TIMESTAMP, do.STATUS " +
"FROM DM_DEVICE_ORGANIZATION do WHERE do.ID = ? ";
Connection conn = ConnectionManagerUtil.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, organizationId);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return DeviceOrganizationDaoUtil.loadDeviceOrganization(rs);
}
return null;
}
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining DB connection to get device organization details for " +
organizationId;
log.error(msg);
throw new DeviceOrganizationMgtDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while processing SQL to get device organization details for " +
organizationId;
log.error(msg);
throw new DeviceOrganizationMgtDAOException(msg, e);
}
}
// public void addDevice(Device device) {
// devices.put(device.getId(), device);
// }
//
// public void addChildDevice(int parentId, int childId) {
// deviceHierarchy.computeIfAbsent(parentId, k -> new ArrayList<>()).add(childId);
// }
//
// public Device getDeviceById(int deviceId) {
// return devices.get(deviceId);
// }
}

@ -2,8 +2,10 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.ResultSet;
import java.sql.SQLException;
@ -14,16 +16,15 @@ public class DeviceOrganizationDaoUtil {
private static final Log log = LogFactory.getLog(DeviceOrganizationDaoUtil.class);
// Helper method to generate parameter placeholders for the SQL query
public static String generateParameterPlaceholders(int count) {
StringBuilder placeholders = new StringBuilder();
for (int i = 0; i < count; i++) {
placeholders.append("?");
if (i < count - 1) {
placeholders.append(", ");
}
}
return placeholders.toString();
public static DeviceOrganization loadDeviceOrganization(ResultSet rs) throws SQLException {
DeviceOrganization deviceOrganization = new DeviceOrganization() {
};
deviceOrganization.setOrganizationId(rs.getInt("ID"));
deviceOrganization.setDeviceId(rs.getInt("DEVICE_ID"));
deviceOrganization.setParentDeviceId(rs.getInt("PARENT_DEVICE_ID"));
deviceOrganization.setUpdateTime(rs.getDate("LAST_UPDATED_TIMESTAMP"));
deviceOrganization.setStatus(DeviceOrganization.DeviceOrganizationStatus.valueOf(rs.getString("STATUS")));
return deviceOrganization;
}
// Helper method to create a Device object from a ResultSet

@ -18,7 +18,8 @@
package io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto;
import java.util.Date;
import java.sql.Date;
public abstract class DeviceOrganization {
@ -26,6 +27,7 @@ public abstract class DeviceOrganization {
private int deviceId;
private int parentDeviceId;
private Date updateTime;
private DeviceOrganizationStatus status;
public int getOrganizationId() {
return organizationId;
@ -58,4 +60,16 @@ public abstract class DeviceOrganization {
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public DeviceOrganizationStatus getStatus() {
return status;
}
public void setStatus(DeviceOrganizationStatus status) {
this.status = status;
}
public enum DeviceOrganizationStatus {
ACT, INA
}
}

@ -22,6 +22,8 @@ import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.D
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.DeviceOrganizationDAOFactory;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.util.ConnectionManagerUtil;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceNode;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.BadRequestException;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DBConnectionException;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DeviceOrganizationMgtDAOException;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DeviceOrganizationMgtPluginException;
@ -29,6 +31,7 @@ import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.spi.D
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
@ -43,7 +46,8 @@ public class DeviceOrganizationServiceImpl implements DeviceOrganizationService
}
@Override
public List<DeviceNode> getChildrenOf(DeviceNode node, int maxDepth, boolean includeDevice) throws DeviceOrganizationMgtPluginException {
public List<DeviceNode> getChildrenOf(DeviceNode node, int maxDepth, boolean includeDevice)
throws DeviceOrganizationMgtPluginException {
try {
// Open a database connection
ConnectionManagerUtil.openDBConnection();
@ -69,7 +73,8 @@ public class DeviceOrganizationServiceImpl implements DeviceOrganizationService
}
@Override
public List<DeviceNode> getParentsOf(DeviceNode node, int maxDepth, boolean includeDevice) throws DeviceOrganizationMgtPluginException {
public List<DeviceNode> getParentsOf(DeviceNode node, int maxDepth, boolean includeDevice)
throws DeviceOrganizationMgtPluginException {
try {
// Open a database connection
ConnectionManagerUtil.openDBConnection();
@ -135,4 +140,106 @@ public class DeviceOrganizationServiceImpl implements DeviceOrganizationService
}
}
}
@Override
public boolean addDeviceOrganization(DeviceOrganization deviceOrganization)
throws DeviceOrganizationMgtPluginException {
String msg = "";
try {
ConnectionManagerUtil.beginDBTransaction();
boolean result = deviceOrganizationDao.addDeviceOrganization(deviceOrganization);
if (result) {
msg = "Device organization added successfully,for " + deviceOrganization.getDeviceId();
if (log.isDebugEnabled()) {
log.debug(msg);
}
} else {
ConnectionManagerUtil.rollbackDBTransaction();
msg = "Device organization failed to add,for " + deviceOrganization.getDeviceId();
throw new DeviceOrganizationMgtPluginException(msg);
}
ConnectionManagerUtil.commitDBTransaction();
return true;
} catch (DBConnectionException e) {
msg = "Error occurred while obtaining the database connection to add device organization for " +
deviceOrganization.getDeviceId();
log.error(msg);
throw new DeviceOrganizationMgtPluginException(msg, e);
} catch (DeviceOrganizationMgtDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
msg = "Error occurred in the database level while adding device organization for " +
deviceOrganization.getDeviceId();
log.error(msg);
throw new DeviceOrganizationMgtPluginException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public boolean updateDeviceOrganization(int deviceID, int parentDeviceID, Date timestamp, String status,
int organizationId) throws DeviceOrganizationMgtPluginException {
String msg = "";
DeviceOrganization deviceOrganization = getDeviceOrganizationByID(organizationId);
if (deviceOrganization == null) {
String errorMsg = "Cannot find device organization for organization ID" + organizationId;
log.error(errorMsg);
throw new NullPointerException(errorMsg);
// throw new BadRequestException(errorMsg);
}
try {
ConnectionManagerUtil.beginDBTransaction();
boolean result = deviceOrganizationDao.updateDeviceOrganization(deviceID, parentDeviceID, timestamp, status,
organizationId);
if (result) {
msg = "Device organization updated successfully,for " + deviceID;
if (log.isDebugEnabled()) {
log.debug(msg);
}
} else {
ConnectionManagerUtil.rollbackDBTransaction();
msg = "Device organization failed to update,for " + deviceID;
throw new DeviceOrganizationMgtPluginException(msg);
}
ConnectionManagerUtil.commitDBTransaction();
return true;
} catch (DBConnectionException e) {
msg = "Error occurred while obtaining the database connection to update device organization for " + deviceID;
log.error(msg);
throw new DeviceOrganizationMgtPluginException(msg, e);
} catch (DeviceOrganizationMgtDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
msg = "Error occurred in the database level while updating device organization for " + deviceID;
log.error(msg);
throw new DeviceOrganizationMgtPluginException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public DeviceOrganization getDeviceOrganizationByID(int organizationId)
throws DeviceOrganizationMgtPluginException {
try {
// Open a database connection
ConnectionManagerUtil.openDBConnection();
DeviceOrganization deviceOrganization = deviceOrganizationDao.getDeviceOrganizationByID(organizationId);
return deviceOrganization;
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the database connection to retrieve child devices";
log.error(msg);
throw new DeviceOrganizationMgtPluginException(msg, e);
} catch (DeviceOrganizationMgtDAOException e) {
String msg = "Error occurred in the database level while retrieving child devices";
log.error(msg);
throw new DeviceOrganizationMgtPluginException(msg, e);
} finally {
// Close the database connection
ConnectionManagerUtil.closeDBConnection();
}
}
}

@ -21,7 +21,6 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.organization.inte
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig;
import io.entgra.device.mgt.core.device.mgt.core.config.datasource.DataSourceConfig;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.DeviceOrganizationDAOFactory;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.impl.DeviceOrganizationServiceImpl;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.spi.DeviceOrganizationService;
@ -83,7 +82,7 @@ public class DeviceOrganizationMgtServiceComponent {
protected void deactivate(ComponentContext componentContext) {
if (log.isDebugEnabled()) {
log.debug("De-activating Device SubType Management Service Component");
log.debug("De-activating Device Organization Management Service Component");
}
}

@ -18,8 +18,10 @@
package io.entgra.device.mgt.core.device.mgt.extensions.device.organization.spi;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceNode;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DeviceOrganizationMgtPluginException;
import java.sql.Date;
import java.util.List;
public interface DeviceOrganizationService {
@ -27,4 +29,12 @@ public interface DeviceOrganizationService {
List<DeviceNode> getChildrenOf(DeviceNode node, int maxDepth, boolean includeDevice) throws DeviceOrganizationMgtPluginException;
List<DeviceNode> getParentsOf(DeviceNode node, int maxDepth, boolean includeDevice) throws DeviceOrganizationMgtPluginException;
boolean addDeviceOrganization(DeviceOrganization deviceOrganization) throws DeviceOrganizationMgtPluginException;
boolean updateDeviceOrganization(int deviceID, int parentDeviceID, Date timestamp, String status,
int organizationId) throws DeviceOrganizationMgtPluginException;
DeviceOrganization getDeviceOrganizationByID(int organizationId)
throws DeviceOrganizationMgtPluginException;
}

@ -0,0 +1,52 @@
package io.entgra.device.mgt.core.device.mgt.extensions.device.organization;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.DeviceOrganizationDAO;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.DeviceOrganizationDAOFactory;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.util.ConnectionManagerUtil;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DBConnectionException;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DeviceOrganizationMgtDAOException;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.mock.BaseDeviceOrganizationTest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class DAONegativeTest extends BaseDeviceOrganizationTest {
private static final Log log = LogFactory.getLog(DAONegativeTest.class);
private DeviceOrganizationDAO deviceOrganizationDAO;
@BeforeClass
public void init() {
deviceOrganizationDAO = DeviceOrganizationDAOFactory.getDeviceOrganizationDAO();
log.info("DAO test initialized");
}
@Test(description = "This method tests the add device organization method under negative circumstances with null data",
expectedExceptions = {NullPointerException.class}
)
public void testAddDeviceOrganization() throws DeviceOrganizationMgtDAOException {
DeviceOrganization deviceOrganization = new DeviceOrganization() {
};
try {
ConnectionManagerUtil.beginDBTransaction();
deviceOrganizationDAO.addDeviceOrganization(deviceOrganization);
ConnectionManagerUtil.commitDBTransaction();
} catch (DeviceOrganizationMgtDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred while processing SQL to insert device organization";
log.error(msg);
throw new DeviceOrganizationMgtDAOException(msg, e);
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining DB connection to insert device organization";
log.error(msg);
throw new DeviceOrganizationMgtDAOException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
}

@ -0,0 +1,96 @@
package io.entgra.device.mgt.core.device.mgt.extensions.device.organization;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.DeviceOrganizationDAO;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.DeviceOrganizationDAOFactory;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.util.ConnectionManagerUtil;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DBConnectionException;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DeviceOrganizationMgtDAOException;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.mock.BaseDeviceOrganizationTest;
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 java.sql.Date;
import java.util.List;
public class DAOTest extends BaseDeviceOrganizationTest {
private static final Log log = LogFactory.getLog(DAOTest.class);
private DeviceOrganizationDAO deviceOrganizationDAO;
@BeforeClass
public void init() {
deviceOrganizationDAO = DeviceOrganizationDAOFactory.getDeviceOrganizationDAO();
log.info("DAO test initialized");
}
@Test(dependsOnMethods = "testAddDeviceOrganization")
public void testGetChildrenOf() throws DBConnectionException, DeviceOrganizationMgtDAOException {
ConnectionManagerUtil.openDBConnection();
List<Device> childrenList = deviceOrganizationDAO.getChildDevices(3);
ConnectionManagerUtil.closeDBConnection();
Assert.assertNotNull(childrenList, "Cannot be null");
}
@Test(dependsOnMethods = "testAddDeviceOrganization")
public void testGetParentsOf() throws DBConnectionException, DeviceOrganizationMgtDAOException {
ConnectionManagerUtil.openDBConnection();
List<Device> parentList = deviceOrganizationDAO.getParentDevices(4);
ConnectionManagerUtil.closeDBConnection();
Assert.assertNotNull(parentList, "Cannot be null");
}
@Test
public void testAddDeviceOrganization() throws DBConnectionException, DeviceOrganizationMgtDAOException {
DeviceOrganization.DeviceOrganizationStatus status = DeviceOrganization.DeviceOrganizationStatus.ACT;
DeviceOrganization deviceOrganization = new DeviceOrganization() {
};
deviceOrganization.setDeviceId(4);
deviceOrganization.setParentDeviceId(3);
deviceOrganization.setUpdateTime(new Date(System.currentTimeMillis()));
deviceOrganization.setStatus(status);
ConnectionManagerUtil.beginDBTransaction();
boolean result = deviceOrganizationDAO.addDeviceOrganization(deviceOrganization);
ConnectionManagerUtil.commitDBTransaction();
ConnectionManagerUtil.closeDBConnection();
Assert.assertNotNull(result, "Cannot be null");
}
@Test(dependsOnMethods = "testAddDeviceOrganization")
public void testUpdateDeviceOrganization() throws DBConnectionException, DeviceOrganizationMgtDAOException {
ConnectionManagerUtil.beginDBTransaction();
boolean result = deviceOrganizationDAO.updateDeviceOrganization(4, 2, new Date(System.currentTimeMillis()), "ACTIVE", 1);
ConnectionManagerUtil.commitDBTransaction();
ConnectionManagerUtil.closeDBConnection();
Assert.assertNotNull(result, "Cannot be null");
}
@Test(dependsOnMethods = "testAddDeviceOrganization")
public void testUpdateDeviceOrganizationInactivate() throws DBConnectionException, DeviceOrganizationMgtDAOException {
ConnectionManagerUtil.beginDBTransaction();
boolean result = deviceOrganizationDAO.updateDeviceOrganization(4, 2, new Date(System.currentTimeMillis()), "INACTIVE", 1);
ConnectionManagerUtil.commitDBTransaction();
ConnectionManagerUtil.closeDBConnection();
Assert.assertNotNull(result, "Cannot be null");
}
@Test(dependsOnMethods = "testAddDeviceOrganization")
public void testGetDeviceOrganization() throws DBConnectionException, DeviceOrganizationMgtDAOException {
ConnectionManagerUtil.beginDBTransaction();
DeviceOrganization deviceOrganization = deviceOrganizationDAO.getDeviceOrganizationByID(1);
ConnectionManagerUtil.commitDBTransaction();
ConnectionManagerUtil.closeDBConnection();
Assert.assertNotNull(deviceOrganization, "Cannot be null");
}
}

@ -0,0 +1,78 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.device.mgt.extensions.device.organization;
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;
}
}

@ -0,0 +1,46 @@
package io.entgra.device.mgt.core.device.mgt.extensions.device.organization;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DeviceOrganizationMgtPluginException;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.impl.DeviceOrganizationServiceImpl;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.mock.BaseDeviceOrganizationTest;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.spi.DeviceOrganizationService;
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 java.sql.Date;
public class ServiceNegativeTest extends BaseDeviceOrganizationTest {
private static final Log log = LogFactory.getLog(ServiceNegativeTest.class);
private DeviceOrganizationService deviceOrganizationService;
@BeforeClass
public void init() {
deviceOrganizationService = new DeviceOrganizationServiceImpl();
log.info("Service test initialized");
}
@Test(description = "This method tests Add Device Organization method under negative circumstances with null data",
expectedExceptions = {NullPointerException.class})
public void testAddDeviceOrganization() throws DeviceOrganizationMgtPluginException {
DeviceOrganization deviceOrganization = new DeviceOrganization(){};
boolean result = deviceOrganizationService.addDeviceOrganization(deviceOrganization);
}
@Test(description = "This method tests Update Device Organization method under negative circumstances with " +
"invalid data",
expectedExceptions = {NullPointerException.class})
public void testUpdateDeviceOrganization() throws DeviceOrganizationMgtPluginException {
boolean result = deviceOrganizationService.updateDeviceOrganization(2,3,
new Date(System.currentTimeMillis()), "INACTIVE", 5);
}
}

@ -0,0 +1,90 @@
package io.entgra.device.mgt.core.device.mgt.extensions.device.organization;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceNode;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DeviceOrganizationMgtPluginException;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.impl.DeviceOrganizationServiceImpl;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.mock.BaseDeviceOrganizationTest;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.spi.DeviceOrganizationService;
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 java.sql.Date;
import java.util.List;
public class ServiceTest extends BaseDeviceOrganizationTest {
private static final Log log = LogFactory.getLog(ServiceTest.class);
private DeviceOrganizationService deviceOrganizationService;
@BeforeClass
public void init() {
deviceOrganizationService = new DeviceOrganizationServiceImpl();
log.info("Service test initialized");
}
@Test(dependsOnMethods = "testAddDeviceOrganization")
public void testGetChildrenOf() throws DeviceOrganizationMgtPluginException {
DeviceNode deviceNode = new DeviceNode();
deviceNode.setDeviceId(3);
List<DeviceNode> childrenList = deviceOrganizationService.getChildrenOf(deviceNode, 2, true);
Assert.assertNotNull(childrenList, "Cannot be null");
}
@Test(dependsOnMethods = "testAddDeviceOrganization")
public void testGetParentsOf() throws DeviceOrganizationMgtPluginException {
DeviceNode deviceNode = new DeviceNode();
deviceNode.setDeviceId(4);
List<DeviceNode> parentList = deviceOrganizationService.getParentsOf(deviceNode, 2, true);
Assert.assertNotNull(parentList, "Cannot be null");
}
@Test
public void testAddDeviceOrganization() throws DeviceOrganizationMgtPluginException {
DeviceOrganization.DeviceOrganizationStatus status = DeviceOrganization.DeviceOrganizationStatus.ACT;
DeviceOrganization deviceOrganization = new DeviceOrganization() {
};
deviceOrganization.setDeviceId(4);
deviceOrganization.setParentDeviceId(3);
deviceOrganization.setUpdateTime(new Date(System.currentTimeMillis()));
deviceOrganization.setStatus(status);
boolean result = deviceOrganizationService.addDeviceOrganization(deviceOrganization);
Assert.assertNotNull(result, "Cannot be null");
}
@Test(dependsOnMethods = "testAddDeviceOrganization")
public void testUpdateDeviceOrganization() throws DeviceOrganizationMgtPluginException {
boolean result = deviceOrganizationService.updateDeviceOrganization(4, 2, new Date(System.currentTimeMillis()), "ACTIVE", 1);
Assert.assertNotNull(result, "Cannot be null");
}
@Test(dependsOnMethods = "testAddDeviceOrganization")
public void testUpdateDeviceOrganizationInactivate() throws DeviceOrganizationMgtPluginException {
boolean result = deviceOrganizationService.updateDeviceOrganization(4, 2, new Date(System.currentTimeMillis()), "INACTIVE", 1);
Assert.assertNotNull(result, "Cannot be null");
}
@Test(dependsOnMethods = "testAddDeviceOrganization")
public void testGetDeviceOrganizationByID() throws DeviceOrganizationMgtPluginException {
DeviceOrganization deviceOrganization = deviceOrganizationService.getDeviceOrganizationByID(1);
Assert.assertNotNull(deviceOrganization, "Cannot be null");
}
}

@ -0,0 +1,53 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.device.mgt.extensions.device.organization;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.util.ConnectionManagerUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestUtils {
private static final Log log = LogFactory.getLog(TestUtils.class);
public static void cleanupResources(Connection conn, Statement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
ConnectionManagerUtil.closeDBConnection();
}
}
}

@ -0,0 +1,157 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.device.mgt.extensions.device.organization.mock;
import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.DataSourceConfig;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.TestUtils;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.DeviceOrganizationDAOFactory;
import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.util.ConnectionManagerUtil;
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.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.w3c.dom.Document;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
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.lang.reflect.Field;
import java.sql.Connection;
import java.sql.Statement;
public abstract class BaseDeviceOrganizationTest {
private static final Log log = LogFactory.getLog(BaseDeviceOrganizationTest.class);
private static final String datasourceLocation = "src/test/resources/carbon-home/repository/conf/" +
"datasources/data-source-config.xml";
private static boolean mock;
@BeforeSuite
@Parameters({"isMock"})
public void setup(@Optional("false") boolean isMock) throws Exception {
log.info("Setting up test suite");
this.initDataSource();
this.initSQLScript();
this.initializeCarbonContext();
this.initServices();
mock = isMock;
log.info("Setting up test suite done!");
}
protected void initDataSource() throws Exception {
DataSource dataSource = this.getDataSource(this.readDataSourceConfig());
Class<?> clazz1 = ConnectionManagerUtil.class;
Field f1 = clazz1.getDeclaredField("dataSource");
f1.setAccessible(true);
f1.set(clazz1, dataSource);
Class<?> clazz2 = DeviceOrganizationDAOFactory.class;
Field f2 = clazz2.getDeclaredField("databaseEngine");
f2.setAccessible(true);
f2.set(clazz2, DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2);
}
private void initServices() {
}
@BeforeClass
public abstract void init() throws Exception;
protected DataSource getDataSource(DataSourceConfig config) {
if (!isMock()) {
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);
} else {
return new MockDataSource(config.getUrl());
}
}
private void initializeCarbonContext() {
if (System.getProperty("carbon.home") == null) {
File file = new File("src/test/resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
file = new File("../resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
file = new File("../../resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
file = new File("../../../resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
}
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants
.SUPER_TENANT_DOMAIN_NAME);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
}
protected DataSourceConfig readDataSourceConfig() throws DeviceManagementException {
try {
File file = new File(BaseDeviceOrganizationTest.datasourceLocation);
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 {
ConnectionManagerUtil.beginDBTransaction();
conn = ConnectionManagerUtil.getDBConnection();
stmt = conn.createStatement();
stmt.executeUpdate("RUNSCRIPT FROM './src/test/resources/carbon-home/dbscripts/dm-db-h2.sql'");
stmt.executeUpdate("RUNSCRIPT FROM './src/test/resources/carbon-home/dbscripts/h2.sql'");
} finally {
TestUtils.cleanupResources(conn, stmt, null);
}
}
protected boolean isMock() {
return mock;
}
}

@ -0,0 +1,329 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.device.mgt.extensions.device.organization.mock;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
/**
* This is mock class which provides mock database connection.
*/
public class MockConnection implements Connection {
private final String url;
private final List<MockStatement> statements = new ArrayList<>();
private int statementCounter = 0;
public MockConnection(String url) {
this.url = url;
}
@Override
public Statement createStatement() throws SQLException {
return getStatement();
}
private MockStatement getStatement() {
if (!statements.isEmpty()) {
MockStatement statement = this.statements.get(this.statementCounter);
statementCounter++;
return statement;
}
return new MockStatement();
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return getStatement();
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
return null;
}
@Override
public String nativeSQL(String sql) throws SQLException {
return null;
}
@Override
public boolean getAutoCommit() throws SQLException {
return false;
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
}
@Override
public void commit() throws SQLException {
}
@Override
public void rollback() throws SQLException {
}
@Override
public void close() throws SQLException {
}
@Override
public boolean isClosed() throws SQLException {
return false;
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
return new MockDatabaseMetaData(this.url);
}
@Override
public boolean isReadOnly() throws SQLException {
return false;
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
}
@Override
public String getCatalog() throws SQLException {
return null;
}
@Override
public void setCatalog(String catalog) throws SQLException {
}
@Override
public int getTransactionIsolation() throws SQLException {
return 0;
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
}
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException {
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException {
return null;
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return null;
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
}
@Override
public int getHoldability() throws SQLException {
return 0;
}
@Override
public void setHoldability(int holdability) throws SQLException {
}
@Override
public Savepoint setSavepoint() throws SQLException {
return null;
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
return null;
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return new MockStatement();
}
@Override
public Clob createClob() throws SQLException {
return null;
}
@Override
public Blob createBlob() throws SQLException {
return null;
}
@Override
public NClob createNClob() throws SQLException {
return null;
}
@Override
public SQLXML createSQLXML() throws SQLException {
return null;
}
@Override
public boolean isValid(int timeout) throws SQLException {
return false;
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
}
@Override
public String getClientInfo(String name) throws SQLException {
return null;
}
@Override
public Properties getClientInfo() throws SQLException {
return null;
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return null;
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return null;
}
@Override
public String getSchema() throws SQLException {
return null;
}
@Override
public void setSchema(String schema) throws SQLException {
}
@Override
public void abort(Executor executor) throws SQLException {
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
}
@Override
public int getNetworkTimeout() throws SQLException {
return 0;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
public void addMockStatement(MockStatement mockStatement) {
this.statements.add(mockStatement);
}
}

@ -0,0 +1,123 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.device.mgt.extensions.device.organization.mock;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* This is the mock data source implementation that will be used in the test cases.
*/
public class MockDataSource implements DataSource {
private final List<Connection> connections = new ArrayList<>();
private final String url;
private boolean throwException = false;
private int connectionCounter = 0;
public MockDataSource(String url) {
this.url = url;
}
@Override
public Connection getConnection() throws SQLException {
if (throwException) {
throw new SQLException("Cannot created test connection.");
} else {
if (!connections.isEmpty()) {
if (this.connectionCounter < this.connections.size()) {
Connection connection = this.connections.get(this.connectionCounter);
this.connectionCounter++;
return connection;
} else {
return new MockConnection(url);
}
}
return new MockConnection(url);
}
}
public void setConnection(Connection connection) {
this.connections.add(connection);
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return null;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
}
@Override
public int getLoginTimeout() throws SQLException {
return 0;
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
public void setThrowException(boolean throwException) {
this.throwException = throwException;
}
public void reset() {
this.throwException = false;
this.connections.clear();
this.connectionCounter = 0;
}
public String getUrl() {
return this.url;
}
public MockConnection getConnection(int id) {
return (MockConnection) this.connections.get(id);
}
}

@ -0,0 +1,937 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.device.mgt.extensions.device.organization.mock;
import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants;
import java.sql.*;
public class MockDatabaseMetaData implements DatabaseMetaData {
private final String url;
public MockDatabaseMetaData(String url) {
this.url = url;
}
@Override
public boolean allProceduresAreCallable() throws SQLException {
return false;
}
@Override
public boolean allTablesAreSelectable() throws SQLException {
return false;
}
@Override
public String getURL() throws SQLException {
return null;
}
@Override
public String getUserName() throws SQLException {
return null;
}
@Override
public boolean isReadOnly() throws SQLException {
return false;
}
@Override
public boolean nullsAreSortedHigh() throws SQLException {
return false;
}
@Override
public boolean nullsAreSortedLow() throws SQLException {
return false;
}
@Override
public boolean nullsAreSortedAtStart() throws SQLException {
return false;
}
@Override
public boolean nullsAreSortedAtEnd() throws SQLException {
return false;
}
@Override
public String getDatabaseProductName() throws SQLException {
if (this.url.contains("mysql")) {
return DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL;
} else if (this.url.contains("h2")) {
return DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2;
} else if (this.url.contains("oracle")) {
return DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE;
} else if (this.url.contains("postgresql")) {
return DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL;
} else if (this.url.contains("sqlserver")) {
return DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL;
} else {
return null;
}
}
@Override
public String getDatabaseProductVersion() throws SQLException {
return null;
}
@Override
public String getDriverName() throws SQLException {
return null;
}
@Override
public String getDriverVersion() throws SQLException {
return null;
}
@Override
public int getDriverMajorVersion() {
return 0;
}
@Override
public int getDriverMinorVersion() {
return 0;
}
@Override
public boolean usesLocalFiles() throws SQLException {
return false;
}
@Override
public boolean usesLocalFilePerTable() throws SQLException {
return false;
}
@Override
public boolean supportsMixedCaseIdentifiers() throws SQLException {
return false;
}
@Override
public boolean storesUpperCaseIdentifiers() throws SQLException {
return false;
}
@Override
public boolean storesLowerCaseIdentifiers() throws SQLException {
return false;
}
@Override
public boolean storesMixedCaseIdentifiers() throws SQLException {
return false;
}
@Override
public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException {
return false;
}
@Override
public boolean storesUpperCaseQuotedIdentifiers() throws SQLException {
return false;
}
@Override
public boolean storesLowerCaseQuotedIdentifiers() throws SQLException {
return false;
}
@Override
public boolean storesMixedCaseQuotedIdentifiers() throws SQLException {
return false;
}
@Override
public String getIdentifierQuoteString() throws SQLException {
return null;
}
@Override
public String getSQLKeywords() throws SQLException {
return null;
}
@Override
public String getNumericFunctions() throws SQLException {
return null;
}
@Override
public String getStringFunctions() throws SQLException {
return null;
}
@Override
public String getSystemFunctions() throws SQLException {
return null;
}
@Override
public String getTimeDateFunctions() throws SQLException {
return null;
}
@Override
public String getSearchStringEscape() throws SQLException {
return null;
}
@Override
public String getExtraNameCharacters() throws SQLException {
return null;
}
@Override
public boolean supportsAlterTableWithAddColumn() throws SQLException {
return false;
}
@Override
public boolean supportsAlterTableWithDropColumn() throws SQLException {
return false;
}
@Override
public boolean supportsColumnAliasing() throws SQLException {
return false;
}
@Override
public boolean nullPlusNonNullIsNull() throws SQLException {
return false;
}
@Override
public boolean supportsConvert() throws SQLException {
return false;
}
@Override
public boolean supportsConvert(int fromType, int toType) throws SQLException {
return false;
}
@Override
public boolean supportsTableCorrelationNames() throws SQLException {
return false;
}
@Override
public boolean supportsDifferentTableCorrelationNames() throws SQLException {
return false;
}
@Override
public boolean supportsExpressionsInOrderBy() throws SQLException {
return false;
}
@Override
public boolean supportsOrderByUnrelated() throws SQLException {
return false;
}
@Override
public boolean supportsGroupBy() throws SQLException {
return false;
}
@Override
public boolean supportsGroupByUnrelated() throws SQLException {
return false;
}
@Override
public boolean supportsGroupByBeyondSelect() throws SQLException {
return false;
}
@Override
public boolean supportsLikeEscapeClause() throws SQLException {
return false;
}
@Override
public boolean supportsMultipleResultSets() throws SQLException {
return false;
}
@Override
public boolean supportsMultipleTransactions() throws SQLException {
return false;
}
@Override
public boolean supportsNonNullableColumns() throws SQLException {
return false;
}
@Override
public boolean supportsMinimumSQLGrammar() throws SQLException {
return false;
}
@Override
public boolean supportsCoreSQLGrammar() throws SQLException {
return false;
}
@Override
public boolean supportsExtendedSQLGrammar() throws SQLException {
return false;
}
@Override
public boolean supportsANSI92EntryLevelSQL() throws SQLException {
return false;
}
@Override
public boolean supportsANSI92IntermediateSQL() throws SQLException {
return false;
}
@Override
public boolean supportsANSI92FullSQL() throws SQLException {
return false;
}
@Override
public boolean supportsIntegrityEnhancementFacility() throws SQLException {
return false;
}
@Override
public boolean supportsOuterJoins() throws SQLException {
return false;
}
@Override
public boolean supportsFullOuterJoins() throws SQLException {
return false;
}
@Override
public boolean supportsLimitedOuterJoins() throws SQLException {
return false;
}
@Override
public String getSchemaTerm() throws SQLException {
return null;
}
@Override
public String getProcedureTerm() throws SQLException {
return null;
}
@Override
public String getCatalogTerm() throws SQLException {
return null;
}
@Override
public boolean isCatalogAtStart() throws SQLException {
return false;
}
@Override
public String getCatalogSeparator() throws SQLException {
return null;
}
@Override
public boolean supportsSchemasInDataManipulation() throws SQLException {
return false;
}
@Override
public boolean supportsSchemasInProcedureCalls() throws SQLException {
return false;
}
@Override
public boolean supportsSchemasInTableDefinitions() throws SQLException {
return false;
}
@Override
public boolean supportsSchemasInIndexDefinitions() throws SQLException {
return false;
}
@Override
public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException {
return false;
}
@Override
public boolean supportsCatalogsInDataManipulation() throws SQLException {
return false;
}
@Override
public boolean supportsCatalogsInProcedureCalls() throws SQLException {
return false;
}
@Override
public boolean supportsCatalogsInTableDefinitions() throws SQLException {
return false;
}
@Override
public boolean supportsCatalogsInIndexDefinitions() throws SQLException {
return false;
}
@Override
public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException {
return false;
}
@Override
public boolean supportsPositionedDelete() throws SQLException {
return false;
}
@Override
public boolean supportsPositionedUpdate() throws SQLException {
return false;
}
@Override
public boolean supportsSelectForUpdate() throws SQLException {
return false;
}
@Override
public boolean supportsStoredProcedures() throws SQLException {
return false;
}
@Override
public boolean supportsSubqueriesInComparisons() throws SQLException {
return false;
}
@Override
public boolean supportsSubqueriesInExists() throws SQLException {
return false;
}
@Override
public boolean supportsSubqueriesInIns() throws SQLException {
return false;
}
@Override
public boolean supportsSubqueriesInQuantifieds() throws SQLException {
return false;
}
@Override
public boolean supportsCorrelatedSubqueries() throws SQLException {
return false;
}
@Override
public boolean supportsUnion() throws SQLException {
return false;
}
@Override
public boolean supportsUnionAll() throws SQLException {
return false;
}
@Override
public boolean supportsOpenCursorsAcrossCommit() throws SQLException {
return false;
}
@Override
public boolean supportsOpenCursorsAcrossRollback() throws SQLException {
return false;
}
@Override
public boolean supportsOpenStatementsAcrossCommit() throws SQLException {
return false;
}
@Override
public boolean supportsOpenStatementsAcrossRollback() throws SQLException {
return false;
}
@Override
public int getMaxBinaryLiteralLength() throws SQLException {
return 0;
}
@Override
public int getMaxCharLiteralLength() throws SQLException {
return 0;
}
@Override
public int getMaxColumnNameLength() throws SQLException {
return 0;
}
@Override
public int getMaxColumnsInGroupBy() throws SQLException {
return 0;
}
@Override
public int getMaxColumnsInIndex() throws SQLException {
return 0;
}
@Override
public int getMaxColumnsInOrderBy() throws SQLException {
return 0;
}
@Override
public int getMaxColumnsInSelect() throws SQLException {
return 0;
}
@Override
public int getMaxColumnsInTable() throws SQLException {
return 0;
}
@Override
public int getMaxConnections() throws SQLException {
return 0;
}
@Override
public int getMaxCursorNameLength() throws SQLException {
return 0;
}
@Override
public int getMaxIndexLength() throws SQLException {
return 0;
}
@Override
public int getMaxSchemaNameLength() throws SQLException {
return 0;
}
@Override
public int getMaxProcedureNameLength() throws SQLException {
return 0;
}
@Override
public int getMaxCatalogNameLength() throws SQLException {
return 0;
}
@Override
public int getMaxRowSize() throws SQLException {
return 0;
}
@Override
public boolean doesMaxRowSizeIncludeBlobs() throws SQLException {
return false;
}
@Override
public int getMaxStatementLength() throws SQLException {
return 0;
}
@Override
public int getMaxStatements() throws SQLException {
return 0;
}
@Override
public int getMaxTableNameLength() throws SQLException {
return 0;
}
@Override
public int getMaxTablesInSelect() throws SQLException {
return 0;
}
@Override
public int getMaxUserNameLength() throws SQLException {
return 0;
}
@Override
public int getDefaultTransactionIsolation() throws SQLException {
return 0;
}
@Override
public boolean supportsTransactions() throws SQLException {
return false;
}
@Override
public boolean supportsTransactionIsolationLevel(int level) throws SQLException {
return false;
}
@Override
public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException {
return false;
}
@Override
public boolean supportsDataManipulationTransactionsOnly() throws SQLException {
return false;
}
@Override
public boolean dataDefinitionCausesTransactionCommit() throws SQLException {
return false;
}
@Override
public boolean dataDefinitionIgnoredInTransactions() throws SQLException {
return false;
}
@Override
public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern)
throws SQLException {
return null;
}
@Override
public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern,
String columnNamePattern) throws SQLException {
return null;
}
@Override
public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)
throws SQLException {
return null;
}
@Override
public ResultSet getSchemas() throws SQLException {
return null;
}
@Override
public ResultSet getCatalogs() throws SQLException {
return null;
}
@Override
public ResultSet getTableTypes() throws SQLException {
return null;
}
@Override
public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern,
String columnNamePattern) throws SQLException {
return null;
}
@Override
public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern)
throws SQLException {
return null;
}
@Override
public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern)
throws SQLException {
return null;
}
@Override
public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable)
throws SQLException {
return null;
}
@Override
public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException {
return null;
}
@Override
public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException {
return null;
}
@Override
public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException {
return null;
}
@Override
public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException {
return null;
}
@Override
public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable,
String foreignCatalog, String foreignSchema, String foreignTable)
throws SQLException {
return null;
}
@Override
public ResultSet getTypeInfo() throws SQLException {
return null;
}
@Override
public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate)
throws SQLException {
return null;
}
@Override
public boolean supportsResultSetType(int type) throws SQLException {
return false;
}
@Override
public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException {
return false;
}
@Override
public boolean ownUpdatesAreVisible(int type) throws SQLException {
return false;
}
@Override
public boolean ownDeletesAreVisible(int type) throws SQLException {
return false;
}
@Override
public boolean ownInsertsAreVisible(int type) throws SQLException {
return false;
}
@Override
public boolean othersUpdatesAreVisible(int type) throws SQLException {
return false;
}
@Override
public boolean othersDeletesAreVisible(int type) throws SQLException {
return false;
}
@Override
public boolean othersInsertsAreVisible(int type) throws SQLException {
return false;
}
@Override
public boolean updatesAreDetected(int type) throws SQLException {
return false;
}
@Override
public boolean deletesAreDetected(int type) throws SQLException {
return false;
}
@Override
public boolean insertsAreDetected(int type) throws SQLException {
return false;
}
@Override
public boolean supportsBatchUpdates() throws SQLException {
return false;
}
@Override
public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types)
throws SQLException {
return null;
}
@Override
public Connection getConnection() throws SQLException {
return null;
}
@Override
public boolean supportsSavepoints() throws SQLException {
return false;
}
@Override
public boolean supportsNamedParameters() throws SQLException {
return false;
}
@Override
public boolean supportsMultipleOpenResults() throws SQLException {
return false;
}
@Override
public boolean supportsGetGeneratedKeys() throws SQLException {
return false;
}
@Override
public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException {
return null;
}
@Override
public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException {
return null;
}
@Override
public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern,
String attributeNamePattern) throws SQLException {
return null;
}
@Override
public boolean supportsResultSetHoldability(int holdability) throws SQLException {
return false;
}
@Override
public int getResultSetHoldability() throws SQLException {
return 0;
}
@Override
public int getDatabaseMajorVersion() throws SQLException {
return 0;
}
@Override
public int getDatabaseMinorVersion() throws SQLException {
return 0;
}
@Override
public int getJDBCMajorVersion() throws SQLException {
return 0;
}
@Override
public int getJDBCMinorVersion() throws SQLException {
return 0;
}
@Override
public int getSQLStateType() throws SQLException {
return 0;
}
@Override
public boolean locatorsUpdateCopy() throws SQLException {
return false;
}
@Override
public boolean supportsStatementPooling() throws SQLException {
return false;
}
@Override
public RowIdLifetime getRowIdLifetime() throws SQLException {
return null;
}
@Override
public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException {
return null;
}
@Override
public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException {
return false;
}
@Override
public boolean autoCommitFailureClosesAllResultSets() throws SQLException {
return false;
}
@Override
public ResultSet getClientInfoProperties() throws SQLException {
return null;
}
@Override
public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException {
return null;
}
@Override
public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern,
String columnNamePattern) throws SQLException {
return null;
}
@Override
public ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern,
String columnNamePattern) throws SQLException {
return null;
}
@Override
public boolean generatedKeyAlwaysReturned() throws SQLException {
return false;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}

@ -0,0 +1,545 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.device.mgt.extensions.device.organization.mock;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* This is the mock statement for the test cases.
*/
public class MockStatement implements PreparedStatement {
private final List<MockResultSet> resultSets = new ArrayList<>();
private int resultSetCounter;
@Override
public ResultSet executeQuery(String sql) throws SQLException {
return this.getMockResultSet();
}
private ResultSet getMockResultSet() {
if (!this.resultSets.isEmpty()) {
ResultSet resultSet = this.resultSets.get(this.resultSetCounter);
this.resultSetCounter++;
return resultSet;
} else {
return new MockResultSet();
}
}
@Override
public int executeUpdate(String sql) throws SQLException {
return 0;
}
@Override
public void close() throws SQLException {
}
@Override
public int getMaxFieldSize() throws SQLException {
return 0;
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
}
@Override
public int getMaxRows() throws SQLException {
return 0;
}
@Override
public void setMaxRows(int max) throws SQLException {
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
}
@Override
public int getQueryTimeout() throws SQLException {
return 0;
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
}
@Override
public void cancel() throws SQLException {
}
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public void setCursorName(String name) throws SQLException {
}
@Override
public boolean execute(String sql) throws SQLException {
return false;
}
@Override
public ResultSet getResultSet() throws SQLException {
return getMockResultSet();
}
@Override
public int getUpdateCount() throws SQLException {
return 0;
}
@Override
public boolean getMoreResults() throws SQLException {
return false;
}
@Override
public int getFetchDirection() throws SQLException {
return 0;
}
@Override
public void setFetchDirection(int direction) throws SQLException {
}
@Override
public int getFetchSize() throws SQLException {
return 0;
}
@Override
public void setFetchSize(int rows) throws SQLException {
}
@Override
public int getResultSetConcurrency() throws SQLException {
return 0;
}
@Override
public int getResultSetType() throws SQLException {
return 0;
}
@Override
public void addBatch(String sql) throws SQLException {
}
@Override
public void clearBatch() throws SQLException {
}
@Override
public int[] executeBatch() throws SQLException {
return new int[0];
}
@Override
public Connection getConnection() throws SQLException {
return null;
}
@Override
public boolean getMoreResults(int current) throws SQLException {
return false;
}
@Override
public ResultSet getGeneratedKeys() throws SQLException {
return getMockResultSet();
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
return 0;
}
@Override
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
return 0;
}
@Override
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
return 0;
}
@Override
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
return false;
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
return false;
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException {
return false;
}
@Override
public int getResultSetHoldability() throws SQLException {
return 0;
}
@Override
public boolean isClosed() throws SQLException {
return false;
}
@Override
public boolean isPoolable() throws SQLException {
return false;
}
@Override
public void setPoolable(boolean poolable) throws SQLException {
}
@Override
public void closeOnCompletion() throws SQLException {
}
@Override
public boolean isCloseOnCompletion() throws SQLException {
return false;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public ResultSet executeQuery() throws SQLException {
return getMockResultSet();
}
@Override
public int executeUpdate() throws SQLException {
return 0;
}
@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
}
@Override
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
}
@Override
public void setByte(int parameterIndex, byte x) throws SQLException {
}
@Override
public void setShort(int parameterIndex, short x) throws SQLException {
}
@Override
public void setInt(int parameterIndex, int x) throws SQLException {
}
@Override
public void setLong(int parameterIndex, long x) throws SQLException {
}
@Override
public void setFloat(int parameterIndex, float x) throws SQLException {
}
@Override
public void setDouble(int parameterIndex, double x) throws SQLException {
}
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
}
@Override
public void setString(int parameterIndex, String x) throws SQLException {
}
@Override
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
}
@Override
public void setDate(int parameterIndex, Date x) throws SQLException {
}
@Override
public void setTime(int parameterIndex, Time x) throws SQLException {
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
}
@Override
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
}
@Override
public void clearParameters() throws SQLException {
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
}
@Override
public void setObject(int parameterIndex, Object x) throws SQLException {
}
@Override
public boolean execute() throws SQLException {
return false;
}
@Override
public void addBatch() throws SQLException {
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
}
@Override
public void setRef(int parameterIndex, Ref x) throws SQLException {
}
@Override
public void setBlob(int parameterIndex, Blob x) throws SQLException {
}
@Override
public void setClob(int parameterIndex, Clob x) throws SQLException {
}
@Override
public void setArray(int parameterIndex, Array x) throws SQLException {
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
return null;
}
@Override
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
}
@Override
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
}
@Override
public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
}
@Override
public void setURL(int parameterIndex, URL x) throws SQLException {
}
@Override
public ParameterMetaData getParameterMetaData() throws SQLException {
return null;
}
@Override
public void setRowId(int parameterIndex, RowId x) throws SQLException {
}
@Override
public void setNString(int parameterIndex, String value) throws SQLException {
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
}
@Override
public void setNClob(int parameterIndex, NClob value) throws SQLException {
}
@Override
public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
}
@Override
public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
}
@Override
public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
}
@Override
public void setClob(int parameterIndex, Reader reader) throws SQLException {
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
}
@Override
public void setNClob(int parameterIndex, Reader reader) throws SQLException {
}
public void addResultSet(MockResultSet resultSet) {
this.resultSets.add(resultSet);
}
}

@ -802,19 +802,19 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_SUB_TYPE (
TYPE_DEFINITION TEXT NOT NULL,
PRIMARY KEY (SUB_TYPE_ID,DEVICE_TYPE)
);
-- END OF DM_DEVICE_SUB_TYPE TABLE--
--DM_DEVICE_ORGANIZATION TABLE--
-- DM_DEVICE_ORGANIZATION TABLE--
CREATE TABLE IF NOT EXISTS DM_DEVICE_ORGANIZATION (
ID INTEGER auto_increment NOT NULL,
DEVICE_ID INT(11) DEFAULT NULL,
PARENT_DEVICE_ID INT(11) DEFAULT NULL,
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INT(11) DEFAULT NULL,
PARENT_DEVICE_ID INT(11) DEFAULT NULL,
LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL,
STATUS VARCHAR(50) DEFAULT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_DM_DEVICE_DM_ID FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_DM_DEVICE_DM_ID2 FOREIGN KEY (PARENT_DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
);
-- END OF DM_DEVICE_ORGANIZATION TABLE--

@ -23,9 +23,10 @@
DEVICE_ID INT(11) DEFAULT NULL,
PARENT_DEVICE_ID INT(11) DEFAULT NULL,
LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL,
STATUS VARCHAR(50) DEFAULT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_DM_DEVICE_DM_ID FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_DM_DEVICE_DM_ID2 FOREIGN KEY (PARENT_DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
@ -33,9 +34,14 @@
-- -----------------------------------------------------
-- Sample data for test cases
-- -----------------------------------------------------
INSERT INTO DM_DEVICE_TYPE ()
INSERT INTO DM_DEVICE ()
INSERT INTO DM_DEVICE_ORGANIZATION (DEVICE_ID, PARENT_DEVICE_ID, LAST_UPDATED_TIMESTAMP) VALUES
(),
();
INSERT INTO DM_DEVICE_TYPE (ID,NAME,DEVICE_TYPE_META,LAST_UPDATED_TIMESTAMP,PROVIDER_TENANT_ID,SHARED_WITH_ALL_TENANTS)
VALUES (1,'METER','meter',CURRENT_TIMESTAMP(),1,true);
INSERT INTO DM_DEVICE (ID,DESCRIPTION,NAME,DEVICE_TYPE_ID,DEVICE_IDENTIFICATION,LAST_UPDATED_TIMESTAMP,TENANT_ID) VALUES
(1,'test device 1','Meter 01',1,'0001',CURRENT_TIMESTAMP(),1),
(2,'test device 2','Meter 02',1,'0002',CURRENT_TIMESTAMP(),1),
(3,'test device 3','Meter 03',1,'0003',CURRENT_TIMESTAMP(),1),
(4,'test device 4','Meter 04',1,'0004',CURRENT_TIMESTAMP(),1),
-- INSERT INTO DM_DEVICE_ORGANIZATION (DEVICE_ID, PARENT_DEVICE_ID, LAST_UPDATED_TIMESTAMP) VALUES
-- (2,1,CURRENT_TIMESTAMP()),
-- (3,2,CURRENT_TIMESTAMP());

@ -1,33 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. 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.
-->
<DataSourceConfig>
<Url>jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true</Url>
<DriverClassName>io.entgra.device.mgt.core.device.mgt.core.mock.MockJDBCDriver</DriverClassName>
<User>wso2carbon</User>
<Password>wso2carbon</Password>
<!-- For MySql -->
<!--<Url>jdbc:mysql://localhost:3306/WSO2CDM</Url>-->
<!--<DriverClassName>com.mysql.jdbc.Driver</DriverClassName>-->
<!--<User>root</User>-->
<!--<Password></Password>-->
</DataSourceConfig>

@ -1,33 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. 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.
-->
<DataSourceConfig>
<Url>jdbc:h2:mem:nodb-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true</Url>
<DriverClassName>org.h2.Driver</DriverClassName>
<User>wso2carbon</User>
<Password>wso2carbon</Password>
<!-- For MySql -->
<!--<Url>jdbc:mysql://localhost:3306/WSO2CDM</Url>-->
<!--<DriverClassName>com.mysql.jdbc.Driver</DriverClassName>-->
<!--<User>root</User>-->
<!--<Password></Password>-->
</DataSourceConfig>

@ -1,33 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. 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.
-->
<DataSourceConfig>
<Url>jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true</Url>
<DriverClassName>org.h2.Driver</DriverClassName>
<User>wso2carbon</User>
<Password>wso2carbon</Password>
<!-- For MySql -->
<!--<Url>jdbc:mysql://localhost:3306/WSO2CDM</Url>-->
<!--<DriverClassName>com.mysql.jdbc.Driver</DriverClassName>-->
<!--<User>root</User>-->
<!--<Password></Password>-->
</DataSourceConfig>

@ -1,11 +0,0 @@
CREATE TABLE IF NOT EXISTS DM_DEVICE_ORGANIZATION (
ID INTEGER auto_increment NOT NULL,
DEVICE_ID INT(11) DEFAULT NULL,
PARENT_DEVICE_ID INT(11) DEFAULT NULL,
LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_DM_DEVICE_DM_ID FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
CONSTRAINT fk_DM_DEVICE_DM_ID2 FOREIGN KEY (PARENT_DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);

@ -23,13 +23,15 @@
<test name="DAO Unit Tests" preserve-order="true">
<classes>
<class name="io.entgra.device.mgt.core.device.mgt.extensions.device.organization.DAONegativeTest"/>
<class name="io.entgra.device.mgt.core.device.mgt.extensions.device.organization.DAOTest"/>
</classes>
</test>
<test name="Service Unit Tests" preserve-order="true">
<classes>
<class name="io.entgra.device.mgt.core.device.mgt.extensions.device.organization.ServiceTest"/>
<class name="io.entgra.device.mgt.core.device.mgt.extensions.device.organization.ServiceNegativeTest"/>
</classes>
</test>
</suite>

Loading…
Cancel
Save