From 062a843ca2ceff551678ac70139d6d85b171ad32 Mon Sep 17 00:00:00 2001 From: charithag Date: Mon, 28 Mar 2016 13:28:49 +0530 Subject: [PATCH 1/5] Fix for https://wso2.org/jira/browse/IOTS-99 --- .../devicemgt/app/pages/cdmf.page.devices/devices.hbs | 2 +- .../devicemgt/app/pages/cdmf.page.devices/devices.js | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs index 7770787a6c..f17d24d014 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs @@ -40,7 +40,7 @@ {{else}} - {{#if permissions.addDevice}} + {{#if permissions.enroll}}
  • diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js index 78de108394..50480ab828 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js @@ -26,10 +26,11 @@ function onRequest(context) { page.groupName = groupName; } page.title =title; + page.permissions = {}; var currentUser = session.get(constants.USER_SESSION_KEY); if (currentUser) { if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/add")) { - page.addDevice = true; + page.permissions.enroll = true; } } return page; From fa2f61f48ac215d150be8b3d4b40b718ad746fa0 Mon Sep 17 00:00:00 2001 From: charithag Date: Tue, 29 Mar 2016 12:41:38 +0530 Subject: [PATCH 2/5] Add missing parts in group management --- .../mgt/common/group/mgt/DeviceGroup.java | 10 + .../core/group/mgt/DeviceGroupBuilder.java | 6 + .../mgt/core/group/mgt/dao/GroupDAO.java | 107 ++- .../mgt/core/group/mgt/dao/GroupDAOImpl.java | 150 +++- .../group/mgt/dao/GroupManagementDAOUtil.java | 3 +- .../DeviceManagementServiceComponent.java | 6 + ...va => GroupManagementProviderService.java} | 68 +- ...> GroupManagementProviderServiceImpl.java} | 286 ++++---- .../core/common/BaseDeviceManagementTest.java | 9 + .../mgt/core/common/TestDataHolder.java | 18 +- .../mgt/core/dao/GroupPersistTests.java | 204 ++++++ .../src/test/resources/sql/h2.sql | 651 +++++++++-------- .../src/test/resources/testng.xml | 3 +- .../src/main/resources/dbscripts/cdm/h2.sql | 652 +++++++++--------- 14 files changed, 1284 insertions(+), 889 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/{GroupManagementServiceProvider.java => GroupManagementProviderService.java} (73%) rename components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/{GroupManagementServiceProviderImpl.java => GroupManagementProviderServiceImpl.java} (73%) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java index 0be33284e6..2c106da829 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java @@ -29,6 +29,7 @@ import java.util.List; @XmlRootElement public class DeviceGroup implements Serializable { + private int id; private String description; private String name; private Long dateOfCreation; @@ -37,6 +38,15 @@ public class DeviceGroup implements Serializable { private List users; private List roles; + @XmlElement + public int getId() { + return id; + } + + protected void setId(int id) { + this.id = id; + } + @XmlElement public String getDescription() { return description; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java index 99098ad07e..b2409b2d70 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java @@ -34,6 +34,7 @@ public class DeviceGroupBuilder extends DeviceGroup { * @param deviceGroup to decorate */ public DeviceGroupBuilder(DeviceGroup deviceGroup) { + this.setId(deviceGroup.getId()); this.setDescription(deviceGroup.getDescription()); this.setName(deviceGroup.getName()); this.setDateOfCreation(deviceGroup.getDateOfCreation()); @@ -43,6 +44,11 @@ public class DeviceGroupBuilder extends DeviceGroup { this.setRoles(deviceGroup.getRoles()); } + @Override + public void setId(int id) { + super.setId(id); + } + @Override public void setUsers(List users) { super.setUsers(users); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java index dbb98c2e74..9fc556c266 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java @@ -20,7 +20,10 @@ package org.wso2.carbon.device.mgt.core.group.mgt.dao; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import java.util.List; @@ -31,44 +34,44 @@ import java.util.Set; */ public interface GroupDAO { /** - * Add new Device Group + * Add new Device Group. * - * @param deviceGroup to be added - * @param tenantId of the group - * @return sql execution result + * @param deviceGroup to be added. + * @param tenantId of the group. + * @return sql execution result. * @throws GroupManagementDAOException */ int addGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException; /** - * Update an existing Device Group + * Update an existing Device Group. * - * @param deviceGroup group to update + * @param deviceGroup group to update. * @throws GroupManagementDAOException */ void updateGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException; /** - * Delete an existing Device Group + * Delete an existing Device Group. * - * @param groupName group Id to delete + * @param groupId to be deleted. * @throws GroupManagementDAOException */ - void deleteGroup(String groupName, int tenantId) throws GroupManagementDAOException; + void deleteGroup(int groupId, int tenantId) throws GroupManagementDAOException; /** - * Get device group by Id + * Get device group by id. * - * @param groupName id of Device Group - * @return Device Group + * @param groupId of Device Group. + * @return Device Group in tenant with specified name. * @throws GroupManagementDAOException */ - DeviceGroupBuilder getGroup(String groupName, int tenantId) throws GroupManagementDAOException; + DeviceGroupBuilder getGroup(int groupId, int tenantId) throws GroupManagementDAOException; /** * Get the list of Device Groups in tenant. * - * @param tenantId of user's tenant + * @param tenantId of user's tenant. * @return List of all Device Groups in tenant. * @throws GroupManagementDAOException */ @@ -77,25 +80,81 @@ public interface GroupDAO { /** * Get the list of Groups that matches with the given DeviceGroup name. * - * @param groupName name of the Device Group. - * @param tenantId of user's tenant + * @param groupName of the Device Group. + * @param tenantId of user's tenant. * @return List of DeviceGroup that matches with the given DeviceGroup name. * @throws GroupManagementDAOException */ - List getGroups(String groupName, int tenantId) throws GroupManagementDAOException; + List findInGroups(String groupName, int tenantId) throws GroupManagementDAOException; + /** + * Check group already existed with given name. + * + * @param groupName of the Device Group. + * @param tenantId of user's tenant. + * @return existence of group with name + * @throws GroupManagementDAOException + */ boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException; - void addDeviceToGroup(String groupName, Device device, int tenantId) throws GroupManagementDAOException; + /** + * Add device to a given Device Group. + * + * @param groupId of the Device Group. + * @param deviceId of the device. + * @param tenantId of user's tenant. + * @throws GroupManagementDAOException + */ + void addDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException; - void addDevicesToGroup(String groupName, Set devices, int tenantId) throws GroupManagementDAOException; + /** + * Remove device from the Device Group. + * + * @param groupId of the Device Group. + * @param deviceId of the device. + * @param tenantId of user's tenant. + * @throws GroupManagementDAOException + */ + void removeDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException; - void removeDeviceFromGroup(String groupName, DeviceIdentifier id, - int tenantId) throws GroupManagementDAOException; + /** + * Check device is belonging to a Device Group. + * + * @param groupId of the Device Group. + * @param deviceId of the device. + * @param tenantId of user's tenant. + * @throws GroupManagementDAOException + */ + boolean isDeviceMappedToGroup(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException; - boolean isDeviceMappedToGroup(String groupName, DeviceIdentifier id, - int tenantId) throws GroupManagementDAOException; + /** + * Get count of devices in a Device Group. + * + * @param groupId of the Device Group. + * @param tenantId of user's tenant. + * @return device count. + * @throws GroupManagementDAOException + */ + int getDeviceCount(int groupId, int tenantId) throws GroupManagementDAOException; - int getDeviceCount(String groupName, int tenantId) throws GroupManagementDAOException; + /** + * Get all devices of a given tenant and device group. + * + * @param groupId of the group. + * @param tenantId of user's tenant. + * @return list of device in group + * @throws GroupManagementDAOException + */ + List getDevices(int groupId, int tenantId) throws GroupManagementDAOException; + /** + * Get all devices of a given tenant and device group. + * + * @param groupId of the group. + * @param tenantId of user's tenant. + * @param request for pagination. + * @return list of device in group + * @throws GroupManagementDAOException + */ + PaginationResult getDevices(int groupId, PaginationRequest request, int tenantId) throws GroupManagementDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java index 767e6ef367..3023a07f3b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java @@ -19,7 +19,8 @@ package org.wso2.carbon.device.mgt.core.group.mgt.dao; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; @@ -30,7 +31,6 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.Set; /** * This class represents implementation of GroupDAO @@ -44,9 +44,9 @@ public class GroupDAOImpl implements GroupDAO { int groupId = -1; try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "INSERT INTO DM_GROUP(DESCRIPTION, GROUP_NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, " + String sql = "INSERT INTO DM_GROUP(DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, " + "OWNER, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?)"; - stmt = conn.prepareStatement(sql, new String[]{"id"}); + stmt = conn.prepareStatement(sql, new String[]{"ID"}); stmt.setString(1, deviceGroup.getDescription()); stmt.setString(2, deviceGroup.getName()); stmt.setLong(3, new Date().getTime()); @@ -73,13 +73,13 @@ public class GroupDAOImpl implements GroupDAO { try { Connection conn = GroupManagementDAOFactory.getConnection(); String sql = "UPDATE DM_GROUP SET DESCRIPTION = ?, GROUP_NAME = ?, DATE_OF_LAST_UPDATE = ?, OWNER = ? " - + "WHERE NAME = ? AND TENANT_ID = ?"; + + "WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceGroup.getDescription()); stmt.setString(2, deviceGroup.getName()); stmt.setLong(3, deviceGroup.getDateOfLastUpdate()); stmt.setString(4, deviceGroup.getOwner()); - stmt.setString(5, deviceGroup.getName()); + stmt.setInt(5, deviceGroup.getId()); stmt.setInt(6, tenantId); stmt.executeUpdate(); } catch (SQLException e) { @@ -91,33 +91,46 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public void deleteGroup(String groupName, int tenantId) throws GroupManagementDAOException { + public void deleteGroup(int groupId, int tenantId) throws GroupManagementDAOException { Connection conn; PreparedStatement stmt = null; try { conn = GroupManagementDAOFactory.getConnection(); - String sql = "DELETE FROM DM_GROUP WHERE NAME = ? AND TENANT_ID = ?"; + String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); - stmt.setString(1, groupName); + stmt.setInt(1, groupId); stmt.setInt(2, tenantId); stmt.executeUpdate(); } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while deleting group '" + groupName + "'", e); + throw new GroupManagementDAOException("Error occurred while removing mappings for group '" + groupId + "'", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, null); + } + + try { + conn = GroupManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_GROUP WHERE ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + stmt.executeUpdate(); + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while deleting group '" + groupId + "'", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, null); } } @Override - public DeviceGroupBuilder getGroup(String groupName, int tenantId) throws GroupManagementDAOException { + public DeviceGroupBuilder getGroup(int groupId, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, OWNER " - + "FROM DM_GROUP WHERE NAME = ? AND TENANT_ID = ?"; + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " + + "FROM DM_GROUP WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); - stmt.setString(1, groupName); + stmt.setInt(1, groupId); stmt.setInt(2, tenantId); resultSet = stmt.executeQuery(); if (resultSet.next()) { @@ -127,7 +140,7 @@ public class GroupDAOImpl implements GroupDAO { } } catch (SQLException e) { throw new GroupManagementDAOException("Error occurred while obtaining information of Device Group '" + - groupName + "'", e); + groupId + "'", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, resultSet); } @@ -140,7 +153,7 @@ public class GroupDAOImpl implements GroupDAO { List deviceGroupList = null; try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, OWNER " + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " + "FROM DM_GROUP WHERE TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -158,14 +171,14 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public List getGroups(String groupName, int tenantId) + public List findInGroups(String groupName, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; List deviceGroups = new ArrayList<>(); try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, OWNER " + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " + "FROM DM_GROUP WHERE GROUP_NAME LIKE ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, "%" + groupName + "%"); @@ -186,49 +199,118 @@ public class GroupDAOImpl implements GroupDAO { @Override public boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; - ResultSet rst = null; + ResultSet resultSet = null; try { Connection conn = GroupManagementDAOFactory.getConnection(); String sql = "SELECT ID FROM DM_GROUP WHERE GROUP_NAME = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, groupName); stmt.setInt(2, tenantId); - rst = stmt.executeQuery(); - return rst.next(); + resultSet = stmt.executeQuery(); + return resultSet.next(); } catch (SQLException e) { throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" + groupName + "'", e); } finally { - GroupManagementDAOUtil.cleanupResources(stmt, rst); + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); } } @Override - public void addDeviceToGroup(String group, Device device, int tenantId) throws GroupManagementDAOException { - + public void addDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException { + PreparedStatement stmt = null; + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "INSERT INTO DM_DEVICE_GROUP_MAP(DEVICE_ID, GROUP_ID, TENANT_ID) VALUES (?, ?, ?)"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + stmt.setInt(2, groupId); + stmt.setInt(3, tenantId); + stmt.executeUpdate(); + stmt.getGeneratedKeys(); + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while adding device to Group '" + groupId + "'", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, null); + } } @Override - public void addDevicesToGroup(String group, Set devices, - int tenantId) throws GroupManagementDAOException { - + public void removeDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException { + PreparedStatement stmt = null; + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE DEVICE_ID = ? AND GROUP_ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + stmt.setInt(2, groupId); + stmt.setInt(3, tenantId); + stmt.executeUpdate(); + stmt.getGeneratedKeys(); + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while removing device from Group '" + + groupId + "'", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, null); + } } @Override - public void removeDeviceFromGroup(String group, DeviceIdentifier id, - int tenantId) throws GroupManagementDAOException { + public boolean isDeviceMappedToGroup(int groupId, int deviceId, int tenantId) + throws GroupManagementDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT ID FROM DM_DEVICE_GROUP_MAP WHERE DEVICE_ID = ? AND GROUP_ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + stmt.setInt(2, groupId); + stmt.setInt(3, tenantId); + resultSet = stmt.executeQuery(); + return resultSet.next(); + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" + + groupId + "'", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + } + @Override + public int getDeviceCount(int groupId, int tenantId) throws GroupManagementDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT COUNT(ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = ? " + + "AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + resultSet = stmt.executeQuery(); + if (resultSet.next()) { + return resultSet.getInt("DEVICE_COUNT"); + } else { + return 0; + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" + + groupId + "'", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } } @Override - public boolean isDeviceMappedToGroup(String group, DeviceIdentifier id, - int tenantId) throws GroupManagementDAOException { - return false; + public List getDevices(int groupId, int tenantId) throws GroupManagementDAOException { + return null; } @Override - public int getDeviceCount(String groupName, int tenantId) throws GroupManagementDAOException { - return 0; + public PaginationResult getDevices(int groupId, PaginationRequest request, int tenantId) + throws GroupManagementDAOException { + return null; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOUtil.java index fa3e52c436..a48af760b5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOUtil.java @@ -82,9 +82,10 @@ public final class GroupManagementDAOUtil { public static DeviceGroupBuilder loadGroup(ResultSet resultSet) throws SQLException { DeviceGroupBuilder group = new DeviceGroupBuilder(new DeviceGroup()); + group.setId(resultSet.getInt("ID")); group.setDescription(resultSet.getString("DESCRIPTION")); group.setName(resultSet.getString("GROUP_NAME")); - group.setDateOfCreation(resultSet.getLong("DATE_OF_ENROLLMENT")); + group.setDateOfCreation(resultSet.getLong("DATE_OF_CREATE")); group.setDateOfLastUpdate(resultSet.getLong("DATE_OF_LAST_UPDATE")); group.setOwner(resultSet.getString("OWNER")); return group; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java index 96d9e8d973..129bd30c6e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -50,6 +50,8 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOF import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer; import org.wso2.carbon.email.sender.core.service.EmailSenderService; import org.wso2.carbon.ndatasource.core.DataSourceService; @@ -181,6 +183,10 @@ public class DeviceManagementServiceComponent { DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProvider); bundleContext.registerService(DeviceManagementProviderService.class.getName(), deviceManagementProvider, null); + /* Registering Group Management Service */ + GroupManagementProviderService groupManagementProvider = new GroupManagementProviderServiceImpl(); + bundleContext.registerService(GroupManagementProviderService.class.getName(), groupManagementProvider, null); + /* Registering Tenant Configuration Management Service */ TenantConfigurationManagementService tenantConfiguration = new TenantConfigurationManagementServiceImpl(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProvider.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java similarity index 73% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProvider.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java index 7d81ad7657..3174772201 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProvider.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java @@ -31,7 +31,7 @@ import java.util.List; /** * Interface for Group Management Services */ -public interface GroupManagementServiceProvider { +public interface GroupManagementProviderService { /** * Add new device group and create default role with default permissions @@ -56,19 +56,19 @@ public interface GroupManagementServiceProvider { /** * Delete existing device group * - * @param groupName of the group to delete + * @param groupId of the group to delete * @throws GroupManagementException */ - boolean deleteGroup(String groupName) throws GroupManagementException; + boolean deleteGroup(int groupId) throws GroupManagementException; /** * Get device group specified by groupId * - * @param groupName of the group of the group + * @param groupId of the group of the group * @return group * @throws GroupManagementException */ - DeviceGroup getGroup(String groupName) throws GroupManagementException; + DeviceGroup getGroup(int groupId) throws GroupManagementException; /** * Get list of device groups matched with %groupName% @@ -78,7 +78,7 @@ public interface GroupManagementServiceProvider { * @return List of Groups that matches with the given DeviceGroup name. * @throws GroupManagementException */ - List findGroups(String groupName, String username) throws GroupManagementException; + List findInGroups(String groupName, String username) throws GroupManagementException; /** * Get device groups of user @@ -102,134 +102,134 @@ public interface GroupManagementServiceProvider { * Share device group with user specified by role * * @param username of the user - * @param groupName of the group of the group + * @param groupId of the group of the group * @param sharingRole to be shared * @return is group shared * @throws GroupManagementException */ - boolean shareGroup(String username, String groupName, String sharingRole) + boolean shareGroup(String username, int groupId, String sharingRole) throws GroupManagementException; /** * Un share existing group sharing with user specified by role * * @param userName of the user - * @param groupName of the group of the group + * @param groupId of the group of the group * @param sharingRole to be un shared * @return is group un shared * @throws GroupManagementException */ - boolean unshareGroup(String userName, String groupName, String sharingRole) + boolean unshareGroup(String userName, int groupId, String sharingRole) throws GroupManagementException; /** * Add new sharing role for device group * * @param userName of the user - * @param groupName of the group + * @param groupId of the group * @param roleName to add * @param permissions to bind with role * @return is role added * @throws GroupManagementException */ - boolean addGroupSharingRole(String userName, String groupName, String roleName, String[] permissions) + boolean addGroupSharingRole(String userName, int groupId, String roleName, String[] permissions) throws GroupManagementException; /** * Remove existing sharing role for device group * - * @param groupName of the group + * @param groupId of the group * @param roleName to remove * @return is role removed * @throws GroupManagementException */ - boolean removeGroupSharingRole(String groupName, String roleName) throws GroupManagementException; + boolean removeGroupSharingRole(int groupId, String roleName) throws GroupManagementException; /** * Get all sharing roles for device group * - * @param groupName of the group + * @param groupId of the group * @return list of roles * @throws GroupManagementException */ - List getRoles(String groupName) throws GroupManagementException; + List getRoles(int groupId) throws GroupManagementException; /** * Get specific device group sharing roles for user * * @param userName of the user - * @param groupName of the group + * @param groupId of the group * @return list of roles * @throws GroupManagementException */ - List getRoles(String userName, String groupName) throws GroupManagementException; + List getRoles(String userName, int groupId) throws GroupManagementException; /** * Get device group users * - * @param groupName of the group + * @param groupId of the group * @return list of group users * @throws GroupManagementException */ - List getUsers(String groupName) throws GroupManagementException; + List getUsers(int groupId) throws GroupManagementException; /** * Get all devices in device group * - * @param groupName of the group + * @param groupId of the group * @return list of group devices * @throws GroupManagementException */ - List getDevices(String groupName) throws GroupManagementException; + List getDevices(int groupId) throws GroupManagementException; /** * Get all devices in device group * - * @param groupName of the group + * @param groupId of the group * @param request PaginationRequest object holding the data for pagination * @return list of group devices * @throws GroupManagementException */ - PaginationResult getDevices(String groupName, PaginationRequest request) throws GroupManagementException; + PaginationResult getDevices(int groupId, PaginationRequest request) throws GroupManagementException; /** * This method is used to retrieve the device count of a given group. * - * @param groupName Name of the group + * @param groupId Name of the group * @return returns the device count. * @throws GroupManagementException */ - int getDeviceCount(String groupName) throws GroupManagementException; + int getDeviceCount(int groupId) throws GroupManagementException; /** * Add device to device group * * @param deviceId of the device - * @param groupName of the group + * @param groupId of the group * @return is device added * @throws GroupManagementException */ - boolean addDevice(DeviceIdentifier deviceId, String groupName) throws GroupManagementException; + boolean addDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException; /** * Remove device from device group * * @param deviceId of the device - * @param groupName of the group + * @param groupId of the group * @return is device removed * @throws GroupManagementException */ - boolean removeDevice(DeviceIdentifier deviceId, String groupName) throws GroupManagementException; + boolean removeDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException; /** * Get device group permissions of user * * @param username of the user - * @param groupName of the group + * @param groupId of the group * @return array of permissions * @throws GroupManagementException */ - String[] getPermissions(String username, String groupName) throws GroupManagementException; + String[] getPermissions(String username, int groupId) throws GroupManagementException; /** * Get device groups of user with permission @@ -245,11 +245,11 @@ public interface GroupManagementServiceProvider { * Check user is authorized for specific permission of device group * * @param username of the user - * @param groupName to authorize + * @param groupId to authorize * @param permission to authorize * @return is user authorized for permission * @throws GroupManagementException */ - boolean isAuthorized(String username, String groupName, String permission) throws GroupManagementException; + boolean isAuthorized(String username, int groupId, String permission) throws GroupManagementException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProviderImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java similarity index 73% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProviderImpl.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index 2923ee944a..f5e57c1ae4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProviderImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -22,7 +22,12 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; 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.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; @@ -38,18 +43,21 @@ import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.util.UserCoreUtil; import java.sql.SQLException; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; -public class GroupManagementServiceProviderImpl implements GroupManagementServiceProvider { +public class GroupManagementProviderServiceImpl implements GroupManagementProviderService { - private static Log log = LogFactory.getLog(GroupManagementServiceProviderImpl.class); + private static Log log = LogFactory.getLog(GroupManagementProviderServiceImpl.class); private GroupDAO groupDAO; /** * Set groupDAO from GroupManagementDAOFactory when class instantiate. */ - public GroupManagementServiceProviderImpl() { + public GroupManagementProviderServiceImpl() { this.groupDAO = GroupManagementDAOFactory.getGroupDAO(); } @@ -71,6 +79,10 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic if (!nameIsExists) { groupId = this.groupDAO.addGroup(groupBroker, tenantId); GroupManagementDAOFactory.commitTransaction(); + if (groupId < 0) { + return -1; + } + groupBroker.setId(groupId); } else { return -2; } @@ -83,10 +95,8 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic } finally { GroupManagementDAOFactory.closeConnection(); } - if (groupId == -1) { - return -1; - } - addGroupSharingRole(groupBroker.getOwner(), deviceGroup.getName(), defaultRole, defaultPermissions); + + addGroupSharingRole(groupBroker.getOwner(), groupId, defaultRole, defaultPermissions); if (log.isDebugEnabled()) { log.debug("DeviceGroup added: " + groupBroker.getName()); } @@ -120,30 +130,22 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic * {@inheritDoc} */ @Override - public boolean deleteGroup(String groupName) throws GroupManagementException { + public boolean deleteGroup(int groupId) throws GroupManagementException { String roleName; - DeviceGroup deviceGroup = getGroup(groupName); + DeviceGroup deviceGroup = getGroup(groupId); if (deviceGroup == null) { return false; } - List groupRoles = getRoles(groupName); + List groupRoles = getRoles(groupId); for (String role : groupRoles) { if (role != null) { - roleName = role.replace("Internal/group-" + groupName + "-", ""); - removeGroupSharingRole(groupName, roleName); - } - } - List groupDevices = getDevices(groupName); - try { - for (Device device : groupDevices) { - DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().modifyEnrollment(device); + roleName = role.replace("Internal/group-" + groupId + "-", ""); + removeGroupSharingRole(groupId, roleName); } - } catch (DeviceManagementException e) { - throw new GroupManagementException("Error occurred while removing device from group.", e); } try { GroupManagementDAOFactory.beginTransaction(); - this.groupDAO.deleteGroup(groupName, CarbonContext.getThreadLocalCarbonContext().getTenantId()); + this.groupDAO.deleteGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId()); GroupManagementDAOFactory.commitTransaction(); if (log.isDebugEnabled()) { log.debug("DeviceGroup " + deviceGroup.getName() + " removed."); @@ -152,7 +154,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.rollbackTransaction(); throw new GroupManagementException("Error occurred while removing group " + - "'" + groupName + "' data.", e); + "'" + groupId + "' data.", e); } catch (TransactionManagementException e) { throw new GroupManagementException("Error occurred while initiating transaction.", e); } finally { @@ -164,21 +166,21 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic * {@inheritDoc} */ @Override - public DeviceGroup getGroup(String groupName) throws GroupManagementException { + public DeviceGroup getGroup(int groupId) throws GroupManagementException { DeviceGroupBuilder groupBroker; try { GroupManagementDAOFactory.openConnection(); - groupBroker = this.groupDAO.getGroup(groupName, CarbonContext.getThreadLocalCarbonContext().getTenantId()); + groupBroker = this.groupDAO.getGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId()); } catch (GroupManagementDAOException e) { - throw new GroupManagementException("Error occurred while obtaining group " + groupName, e); + throw new GroupManagementException("Error occurred while obtaining group " + groupId, e); } catch (SQLException e) { throw new GroupManagementException("Error occurred while opening a connection to the data source.", e); } finally { GroupManagementDAOFactory.closeConnection(); } if (groupBroker != null) { - groupBroker.setUsers(this.getUsers(groupName)); - groupBroker.setRoles(this.getRoles(groupName)); + groupBroker.setUsers(this.getUsers(groupId)); + groupBroker.setRoles(this.getRoles(groupId)); return groupBroker.getGroup(); } else { return null; @@ -189,12 +191,12 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic * {@inheritDoc} */ @Override - public List findGroups(String groupName, String owner) throws GroupManagementException { + public List findInGroups(String groupName, String owner) throws GroupManagementException { List deviceGroups = new ArrayList<>(); try { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); GroupManagementDAOFactory.openConnection(); - deviceGroups = this.groupDAO.getGroups(groupName, tenantId); + deviceGroups = this.groupDAO.findInGroups(groupName, tenantId); } catch (GroupManagementDAOException e) { throw new GroupManagementException("Error occurred while finding group " + groupName, e); } catch (SQLException e) { @@ -204,8 +206,8 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic } List groupsWithData = new ArrayList<>(); for (DeviceGroupBuilder groupBroker : deviceGroups) { - groupBroker.setUsers(this.getUsers(groupBroker.getName())); - groupBroker.setRoles(this.getRoles(groupBroker.getName())); + groupBroker.setUsers(this.getUsers(groupBroker.getId())); + groupBroker.setRoles(this.getRoles(groupBroker.getId())); groupsWithData.add(groupBroker.getGroup()); } return groupsWithData; @@ -222,13 +224,12 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) .getUserStoreManager(); String[] roleList = userStoreManager.getRoleListOfUser(username); - Map groups = new HashMap<>(); + Map groups = new HashMap<>(); for (String role : roleList) { if (role != null && role.contains("Internal/group-")) { - String groupName = role.split("-")[1]; - if (!groups.containsKey(groupName)) { - DeviceGroup deviceGroup = getGroup(groupName); - groups.put(groupName, deviceGroup); + DeviceGroup deviceGroup = extractNewGroupFromRole(groups, role); + if (deviceGroup != null) { + groups.put(deviceGroup.getId(), deviceGroup); } } } @@ -250,66 +251,39 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic * {@inheritDoc} */ @Override - public boolean shareGroup(String username, String groupName, String sharingRole) + public boolean shareGroup(String username, int groupId, String sharingRole) throws GroupManagementException { - return modifyGroupShare(username, groupName, sharingRole, true); + return modifyGroupShare(username, groupId, sharingRole, true); } /** * {@inheritDoc} */ @Override - public boolean unshareGroup(String username, String groupName, String sharingRole) + public boolean unshareGroup(String username, int groupId, String sharingRole) throws GroupManagementException { - return modifyGroupShare(username, groupName, sharingRole, false); - } - - private boolean modifyGroupShare(String username, String groupName, String sharingRole, - boolean isAddNew) - throws GroupManagementException { - UserStoreManager userStoreManager; - String[] roles = new String[1]; - try { - DeviceGroup deviceGroup = getGroup(groupName); - if (deviceGroup == null) { - return false; - } - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - userStoreManager = - DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( - tenantId).getUserStoreManager(); - roles[0] = "Internal/group-" + groupName + "-" + sharingRole; - if (isAddNew) { - userStoreManager.updateRoleListOfUser(username, null, roles); - } else { - userStoreManager.updateRoleListOfUser(username, roles, null); - } - return true; - } catch (UserStoreException e) { - throw new GroupManagementException("User store error in adding user " + username + " to group name:" + - groupName, e); - } + return modifyGroupShare(username, groupId, sharingRole, false); } /** * {@inheritDoc} */ @Override - public boolean addGroupSharingRole(String username, String groupName, String roleName, + public boolean addGroupSharingRole(String username, int groupId, String roleName, String[] permissions) throws GroupManagementException { UserStoreManager userStoreManager; String role; String[] userNames = new String[1]; try { - DeviceGroup deviceGroup = getGroup(groupName); + DeviceGroup deviceGroup = getGroup(groupId); if (deviceGroup == null) { return false; } int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) .getUserStoreManager(); - role = "Internal/group-" + groupName + "-" + roleName; + role = "Internal/group-" + groupId + "-" + roleName; userNames[0] = username; Permission[] carbonPermissions = new Permission[permissions.length]; for (int i = 0; i < permissions.length; i++) { @@ -318,8 +292,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic userStoreManager.addRole(role, userNames, carbonPermissions); return true; } catch (UserStoreException e) { - String errorMsg = "User store error in adding role to group id:" + groupName; - log.error(errorMsg, e); + String errorMsg = "User store error in adding role to group id:" + groupId; throw new GroupManagementException(errorMsg, e); } } @@ -328,23 +301,23 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic * {@inheritDoc} */ @Override - public boolean removeGroupSharingRole(String groupName, String roleName) + public boolean removeGroupSharingRole(int groupId, String roleName) throws GroupManagementException { UserStoreManager userStoreManager; String role; try { - DeviceGroup deviceGroup = getGroup(groupName); + DeviceGroup deviceGroup = getGroup(groupId); if (deviceGroup == null) { return false; } int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) .getUserStoreManager(); - role = "Internal/group-" + groupName + "-" + roleName; + role = "Internal/group-" + groupId + "-" + roleName; userStoreManager.deleteRole(role); return true; } catch (UserStoreException userStoreEx) { - String errorMsg = "User store error in adding role to group id:" + groupName; + String errorMsg = "User store error in adding role to group id:" + groupId; log.error(errorMsg, userStoreEx); throw new GroupManagementException(errorMsg, userStoreEx); } @@ -354,7 +327,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic * {@inheritDoc} */ @Override - public List getRoles(String groupName) throws GroupManagementException { + public List getRoles(int groupId) throws GroupManagementException { UserStoreManager userStoreManager; String[] roles; List groupRoles; @@ -365,13 +338,13 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic roles = userStoreManager.getRoleNames(); groupRoles = new ArrayList<>(); for (String r : roles) { - if (r != null && r.contains("Internal/group-" + groupName + "-")) { - groupRoles.add(r.replace("Internal/group-" + groupName + "-", "")); + if (r != null && r.contains("Internal/group-" + groupId + "-")) { + groupRoles.add(r.replace("Internal/group-" + groupId + "-", "")); } } return groupRoles; } catch (UserStoreException userStoreEx) { - String errorMsg = "User store error in adding role to group id:" + groupName; + String errorMsg = "User store error in adding role to group id:" + groupId; log.error(errorMsg, userStoreEx); throw new GroupManagementException(errorMsg, userStoreEx); } @@ -381,7 +354,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic * {@inheritDoc} */ @Override - public List getRoles(String username, String groupName) throws GroupManagementException { + public List getRoles(String username, int groupId) throws GroupManagementException { UserStoreManager userStoreManager; List groupRoleList = new ArrayList<>(); try { @@ -390,8 +363,8 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic .getUserStoreManager(); String[] roleList = userStoreManager.getRoleListOfUser(username); for (String role : roleList) { - if (role != null && role.contains("Internal/group-" + groupName)) { - String roleName = role.replace("Internal/group-" + groupName + "-", ""); + if (role != null && role.contains("Internal/group-" + groupId)) { + String roleName = role.replace("Internal/group-" + groupId + "-", ""); groupRoleList.add(roleName); } } @@ -405,16 +378,16 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic * {@inheritDoc} */ @Override - public List getUsers(String groupName) throws GroupManagementException { + public List getUsers(int groupId) throws GroupManagementException { UserStoreManager userStoreManager; Map groupUserHashMap = new HashMap<>(); try { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) .getUserStoreManager(); - List rolesForGroup = this.getRoles(groupName); + List rolesForGroup = this.getRoles(groupId); for (String role : rolesForGroup) { - String[] users = userStoreManager.getUserListOfRole("Internal/group-" + groupName + "-" + role); + String[] users = userStoreManager.getUserListOfRole("Internal/group-" + groupId + "-" + role); for (String user : users) { GroupUser groupUser; if (groupUserHashMap.containsKey(user)) { @@ -431,7 +404,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic } return new ArrayList<>(groupUserHashMap.values()); } catch (UserStoreException e) { - String errorMsg = "User store error in fetching user list for group id:" + groupName; + String errorMsg = "User store error in fetching user list for group id:" + groupId; log.error(errorMsg, e); throw new GroupManagementException(errorMsg, e); } @@ -441,53 +414,45 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic * {@inheritDoc} */ @Override - public List getDevices(String groupName) throws GroupManagementException { - return Collections.emptyList(); - //TODO: Add a method that returns a collection of devices in a particular group to GroupDAO -// try { -// return DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevices(groupName); -// } catch (DeviceManagementException e) { -// throw new GroupManagementException("Error occurred while getting devices in group.", e); -// } + public List getDevices(int groupId) throws GroupManagementException { + try { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + return this.groupDAO.getDevices(groupId, tenantId); + } catch (GroupManagementDAOException e) { + throw new GroupManagementException("Error occurred while getting devices in group.", e); + } } /** * {@inheritDoc} */ @Override - public PaginationResult getDevices(String groupName, PaginationRequest request) + public PaginationResult getDevices(int groupId, PaginationRequest request) throws GroupManagementException { - return null; - //TODO: Add a method that returns a collection of devices in a particular group to GroupDAO -// try { -// return DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevices(groupName); -// } catch (DeviceManagementException e) { -// throw new GroupManagementException("Error occurred while getting devices in group.", e); -// } -// try { -// return DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevices(groupName, -// request); -// } catch (DeviceManagementException e) { -// throw new GroupManagementException("Error occurred while getting devices in group.", e); -// } + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + return this.groupDAO.getDevices(groupId, request, tenantId); + } catch (GroupManagementDAOException e) { + throw new GroupManagementException("Error occurred while getting devices in group.", e); + } } /** * {@inheritDoc} */ @Override - public int getDeviceCount(String groupName) throws GroupManagementException { + public int getDeviceCount(int groupId) throws GroupManagementException { try { int count; GroupManagementDAOFactory.beginTransaction(); - count = groupDAO.getDeviceCount(groupName, - CarbonContext.getThreadLocalCarbonContext().getTenantId()); + count = groupDAO.getDeviceCount(groupId, + CarbonContext.getThreadLocalCarbonContext().getTenantId()); GroupManagementDAOFactory.commitTransaction(); return count; } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.rollbackTransaction(); throw new GroupManagementException("Error occurred while retrieving device count of group " + - "'" + groupName + "'.", e); + "'" + groupId + "'.", e); } catch (TransactionManagementException e) { throw new GroupManagementException("Error occurred while initiating transaction.", e); } finally { @@ -499,19 +464,22 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic * {@inheritDoc} */ @Override - public boolean addDevice(DeviceIdentifier deviceId, String groupName) + public boolean addDevice(DeviceIdentifier deviceIdentifier, int groupId) throws GroupManagementException { Device device; DeviceGroup deviceGroup; try { - device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId); - deviceGroup = this.getGroup(groupName); + device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier); + deviceGroup = this.getGroup(groupId); if (device == null || deviceGroup == null) { return false; } - DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().modifyEnrollment(device); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + this.groupDAO.addDevice(groupId, device.getId(), tenantId); } catch (DeviceManagementException e) { - throw new GroupManagementException("Error occurred while adding device in to deviceGroup.", e); + throw new GroupManagementException("Error occurred while retrieving device.", e); + } catch (GroupManagementDAOException e) { + throw new GroupManagementException("Error occurred while adding device to group '" + groupId + "'.", e); } return true; } @@ -520,19 +488,22 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic * {@inheritDoc} */ @Override - public boolean removeDevice(DeviceIdentifier deviceId, String groupName) + public boolean removeDevice(DeviceIdentifier deviceIdentifier, int groupId) throws GroupManagementException { Device device; DeviceGroup deviceGroup; try { - device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId); - deviceGroup = this.getGroup(groupName); + device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier); + deviceGroup = this.getGroup(groupId); if (device == null || deviceGroup == null) { return false; } - DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().modifyEnrollment(device); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + this.groupDAO.removeDevice(groupId, device.getId(), tenantId); } catch (DeviceManagementException e) { - throw new GroupManagementException("Error occurred while removing device from deviceGroup.", e); + throw new GroupManagementException("Error occurred while retrieving device.", e); + } catch (GroupManagementDAOException e) { + throw new GroupManagementException("Error occurred while adding device to group '" + groupId + "'.", e); } return true; } @@ -541,9 +512,9 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic * {@inheritDoc} */ @Override - public String[] getPermissions(String username, String groupName) throws GroupManagementException { + public String[] getPermissions(String username, int groupId) throws GroupManagementException { UserRealm userRealm; - List roles = getRoles(username, groupName); + List roles = getRoles(username, groupId); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); try { userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); @@ -553,8 +524,8 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic for (String resourceId : resourceIds) { for (String roleName : roles) { if (userRealm.getAuthorizationManager(). - isRoleAuthorized("Internal/group-" + groupName + "-" + roleName, resourceId, - CarbonConstants.UI_PERMISSION_ACTION)) { + isRoleAuthorized("Internal/group-" + groupId + "-" + roleName, resourceId, + CarbonConstants.UI_PERMISSION_ACTION)) { lstPermissions.add(resourceId); } } @@ -575,17 +546,16 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic throws GroupManagementException { UserRealm userRealm; int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - Map groups = new HashMap<>(); + Map groups = new HashMap<>(); try { userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); String[] roles = userRealm.getUserStoreManager().getRoleListOfUser(username); for (String role : roles) { if (role != null && role.contains("Internal/group-") && userRealm.getAuthorizationManager() .isRoleAuthorized(role, permission, CarbonConstants.UI_PERMISSION_ACTION)) { - String groupName = role.split("-")[1]; - if (!groups.containsKey(groupName)) { - DeviceGroup deviceGroup = getGroup(groupName); - groups.put(groupName, deviceGroup); + DeviceGroup deviceGroup = extractNewGroupFromRole(groups, role); + if (deviceGroup != null) { + groups.put(deviceGroup.getId(), deviceGroup); } } } @@ -599,17 +569,17 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic * {@inheritDoc} */ @Override - public boolean isAuthorized(String username, String groupName, String permission) + public boolean isAuthorized(String username, int groupId, String permission) throws GroupManagementException { UserRealm userRealm; int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); try { userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); - List roles = this.getRoles(username, groupName); + List roles = this.getRoles(username, groupId); for (String role : roles) { if (userRealm.getAuthorizationManager() - .isRoleAuthorized("Internal/group-" + groupName + "-" + role, permission, - CarbonConstants.UI_PERMISSION_ACTION)) { + .isRoleAuthorized("Internal/group-" + groupId + "-" + role, permission, + CarbonConstants.UI_PERMISSION_ACTION)) { return true; } } @@ -619,4 +589,44 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic } } + private boolean modifyGroupShare(String username, int groupId, String sharingRole, + boolean isAddNew) + throws GroupManagementException { + UserStoreManager userStoreManager; + String[] roles = new String[1]; + try { + DeviceGroup deviceGroup = getGroup(groupId); + if (deviceGroup == null) { + return false; + } + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + userStoreManager = + DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( + tenantId).getUserStoreManager(); + roles[0] = "Internal/group-" + groupId + "-" + sharingRole; + if (isAddNew) { + userStoreManager.updateRoleListOfUser(username, null, roles); + } else { + userStoreManager.updateRoleListOfUser(username, roles, null); + } + return true; + } catch (UserStoreException e) { + throw new GroupManagementException("User store error in adding user " + username + " to group name:" + + groupId, e); + } + } + + private DeviceGroup extractNewGroupFromRole(Map groups, String role) + throws GroupManagementException { + try { + int groupId = Integer.parseInt(role.split("-")[1]); + if (!groups.containsKey(groupId)) { + return getGroup(groupId); + } + } catch (NumberFormatException e) { + log.error("Unable to extract groupId from role " + role, e); + } + return null; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java index a270659ca3..5405338116 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java @@ -31,6 +31,7 @@ import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.TestUtils; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import javax.sql.DataSource; @@ -58,6 +59,7 @@ public abstract class BaseDeviceManagementTest { public void initDataSource() throws Exception { this.dataSource = this.getDataSource(this.readDataSourceConfig()); DeviceManagementDAOFactory.init(dataSource); + GroupManagementDAOFactory.init(dataSource); } @BeforeClass @@ -135,6 +137,7 @@ public abstract class BaseDeviceManagementTest { // this.cleanApplicationData(conn); // this.cleanupDeviceData(conn); // this.cleanupDeviceTypeData(conn); + this.cleanupGroupData(conn); conn.commit(); } catch (SQLException e) { @@ -190,6 +193,12 @@ public abstract class BaseDeviceManagementTest { } } + private void cleanupGroupData(Connection conn) throws SQLException { + try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_GROUP")) { + stmt.execute(); + } + } + public DataSource getDataSource() { return dataSource; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java index 1d381abf1e..423fc6666e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java @@ -18,7 +18,9 @@ package org.wso2.carbon.device.mgt.core.common; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.app.mgt.Application; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import java.util.Date; import java.util.Properties; @@ -30,6 +32,7 @@ public class TestDataHolder { public static String TEST_DEVICE_TYPE = "Test"; public static Integer SUPER_TENANT_ID = -1234; public static String initialDeviceIdentifier = "12345"; + public static String OWNER = "admin"; public static Device generateDummyDeviceData(String deviceType){ @@ -37,12 +40,12 @@ public class TestDataHolder { EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); enrolmentInfo.setDateOfEnrolment(new Date().getTime()); enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); - enrolmentInfo.setOwner("admin"); + enrolmentInfo.setOwner(OWNER); enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED); device.setEnrolmentInfo(enrolmentInfo); device.setDescription("Test Description"); - device.setDeviceIdentifier("12345"); + device.setDeviceIdentifier(initialDeviceIdentifier); device.setType(deviceType); return device; } @@ -70,4 +73,15 @@ public class TestDataHolder { return application; } + + public static DeviceGroup generateDummyGroupData() { + DeviceGroup deviceGroup = new DeviceGroup(); + deviceGroup.setName("Test device group"); + deviceGroup.setDescription("Test description"); + deviceGroup.setDateOfCreation(new Date().getTime()); + deviceGroup.setDateOfLastUpdate(new Date().getTime()); + deviceGroup.setOwner(OWNER); + DeviceGroupBuilder broker = new DeviceGroupBuilder(deviceGroup); + return broker.getGroup(); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java new file mode 100644 index 0000000000..30fbae49e4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2016, 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.TransactionManagementException; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; +import org.wso2.carbon.device.mgt.core.common.TestDataHolder; +import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; +import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupDAO; +import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOException; +import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory; + +import java.sql.SQLException; +import java.util.Date; +import java.util.List; + +public class GroupPersistTests extends BaseDeviceManagementTest { + + private static final Log log = LogFactory.getLog(GroupPersistTests.class); + GroupDAO groupDAO = GroupManagementDAOFactory.getGroupDAO(); + int groupId = -1; + + @BeforeClass + @Override + public void init() { + try { + initDataSource(); + } catch (Exception e) { + String msg = "Error occurred while initializing data source."; + log.error(msg, e); + Assert.fail(msg, e); + } + } + + @Test + public void testAddGroupTest() { + DeviceGroup deviceGroup = TestDataHolder.generateDummyGroupData(); + try { + GroupManagementDAOFactory.beginTransaction(); + groupId = groupDAO.addGroup(deviceGroup, TestDataHolder.SUPER_TENANT_ID); + GroupManagementDAOFactory.commitTransaction(); + log.debug("Group added to database."); + } catch (GroupManagementDAOException e) { + GroupManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while adding device type '" + deviceGroup.getName() + "'."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + + DeviceGroup group = getGroupById(groupId); + Assert.assertNotNull(group, "Group is null"); + log.debug("Group name: " + group.getName()); + } + + public DeviceGroup getGroupById(int groupId) { + try { + GroupManagementDAOFactory.openConnection(); + return groupDAO.getGroup(groupId, TestDataHolder.SUPER_TENANT_ID); + } catch (GroupManagementDAOException e) { + String msg = "Error occurred while retrieving group details."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the data source."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + return null; + } + + @Test(dependsOnMethods = {"testAddGroupTest"}) + public void updateGroupTest() { + long time = new Date().getTime(); + String name = "Test Updated"; + String desc = "Desc updated"; + DeviceGroup group = getGroupById(groupId); + Assert.assertNotNull(group, "Group is null"); + group.setDateOfLastUpdate(time); + group.setName(name); + group.setDescription(desc); + try { + GroupManagementDAOFactory.beginTransaction(); + groupDAO.updateGroup(group, TestDataHolder.SUPER_TENANT_ID); + GroupManagementDAOFactory.commitTransaction(); + log.debug("Group updated"); + } catch (GroupManagementDAOException e) { + GroupManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while updating group details."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + + group = getGroupById(group.getId()); + Assert.assertNotNull(group, "Group is null"); + Assert.assertEquals(group.getName(), name, "Group name"); + Assert.assertEquals(group.getDescription(), desc, "Group description"); + Assert.assertEquals((long) group.getDateOfLastUpdate(), time, "Update time"); + } + + @Test(dependsOnMethods = {"testAddGroupTest"}) + public void findGroupTest() { + try { + GroupManagementDAOFactory.openConnection(); + List groups = groupDAO.findInGroups("Test", TestDataHolder.SUPER_TENANT_ID); + Assert.assertNotEquals(groups.size(), 0, "No groups found"); + Assert.assertNotNull(groups.get(0), "Group is null"); + log.debug("Group found: " + groups.get(0).getName()); + } catch (GroupManagementDAOException e) { + String msg = "Error occurred while find group by name."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the data source."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = {"testAddGroupTest"}) + public void getGroupTest() { + try { + GroupManagementDAOFactory.openConnection(); + List groups = groupDAO.getGroups(TestDataHolder.SUPER_TENANT_ID); + Assert.assertNotEquals(groups.size(), 0, "No groups found"); + Assert.assertNotNull(groups.get(0), "Group is null"); + log.debug("No of Groups found: " + groups.size()); + } catch (GroupManagementDAOException e) { + String msg = "Error occurred while find group by name."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the data source."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = {"updateGroupTest"}) + public void deleteGroupTest() { + DeviceGroup group = getGroupById(groupId); + int groupId = 0; + try { + Assert.assertNotNull(group, "Group is null"); + groupId = group.getId(); + GroupManagementDAOFactory.beginTransaction(); + groupDAO.deleteGroup(groupId, TestDataHolder.SUPER_TENANT_ID); + GroupManagementDAOFactory.commitTransaction(); + log.debug("Group deleted"); + } catch (GroupManagementDAOException e) { + GroupManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while updating group details."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + group = getGroupById(groupId); + Assert.assertNull(group, "Group not deleted"); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index d172e2f5d2..c80cf3d00a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -1,378 +1,378 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( - ID INT auto_increment NOT NULL, - NAME VARCHAR(300) DEFAULT NULL, - PRIMARY KEY (ID) + ID INT AUTO_INCREMENT NOT NULL, + NAME VARCHAR(300) DEFAULT NULL, + PRIMARY KEY (ID) +); + +CREATE TABLE IF NOT EXISTS DM_GROUP ( + ID INTEGER AUTO_INCREMENT NOT NULL, + GROUP_NAME VARCHAR(100) DEFAULT NULL, + DESCRIPTION TEXT DEFAULT NULL, + DATE_OF_CREATE BIGINT DEFAULT NULL, + DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL, + OWNER VARCHAR(45) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( - ID INTEGER auto_increment NOT NULL, - SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, - CERTIFICATE BLOB DEFAULT NULL, - PRIMARY KEY (ID) + ID INTEGER AUTO_INCREMENT NOT NULL, + SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, + CERTIFICATE BLOB DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS DM_DEVICE ( - ID INTEGER auto_increment NOT NULL, - DESCRIPTION TEXT DEFAULT NULL, - NAME VARCHAR(100) DEFAULT NULL, - DEVICE_TYPE_ID INT(11) DEFAULT NULL, - DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (ID), - CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + ID INTEGER AUTO_INCREMENT NOT NULL, + DESCRIPTION TEXT DEFAULT NULL, + NAME VARCHAR(100) DEFAULT NULL, + DEVICE_TYPE_ID INT(11) DEFAULT NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID), + CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID) + REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); + +CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER DEFAULT NULL, + GROUP_ID INTEGER DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID), + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) + REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_OPERATION ( - ID INTEGER AUTO_INCREMENT NOT NULL, - TYPE VARCHAR(50) NOT NULL, - CREATED_TIMESTAMP TIMESTAMP NOT NULL, - RECEIVED_TIMESTAMP TIMESTAMP NULL, - OPERATION_CODE VARCHAR(1000) NOT NULL, - PRIMARY KEY (ID) + ID INTEGER AUTO_INCREMENT NOT NULL, + TYPE VARCHAR(50) NOT NULL, + CREATED_TIMESTAMP TIMESTAMP NOT NULL, + RECEIVED_TIMESTAMP TIMESTAMP NULL, + OPERATION_CODE VARCHAR(1000) NOT NULL, + PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS DM_CONFIG_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - OPERATION_CONFIG BLOB DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_config FOREIGN KEY (OPERATION_ID) REFERENCES + OPERATION_ID INTEGER NOT NULL, + OPERATION_CONFIG BLOB DEFAULT NULL, + PRIMARY KEY (OPERATION_ID), + CONSTRAINT fk_dm_operation_config FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_COMMAND_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_command FOREIGN KEY (OPERATION_ID) REFERENCES + OPERATION_ID INTEGER NOT NULL, + ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY (OPERATION_ID), + CONSTRAINT fk_dm_operation_command FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_POLICY_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED INTEGER NOT NULL DEFAULT 0, - OPERATION_DETAILS BLOB DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_policy FOREIGN KEY (OPERATION_ID) REFERENCES + OPERATION_ID INTEGER NOT NULL, + ENABLED INTEGER NOT NULL DEFAULT 0, + OPERATION_DETAILS BLOB DEFAULT NULL, + PRIMARY KEY (OPERATION_ID), + CONSTRAINT fk_dm_operation_policy FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_PROFILE_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED INTEGER NOT NULL DEFAULT 0, - OPERATION_DETAILS BLOB DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_profile FOREIGN KEY (OPERATION_ID) REFERENCES + OPERATION_ID INTEGER NOT NULL, + ENABLED INTEGER NOT NULL DEFAULT 0, + OPERATION_DETAILS BLOB DEFAULT NULL, + PRIMARY KEY (OPERATION_ID), + CONSTRAINT fk_dm_operation_profile FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); 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) DEFAULT NULL, - STATUS VARCHAR(50) NULL, - DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, - DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, - TENANT_ID INT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OWNER VARCHAR(50) NOT NULL, + OWNERSHIP VARCHAR(45) DEFAULT NULL, + STATUS VARCHAR(50) NULL, + DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, + DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, + TENANT_ID INT NOT NULL, + PRIMARY KEY (ID), + 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_ENROLMENT_OP_MAPPING ( - ID INTEGER AUTO_INCREMENT NOT NULL, - ENROLMENT_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NOT NULL, - STATUS VARCHAR(50) NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES + ID INTEGER AUTO_INCREMENT NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + STATUS VARCHAR(50) NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_device_operation_mapping_operation FOREIGN KEY (OPERATION_ID) REFERENCES + CONSTRAINT fk_dm_device_operation_mapping_operation FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( - ID INTEGER AUTO_INCREMENT NOT NULL, - ENROLMENT_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NOT NULL, - OPERATION_RESPONSE BLOB DEFAULT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES + ID INTEGER AUTO_INCREMENT NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + OPERATION_RESPONSE BLOB DEFAULT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES + CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); -- POLICY RELATED TABLES -- -CREATE TABLE IF NOT EXISTS DM_PROFILE ( - ID INT NOT NULL AUTO_INCREMENT , - PROFILE_NAME VARCHAR(45) NOT NULL , - TENANT_ID INT NOT NULL , - DEVICE_TYPE_ID INT NOT NULL , - CREATED_TIME DATETIME NOT NULL , - UPDATED_TIME DATETIME NOT NULL , - PRIMARY KEY (ID) , +CREATE TABLE IF NOT EXISTS DM_PROFILE ( + ID INT NOT NULL AUTO_INCREMENT, + PROFILE_NAME VARCHAR(45) NOT NULL, + TENANT_ID INT NOT NULL, + DEVICE_TYPE_ID INT NOT NULL, + CREATED_TIME DATETIME NOT NULL, + UPDATED_TIME DATETIME NOT NULL, + PRIMARY KEY (ID), CONSTRAINT DM_PROFILE_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - - - - - -CREATE TABLE IF NOT EXISTS DM_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - NAME VARCHAR(45) DEFAULT NULL , - DESCRIPTION VARCHAR(1000) NULL, - TENANT_ID INT(11) NOT NULL , - PROFILE_ID INT(11) NOT NULL , - OWNERSHIP_TYPE VARCHAR(45) NULL, - COMPLIANCE VARCHAR(100) NULL, - PRIORITY INT NOT NULL, - ACTIVE INT(2) NOT NULL, - UPDATED INT(1) NULL, - PRIMARY KEY (ID) , + FOREIGN KEY (DEVICE_TYPE_ID) + REFERENCES DM_DEVICE_TYPE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + +CREATE TABLE IF NOT EXISTS DM_POLICY ( + ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(45) DEFAULT NULL, + DESCRIPTION VARCHAR(1000) NULL, + TENANT_ID INT(11) NOT NULL, + PROFILE_ID INT(11) NOT NULL, + OWNERSHIP_TYPE VARCHAR(45) NULL, + COMPLIANCE VARCHAR(100) NULL, + PRIORITY INT NOT NULL, + ACTIVE INT(2) NOT NULL, + UPDATED INT(1) NULL, + PRIMARY KEY (ID), CONSTRAINT FK_DM_PROFILE_DM_POLICY - FOREIGN KEY (PROFILE_ID ) - REFERENCES DM_PROFILE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (PROFILE_ID) + REFERENCES DM_PROFILE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - - - -CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - DEVICE_ID INT(11) NOT NULL , +CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( + ID INT(11) NOT NULL AUTO_INCREMENT, + DEVICE_ID INT(11) NOT NULL, ENROLMENT_ID INT(11) NOT NULL, - DEVICE BLOB NOT NULL, - POLICY_ID INT(11) NOT NULL , - PRIMARY KEY (ID) , + DEVICE BLOB NOT NULL, + POLICY_ID INT(11) NOT NULL, + PRIMARY KEY (ID), CONSTRAINT FK_POLICY_DEVICE_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION, + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, CONSTRAINT FK_DEVICE_DEVICE_POLICY - FOREIGN KEY (DEVICE_ID ) - REFERENCES DM_DEVICE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - - - -CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( - ID INT(11) NOT NULL , - DEVICE_TYPE_ID INT(11) NOT NULL , - POLICY_ID INT(11) NOT NULL , - PRIMARY KEY (ID) , +CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( + ID INT(11) NOT NULL, + DEVICE_TYPE_ID INT(11) NOT NULL, + POLICY_ID INT(11) NOT NULL, + PRIMARY KEY (ID), CONSTRAINT FK_DEVICE_TYPE_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION, + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - - - - - -CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( - ID INT(11) NOT NULL AUTO_INCREMENT, - PROFILE_ID INT(11) NOT NULL, - FEATURE_CODE VARCHAR(30) NOT NULL, - DEVICE_TYPE_ID INT NOT NULL, - TENANT_ID INT(11) NOT NULL , - CONTENT BLOB NULL DEFAULT NULL, + FOREIGN KEY (DEVICE_TYPE_ID) + REFERENCES DM_DEVICE_TYPE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + +CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( + ID INT(11) NOT NULL AUTO_INCREMENT, + PROFILE_ID INT(11) NOT NULL, + FEATURE_CODE VARCHAR(30) NOT NULL, + DEVICE_TYPE_ID INT NOT NULL, + TENANT_ID INT(11) NOT NULL, + CONTENT BLOB NULL DEFAULT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES - FOREIGN KEY (PROFILE_ID) - REFERENCES DM_PROFILE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (PROFILE_ID) + REFERENCES DM_PROFILE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - - - -CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - ROLE_NAME VARCHAR(45) NOT NULL , - POLICY_ID INT(11) NOT NULL , - PRIMARY KEY (ID) , +CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( + ID INT(11) NOT NULL AUTO_INCREMENT, + ROLE_NAME VARCHAR(45) NOT NULL, + POLICY_ID INT(11) NOT NULL, + PRIMARY KEY (ID), CONSTRAINT FK_ROLE_POLICY_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - - - -CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( - ID INT NOT NULL AUTO_INCREMENT , - POLICY_ID INT NOT NULL , - USERNAME VARCHAR(45) NOT NULL , - PRIMARY KEY (ID) , +CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( + ID INT NOT NULL AUTO_INCREMENT, + POLICY_ID INT NOT NULL, + USERNAME VARCHAR(45) NOT NULL, + PRIMARY KEY (ID), CONSTRAINT DM_POLICY_USER_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - - - CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( - ID INT NOT NULL AUTO_INCREMENT , - DEVICE_ID INT NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, - POLICY_ID INT NOT NULL , - POLICY_CONTENT BLOB NULL , - TENANT_ID INT NOT NULL, - APPLIED TINYINT(1) NULL , - CREATED_TIME TIMESTAMP NULL , - UPDATED_TIME TIMESTAMP NULL , - APPLIED_TIME TIMESTAMP NULL , - PRIMARY KEY (ID) , - CONSTRAINT FK_DM_POLICY_DEVCIE_APPLIED - FOREIGN KEY (DEVICE_ID ) - REFERENCES DM_DEVICE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + +CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + ENROLMENT_ID INT(11) NOT NULL, + POLICY_ID INT NOT NULL, + POLICY_CONTENT BLOB NULL, + TENANT_ID INT NOT NULL, + APPLIED BOOLEAN NULL, + CREATED_TIME TIMESTAMP NULL, + UPDATED_TIME TIMESTAMP NULL, + APPLIED_TIME TIMESTAMP NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_POLICY_DEVICE_APPLIED + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - - CREATE TABLE IF NOT EXISTS DM_CRITERIA ( - ID INT NOT NULL AUTO_INCREMENT, - TENANT_ID INT NOT NULL, - NAME VARCHAR(50) NULL, + ID INT NOT NULL AUTO_INCREMENT, + TENANT_ID INT NOT NULL, + NAME VARCHAR(50) NULL, PRIMARY KEY (ID) ); - - CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA ( - ID INT NOT NULL AUTO_INCREMENT, + ID INT NOT NULL AUTO_INCREMENT, CRITERIA_ID INT NOT NULL, - POLICY_ID INT NOT NULL, + POLICY_ID INT NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_CRITERIA_POLICY_CRITERIA - FOREIGN KEY (CRITERIA_ID) - REFERENCES DM_CRITERIA (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, + FOREIGN KEY (CRITERIA_ID) + REFERENCES DM_CRITERIA (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, CONSTRAINT FK_POLICY_POLICY_CRITERIA - FOREIGN KEY (POLICY_ID) - REFERENCES DM_POLICY (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( - ID INT NOT NULL AUTO_INCREMENT, - POLICY_CRITERION_ID INT NOT NULL, - PROP_KEY VARCHAR(45) NULL, - PROP_VALUE VARCHAR(100) NULL, - CONTENT BLOB NULL COMMENT 'This is used to ', + ID INT NOT NULL AUTO_INCREMENT, + POLICY_CRITERION_ID INT NOT NULL, + PROP_KEY VARCHAR(45) NULL, + PROP_VALUE VARCHAR(100) NULL, + CONTENT BLOB NULL + COMMENT 'This is used to ', PRIMARY KEY (ID), CONSTRAINT FK_POLICY_CRITERIA_PROPERTIES - FOREIGN KEY (POLICY_CRITERION_ID) - REFERENCES DM_POLICY_CRITERIA (ID) - ON DELETE CASCADE - ON UPDATE NO ACTION + FOREIGN KEY (POLICY_CRITERION_ID) + REFERENCES DM_POLICY_CRITERIA (ID) + ON DELETE CASCADE + ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( - ID INT NOT NULL AUTO_INCREMENT, - DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT(11) NOT NULL, - POLICY_ID INT NOT NULL, - TENANT_ID INT NOT NULL, - STATUS INT NULL, - LAST_SUCCESS_TIME TIMESTAMP NULL, + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + ENROLMENT_ID INT(11) NOT NULL, + POLICY_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + STATUS INT NULL, + LAST_SUCCESS_TIME TIMESTAMP NULL, LAST_REQUESTED_TIME TIMESTAMP NULL, - LAST_FAILED_TIME TIMESTAMP NULL, - ATTEMPTS INT NULL, + LAST_FAILED_TIME TIMESTAMP NULL, + ATTEMPTS INT NULL, PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( - ID INT NOT NULL AUTO_INCREMENT, - POLICY_ID INT NOT NULL, - DEVICE_TYPE_ID INT NOT NULL, - TENANT_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT, + POLICY_ID INT NOT NULL, + DEVICE_TYPE_ID INT NOT NULL, + TENANT_ID INT(11) NOT NULL, PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( - ID INT NOT NULL AUTO_INCREMENT, - COMPLIANCE_STATUS_ID INT NOT NULL, - TENANT_ID INT NOT NULL, - FEATURE_CODE VARCHAR(15) NOT NULL, - STATUS INT NULL, + ID INT NOT NULL AUTO_INCREMENT, + COMPLIANCE_STATUS_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + FEATURE_CODE VARCHAR(15) NOT NULL, + STATUS INT NULL, PRIMARY KEY (ID), CONSTRAINT FK_COMPLIANCE_FEATURES_STATUS - FOREIGN KEY (COMPLIANCE_STATUS_ID) - REFERENCES DM_POLICY_COMPLIANCE_STATUS (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (COMPLIANCE_STATUS_ID) + REFERENCES DM_POLICY_COMPLIANCE_STATUS (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); 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) DEFAULT NULL, - STATUS VARCHAR(50) NULL, - DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, - DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, - TENANT_ID INT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OWNER VARCHAR(50) NOT NULL, + OWNERSHIP VARCHAR(45) DEFAULT NULL, + STATUS VARCHAR(50) NULL, + DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, + DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, + TENANT_ID INT NOT NULL, + PRIMARY KEY (ID), + 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(150) NOT NULL, - APP_IDENTIFIER VARCHAR(150) NOT NULL, - PLATFORM VARCHAR(50) DEFAULT NULL, - CATEGORY VARCHAR(50) NULL, - VERSION VARCHAR(50) NULL, - TYPE VARCHAR(50) NULL, - LOCATION_URL VARCHAR(100) DEFAULT NULL, - IMAGE_URL VARCHAR(100) DEFAULT NULL, - APP_PROPERTIES BLOB NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID) + ID INTEGER AUTO_INCREMENT NOT NULL, + NAME VARCHAR(150) NOT NULL, + APP_IDENTIFIER VARCHAR(150) NOT NULL, + PLATFORM VARCHAR(50) DEFAULT NULL, + CATEGORY VARCHAR(50) NULL, + VERSION VARCHAR(50) NULL, + TYPE VARCHAR(50) NULL, + LOCATION_URL VARCHAR(100) DEFAULT NULL, + IMAGE_URL VARCHAR(100) DEFAULT NULL, + APP_PROPERTIES BLOB 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 + 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 + CONSTRAINT fk_dm_application FOREIGN KEY (APPLICATION_ID) REFERENCES DM_APPLICATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); @@ -380,16 +380,16 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING ( -- NOTIFICATION TABLE -- CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( - NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - STATUS VARCHAR(10) NULL, - DESCRIPTION VARCHAR(100) NULL, - PRIMARY KEY (NOTIFICATION_ID), - CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES + NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + STATUS VARCHAR(10) NULL, + DESCRIPTION VARCHAR(100) NULL, + PRIMARY KEY (NOTIFICATION_ID), + CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_operation_notification FOREIGN KEY (OPERATION_ID) REFERENCES + CONSTRAINT fk_dm_operation_notification FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); -- NOTIFICATION TABLE END -- @@ -397,67 +397,64 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( DROP TABLE IF EXISTS DM_DEVICE_INFO; CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( - ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INT NULL, - KEY_FIELD VARCHAR(45) NULL, - VALUE_FIELD VARCHAR(100) NULL, + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, + KEY_FIELD VARCHAR(45) NULL, + VALUE_FIELD VARCHAR(100) NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_INFO_DEVICE - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - - DROP TABLE IF EXISTS DM_DEVICE_LOCATION; CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( - ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INT NULL, - LATITUDE DOUBLE NULL, - LONGITUDE DOUBLE NULL, - STREET1 VARCHAR(45) NULL, - STREET2 VARCHAR(45) NULL, - CITY VARCHAR(45) NULL, - ZIP VARCHAR(10) NULL, - STATE VARCHAR(45) NULL, - COUNTRY VARCHAR(45) NULL, + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, + LATITUDE DOUBLE NULL, + LONGITUDE DOUBLE NULL, + STREET1 VARCHAR(45) NULL, + STREET2 VARCHAR(45) NULL, + CITY VARCHAR(45) NULL, + ZIP VARCHAR(10) NULL, + STATE VARCHAR(45) NULL, + COUNTRY VARCHAR(45) NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_LOCATION_DEVICE - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( - ID INT NOT NULL AUTO_INCREMENT, - DEVICE_ID INT NOT NULL, - IMEI VARCHAR(100) NULL, - IMSI VARCHAR(100) NULL, - DEVICE_MODEL VARCHAR(45) NULL, - VENDOR VARCHAR(45) NULL, - OS_VERSION VARCHAR(45) NULL, - BATTERY_LEVEL DECIMAL(4) NULL, - INTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - INTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - EXTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - EXTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - OPERATOR VARCHAR(45) NULL, - CONNECTION_TYPE VARCHAR(10) NULL, - MOBILE_SIGNAL_STRENGTH DECIMAL(5) NULL, - SSID VARCHAR(45) NULL, - CPU_USAGE DECIMAL(5) NULL, - TOTAL_RAM_MEMORY DECIMAL(5) NULL, - AVAILABLE_RAM_MEMORY DECIMAL(5) NULL, - PLUGGED_IN INT(1) NULL, + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + IMEI VARCHAR(100) NULL, + IMSI VARCHAR(100) NULL, + DEVICE_MODEL VARCHAR(45) NULL, + VENDOR VARCHAR(45) NULL, + OS_VERSION VARCHAR(45) NULL, + BATTERY_LEVEL DECIMAL(4) NULL, + INTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, + INTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, + EXTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, + EXTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, + OPERATOR VARCHAR(45) NULL, + CONNECTION_TYPE VARCHAR(10) NULL, + MOBILE_SIGNAL_STRENGTH DECIMAL(5) NULL, + SSID VARCHAR(45) NULL, + CPU_USAGE DECIMAL(5) NULL, + TOTAL_RAM_MEMORY DECIMAL(5) NULL, + AVAILABLE_RAM_MEMORY DECIMAL(5) NULL, + PLUGGED_IN INT(1) NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml index 5195f7e39c..d050c5ada7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml @@ -33,7 +33,8 @@ - + + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index 3a268960d1..c80cf3d00a 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -1,379 +1,378 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( - ID INT auto_increment NOT NULL, - NAME VARCHAR(300) DEFAULT NULL, - PRIMARY KEY (ID) + ID INT AUTO_INCREMENT NOT NULL, + NAME VARCHAR(300) DEFAULT NULL, + PRIMARY KEY (ID) +); + +CREATE TABLE IF NOT EXISTS DM_GROUP ( + ID INTEGER AUTO_INCREMENT NOT NULL, + GROUP_NAME VARCHAR(100) DEFAULT NULL, + DESCRIPTION TEXT DEFAULT NULL, + DATE_OF_CREATE BIGINT DEFAULT NULL, + DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL, + OWNER VARCHAR(45) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( - ID INTEGER auto_increment NOT NULL, - SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, - CERTIFICATE BLOB DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (ID) + ID INTEGER AUTO_INCREMENT NOT NULL, + SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, + CERTIFICATE BLOB DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS DM_DEVICE ( - ID INTEGER auto_increment NOT NULL, - DESCRIPTION TEXT DEFAULT NULL, - NAME VARCHAR(100) DEFAULT NULL, - DEVICE_TYPE_ID INT(11) DEFAULT NULL, - DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (ID), - CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + ID INTEGER AUTO_INCREMENT NOT NULL, + DESCRIPTION TEXT DEFAULT NULL, + NAME VARCHAR(100) DEFAULT NULL, + DEVICE_TYPE_ID INT(11) DEFAULT NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID), + CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID) + REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); + +CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER DEFAULT NULL, + GROUP_ID INTEGER DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID), + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) + REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_OPERATION ( - ID INTEGER AUTO_INCREMENT NOT NULL, - TYPE VARCHAR(50) NOT NULL, - CREATED_TIMESTAMP TIMESTAMP NOT NULL, - RECEIVED_TIMESTAMP TIMESTAMP NULL, - OPERATION_CODE VARCHAR(1000) NOT NULL, - PRIMARY KEY (ID) + ID INTEGER AUTO_INCREMENT NOT NULL, + TYPE VARCHAR(50) NOT NULL, + CREATED_TIMESTAMP TIMESTAMP NOT NULL, + RECEIVED_TIMESTAMP TIMESTAMP NULL, + OPERATION_CODE VARCHAR(1000) NOT NULL, + PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS DM_CONFIG_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - OPERATION_CONFIG BLOB DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_config FOREIGN KEY (OPERATION_ID) REFERENCES + OPERATION_ID INTEGER NOT NULL, + OPERATION_CONFIG BLOB DEFAULT NULL, + PRIMARY KEY (OPERATION_ID), + CONSTRAINT fk_dm_operation_config FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_COMMAND_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_command FOREIGN KEY (OPERATION_ID) REFERENCES + OPERATION_ID INTEGER NOT NULL, + ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY (OPERATION_ID), + CONSTRAINT fk_dm_operation_command FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_POLICY_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED INTEGER NOT NULL DEFAULT 0, - OPERATION_DETAILS BLOB DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_policy FOREIGN KEY (OPERATION_ID) REFERENCES + OPERATION_ID INTEGER NOT NULL, + ENABLED INTEGER NOT NULL DEFAULT 0, + OPERATION_DETAILS BLOB DEFAULT NULL, + PRIMARY KEY (OPERATION_ID), + CONSTRAINT fk_dm_operation_policy FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_PROFILE_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED INTEGER NOT NULL DEFAULT 0, - OPERATION_DETAILS BLOB DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_profile FOREIGN KEY (OPERATION_ID) REFERENCES + OPERATION_ID INTEGER NOT NULL, + ENABLED INTEGER NOT NULL DEFAULT 0, + OPERATION_DETAILS BLOB DEFAULT NULL, + PRIMARY KEY (OPERATION_ID), + CONSTRAINT fk_dm_operation_profile FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); 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) DEFAULT NULL, - STATUS VARCHAR(50) NULL, - DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, - DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, - TENANT_ID INT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OWNER VARCHAR(50) NOT NULL, + OWNERSHIP VARCHAR(45) DEFAULT NULL, + STATUS VARCHAR(50) NULL, + DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, + DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, + TENANT_ID INT NOT NULL, + PRIMARY KEY (ID), + 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_ENROLMENT_OP_MAPPING ( - ID INTEGER AUTO_INCREMENT NOT NULL, - ENROLMENT_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NOT NULL, - STATUS VARCHAR(50) NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES + ID INTEGER AUTO_INCREMENT NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + STATUS VARCHAR(50) NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_device_operation_mapping_operation FOREIGN KEY (OPERATION_ID) REFERENCES + CONSTRAINT fk_dm_device_operation_mapping_operation FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( - ID INTEGER AUTO_INCREMENT NOT NULL, - ENROLMENT_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NOT NULL, - OPERATION_RESPONSE BLOB DEFAULT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES + ID INTEGER AUTO_INCREMENT NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + OPERATION_RESPONSE BLOB DEFAULT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES + CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); -- POLICY RELATED TABLES -- -CREATE TABLE IF NOT EXISTS DM_PROFILE ( - ID INT NOT NULL AUTO_INCREMENT , - PROFILE_NAME VARCHAR(45) NOT NULL , - TENANT_ID INT NOT NULL , - DEVICE_TYPE_ID INT NOT NULL , - CREATED_TIME DATETIME NOT NULL , - UPDATED_TIME DATETIME NOT NULL , - PRIMARY KEY (ID) , +CREATE TABLE IF NOT EXISTS DM_PROFILE ( + ID INT NOT NULL AUTO_INCREMENT, + PROFILE_NAME VARCHAR(45) NOT NULL, + TENANT_ID INT NOT NULL, + DEVICE_TYPE_ID INT NOT NULL, + CREATED_TIME DATETIME NOT NULL, + UPDATED_TIME DATETIME NOT NULL, + PRIMARY KEY (ID), CONSTRAINT DM_PROFILE_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - - - - - -CREATE TABLE IF NOT EXISTS DM_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - NAME VARCHAR(45) DEFAULT NULL , - DESCRIPTION VARCHAR(1000) NULL, - TENANT_ID INT(11) NOT NULL , - PROFILE_ID INT(11) NOT NULL , - OWNERSHIP_TYPE VARCHAR(45) NULL, - COMPLIANCE VARCHAR(100) NULL, - PRIORITY INT NOT NULL, - ACTIVE INT(2) NOT NULL, - UPDATED INT(1) NULL, - PRIMARY KEY (ID) , + FOREIGN KEY (DEVICE_TYPE_ID) + REFERENCES DM_DEVICE_TYPE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + +CREATE TABLE IF NOT EXISTS DM_POLICY ( + ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(45) DEFAULT NULL, + DESCRIPTION VARCHAR(1000) NULL, + TENANT_ID INT(11) NOT NULL, + PROFILE_ID INT(11) NOT NULL, + OWNERSHIP_TYPE VARCHAR(45) NULL, + COMPLIANCE VARCHAR(100) NULL, + PRIORITY INT NOT NULL, + ACTIVE INT(2) NOT NULL, + UPDATED INT(1) NULL, + PRIMARY KEY (ID), CONSTRAINT FK_DM_PROFILE_DM_POLICY - FOREIGN KEY (PROFILE_ID ) - REFERENCES DM_PROFILE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (PROFILE_ID) + REFERENCES DM_PROFILE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - - - -CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - DEVICE_ID INT(11) NOT NULL , +CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( + ID INT(11) NOT NULL AUTO_INCREMENT, + DEVICE_ID INT(11) NOT NULL, ENROLMENT_ID INT(11) NOT NULL, - DEVICE BLOB NOT NULL, - POLICY_ID INT(11) NOT NULL , - PRIMARY KEY (ID) , + DEVICE BLOB NOT NULL, + POLICY_ID INT(11) NOT NULL, + PRIMARY KEY (ID), CONSTRAINT FK_POLICY_DEVICE_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION, + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, CONSTRAINT FK_DEVICE_DEVICE_POLICY - FOREIGN KEY (DEVICE_ID ) - REFERENCES DM_DEVICE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - - - -CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( - ID INT(11) NOT NULL , - DEVICE_TYPE_ID INT(11) NOT NULL , - POLICY_ID INT(11) NOT NULL , - PRIMARY KEY (ID) , +CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( + ID INT(11) NOT NULL, + DEVICE_TYPE_ID INT(11) NOT NULL, + POLICY_ID INT(11) NOT NULL, + PRIMARY KEY (ID), CONSTRAINT FK_DEVICE_TYPE_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION, + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - - - - - -CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( - ID INT(11) NOT NULL AUTO_INCREMENT, - PROFILE_ID INT(11) NOT NULL, - FEATURE_CODE VARCHAR(30) NOT NULL, - DEVICE_TYPE_ID INT NOT NULL, - TENANT_ID INT(11) NOT NULL , - CONTENT BLOB NULL DEFAULT NULL, + FOREIGN KEY (DEVICE_TYPE_ID) + REFERENCES DM_DEVICE_TYPE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + +CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( + ID INT(11) NOT NULL AUTO_INCREMENT, + PROFILE_ID INT(11) NOT NULL, + FEATURE_CODE VARCHAR(30) NOT NULL, + DEVICE_TYPE_ID INT NOT NULL, + TENANT_ID INT(11) NOT NULL, + CONTENT BLOB NULL DEFAULT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES - FOREIGN KEY (PROFILE_ID) - REFERENCES DM_PROFILE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (PROFILE_ID) + REFERENCES DM_PROFILE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - - - -CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - ROLE_NAME VARCHAR(45) NOT NULL , - POLICY_ID INT(11) NOT NULL , - PRIMARY KEY (ID) , +CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( + ID INT(11) NOT NULL AUTO_INCREMENT, + ROLE_NAME VARCHAR(45) NOT NULL, + POLICY_ID INT(11) NOT NULL, + PRIMARY KEY (ID), CONSTRAINT FK_ROLE_POLICY_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - - - -CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( - ID INT NOT NULL AUTO_INCREMENT , - POLICY_ID INT NOT NULL , - USERNAME VARCHAR(45) NOT NULL , - PRIMARY KEY (ID) , +CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( + ID INT NOT NULL AUTO_INCREMENT, + POLICY_ID INT NOT NULL, + USERNAME VARCHAR(45) NOT NULL, + PRIMARY KEY (ID), CONSTRAINT DM_POLICY_USER_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - - - CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( - ID INT NOT NULL AUTO_INCREMENT , - DEVICE_ID INT NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, - POLICY_ID INT NOT NULL , - POLICY_CONTENT BLOB NULL , - TENANT_ID INT NOT NULL, - APPLIED TINYINT(1) NULL , - CREATED_TIME TIMESTAMP NULL , - UPDATED_TIME TIMESTAMP NULL , - APPLIED_TIME TIMESTAMP NULL , - PRIMARY KEY (ID) , - CONSTRAINT FK_DM_POLICY_DEVCIE_APPLIED - FOREIGN KEY (DEVICE_ID ) - REFERENCES DM_DEVICE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + +CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + ENROLMENT_ID INT(11) NOT NULL, + POLICY_ID INT NOT NULL, + POLICY_CONTENT BLOB NULL, + TENANT_ID INT NOT NULL, + APPLIED BOOLEAN NULL, + CREATED_TIME TIMESTAMP NULL, + UPDATED_TIME TIMESTAMP NULL, + APPLIED_TIME TIMESTAMP NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_POLICY_DEVICE_APPLIED + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - - CREATE TABLE IF NOT EXISTS DM_CRITERIA ( - ID INT NOT NULL AUTO_INCREMENT, - TENANT_ID INT NOT NULL, - NAME VARCHAR(50) NULL, + ID INT NOT NULL AUTO_INCREMENT, + TENANT_ID INT NOT NULL, + NAME VARCHAR(50) NULL, PRIMARY KEY (ID) ); - - CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA ( - ID INT NOT NULL AUTO_INCREMENT, + ID INT NOT NULL AUTO_INCREMENT, CRITERIA_ID INT NOT NULL, - POLICY_ID INT NOT NULL, + POLICY_ID INT NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_CRITERIA_POLICY_CRITERIA - FOREIGN KEY (CRITERIA_ID) - REFERENCES DM_CRITERIA (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, + FOREIGN KEY (CRITERIA_ID) + REFERENCES DM_CRITERIA (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, CONSTRAINT FK_POLICY_POLICY_CRITERIA - FOREIGN KEY (POLICY_ID) - REFERENCES DM_POLICY (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( - ID INT NOT NULL AUTO_INCREMENT, - POLICY_CRITERION_ID INT NOT NULL, - PROP_KEY VARCHAR(45) NULL, - PROP_VALUE VARCHAR(100) NULL, - CONTENT BLOB NULL COMMENT 'This is used to ', + ID INT NOT NULL AUTO_INCREMENT, + POLICY_CRITERION_ID INT NOT NULL, + PROP_KEY VARCHAR(45) NULL, + PROP_VALUE VARCHAR(100) NULL, + CONTENT BLOB NULL + COMMENT 'This is used to ', PRIMARY KEY (ID), CONSTRAINT FK_POLICY_CRITERIA_PROPERTIES - FOREIGN KEY (POLICY_CRITERION_ID) - REFERENCES DM_POLICY_CRITERIA (ID) - ON DELETE CASCADE - ON UPDATE NO ACTION + FOREIGN KEY (POLICY_CRITERION_ID) + REFERENCES DM_POLICY_CRITERIA (ID) + ON DELETE CASCADE + ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( - ID INT NOT NULL AUTO_INCREMENT, - DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT(11) NOT NULL, - POLICY_ID INT NOT NULL, - TENANT_ID INT NOT NULL, - STATUS INT NULL, - LAST_SUCCESS_TIME TIMESTAMP NULL, + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + ENROLMENT_ID INT(11) NOT NULL, + POLICY_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + STATUS INT NULL, + LAST_SUCCESS_TIME TIMESTAMP NULL, LAST_REQUESTED_TIME TIMESTAMP NULL, - LAST_FAILED_TIME TIMESTAMP NULL, - ATTEMPTS INT NULL, + LAST_FAILED_TIME TIMESTAMP NULL, + ATTEMPTS INT NULL, PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( - ID INT NOT NULL AUTO_INCREMENT, - POLICY_ID INT NOT NULL, - DEVICE_TYPE_ID INT NOT NULL, - TENANT_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT, + POLICY_ID INT NOT NULL, + DEVICE_TYPE_ID INT NOT NULL, + TENANT_ID INT(11) NOT NULL, PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( - ID INT NOT NULL AUTO_INCREMENT, - COMPLIANCE_STATUS_ID INT NOT NULL, - TENANT_ID INT NOT NULL, - FEATURE_CODE VARCHAR(15) NOT NULL, - STATUS INT NULL, + ID INT NOT NULL AUTO_INCREMENT, + COMPLIANCE_STATUS_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + FEATURE_CODE VARCHAR(15) NOT NULL, + STATUS INT NULL, PRIMARY KEY (ID), CONSTRAINT FK_COMPLIANCE_FEATURES_STATUS - FOREIGN KEY (COMPLIANCE_STATUS_ID) - REFERENCES DM_POLICY_COMPLIANCE_STATUS (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (COMPLIANCE_STATUS_ID) + REFERENCES DM_POLICY_COMPLIANCE_STATUS (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); 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) DEFAULT NULL, - STATUS VARCHAR(50) NULL, - DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, - DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, - TENANT_ID INT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OWNER VARCHAR(50) NOT NULL, + OWNERSHIP VARCHAR(45) DEFAULT NULL, + STATUS VARCHAR(50) NULL, + DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, + DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, + TENANT_ID INT NOT NULL, + PRIMARY KEY (ID), + 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(150) NOT NULL, - APP_IDENTIFIER VARCHAR(150) NOT NULL, - PLATFORM VARCHAR(50) DEFAULT NULL, - CATEGORY VARCHAR(50) NULL, - VERSION VARCHAR(50) NULL, - TYPE VARCHAR(50) NULL, - LOCATION_URL VARCHAR(100) DEFAULT NULL, - IMAGE_URL VARCHAR(100) DEFAULT NULL, - APP_PROPERTIES BLOB NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID) + ID INTEGER AUTO_INCREMENT NOT NULL, + NAME VARCHAR(150) NOT NULL, + APP_IDENTIFIER VARCHAR(150) NOT NULL, + PLATFORM VARCHAR(50) DEFAULT NULL, + CATEGORY VARCHAR(50) NULL, + VERSION VARCHAR(50) NULL, + TYPE VARCHAR(50) NULL, + LOCATION_URL VARCHAR(100) DEFAULT NULL, + IMAGE_URL VARCHAR(100) DEFAULT NULL, + APP_PROPERTIES BLOB 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 + 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 + CONSTRAINT fk_dm_application FOREIGN KEY (APPLICATION_ID) REFERENCES DM_APPLICATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); @@ -381,16 +380,16 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING ( -- NOTIFICATION TABLE -- CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( - NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - STATUS VARCHAR(10) NULL, - DESCRIPTION VARCHAR(100) NULL, - PRIMARY KEY (NOTIFICATION_ID), - CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES + NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + STATUS VARCHAR(10) NULL, + DESCRIPTION VARCHAR(100) NULL, + PRIMARY KEY (NOTIFICATION_ID), + CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_operation_notification FOREIGN KEY (OPERATION_ID) REFERENCES + CONSTRAINT fk_dm_operation_notification FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); -- NOTIFICATION TABLE END -- @@ -398,67 +397,64 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( DROP TABLE IF EXISTS DM_DEVICE_INFO; CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( - ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INT NULL, - KEY_FIELD VARCHAR(45) NULL, - VALUE_FIELD VARCHAR(100) NULL, + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, + KEY_FIELD VARCHAR(45) NULL, + VALUE_FIELD VARCHAR(100) NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_INFO_DEVICE - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - - DROP TABLE IF EXISTS DM_DEVICE_LOCATION; CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( - ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INT NULL, - LATITUDE DOUBLE NULL, - LONGITUDE DOUBLE NULL, - STREET1 VARCHAR(45) NULL, - STREET2 VARCHAR(45) NULL, - CITY VARCHAR(45) NULL, - ZIP VARCHAR(10) NULL, - STATE VARCHAR(45) NULL, - COUNTRY VARCHAR(45) NULL, + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, + LATITUDE DOUBLE NULL, + LONGITUDE DOUBLE NULL, + STREET1 VARCHAR(45) NULL, + STREET2 VARCHAR(45) NULL, + CITY VARCHAR(45) NULL, + ZIP VARCHAR(10) NULL, + STATE VARCHAR(45) NULL, + COUNTRY VARCHAR(45) NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_LOCATION_DEVICE - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); - CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( - ID INT NOT NULL AUTO_INCREMENT, - DEVICE_ID INT NOT NULL, - IMEI VARCHAR(100) NULL, - IMSI VARCHAR(100) NULL, - DEVICE_MODEL VARCHAR(45) NULL, - VENDOR VARCHAR(45) NULL, - OS_VERSION VARCHAR(45) NULL, - BATTERY_LEVEL DECIMAL(4) NULL, - INTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - INTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - EXTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - EXTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - OPERATOR VARCHAR(45) NULL, - CONNECTION_TYPE VARCHAR(10) NULL, - MOBILE_SIGNAL_STRENGTH DECIMAL(5) NULL, - SSID VARCHAR(45) NULL, - CPU_USAGE DECIMAL(5) NULL, - TOTAL_RAM_MEMORY DECIMAL(5) NULL, - AVAILABLE_RAM_MEMORY DECIMAL(5) NULL, - PLUGGED_IN INT(1) NULL, + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + IMEI VARCHAR(100) NULL, + IMSI VARCHAR(100) NULL, + DEVICE_MODEL VARCHAR(45) NULL, + VENDOR VARCHAR(45) NULL, + OS_VERSION VARCHAR(45) NULL, + BATTERY_LEVEL DECIMAL(4) NULL, + INTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, + INTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, + EXTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, + EXTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, + OPERATOR VARCHAR(45) NULL, + CONNECTION_TYPE VARCHAR(10) NULL, + MOBILE_SIGNAL_STRENGTH DECIMAL(5) NULL, + SSID VARCHAR(45) NULL, + CPU_USAGE DECIMAL(5) NULL, + TOTAL_RAM_MEMORY DECIMAL(5) NULL, + AVAILABLE_RAM_MEMORY DECIMAL(5) NULL, + PLUGGED_IN INT(1) NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); From 3fd141acdfa486e641093c36f8536f11b500f8af Mon Sep 17 00:00:00 2001 From: charithag Date: Tue, 29 Mar 2016 17:07:56 +0530 Subject: [PATCH 3/5] Add missing parts and test to group management. --- .../mgt/core/group/mgt/dao/GroupDAO.java | 8 +- .../mgt/core/group/mgt/dao/GroupDAOImpl.java | 74 +++++++++++++++++- .../GroupManagementProviderService.java | 28 ++++--- .../GroupManagementProviderServiceImpl.java | 28 ++++--- .../mgt/core/dao/GroupPersistTests.java | 77 ++++++++++++++++--- .../src/test/resources/log4j.properties | 22 +++--- 6 files changed, 178 insertions(+), 59 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java index 9fc556c266..00fdd97a44 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java @@ -19,15 +19,11 @@ package org.wso2.carbon.device.mgt.core.group.mgt.dao; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import java.util.List; -import java.util.Set; /** * This interface represents the key operations associated with persisting group related information. @@ -151,10 +147,10 @@ public interface GroupDAO { * Get all devices of a given tenant and device group. * * @param groupId of the group. - * @param tenantId of user's tenant. * @param request for pagination. + * @param tenantId of user's tenant. * @return list of device in group * @throws GroupManagementDAOException */ - PaginationResult getDevices(int groupId, PaginationRequest request, int tenantId) throws GroupManagementDAOException; + List getDevices(int groupId, PaginationRequest request, int tenantId) throws GroupManagementDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java index 3023a07f3b..0a2004dff2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java @@ -20,8 +20,8 @@ package org.wso2.carbon.device.mgt.core.group.mgt.dao; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import java.sql.Connection; @@ -304,13 +304,79 @@ public class GroupDAOImpl implements GroupDAO { @Override public List getDevices(int groupId, int tenantId) throws GroupManagementDAOException { - return null; + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List devices = null; + try { + conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT gd.DEVICE_ID, " + + "gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + + "FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, " + + "d.DEVICE_TYPE_ID FROM DM_DEVICE d, DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ? " + + "AND d.ID = dgm.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t " + + "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + rs = stmt.executeQuery(); + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while retrieving information of all " + + "registered devices", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; } + @SuppressWarnings("JpaQueryApiInspection") @Override - public PaginationResult getDevices(int groupId, PaginationRequest request, int tenantId) + public List getDevices(int groupId, PaginationRequest request, int tenantId) throws GroupManagementDAOException { - return null; + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List devices = null; + try { + conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT gd.DEVICE_ID, " + + "gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + + "FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, " + + "d.DEVICE_TYPE_ID FROM DM_DEVICE d, DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ? " + + "AND d.ID = dgm.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t " + + "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? " + + "LIMIT ?, ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + //noinspection JpaQueryApiInspection + stmt.setInt(4, request.getStartIndex()); + stmt.setInt(5, request.getRowCount()); + rs = stmt.executeQuery(); + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while retrieving information of all " + + "registered devices", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java index 3174772201..7c47929802 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java @@ -1,27 +1,25 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2016, 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 + * 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. + * 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.service; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; @@ -190,7 +188,7 @@ public interface GroupManagementProviderService { * @return list of group devices * @throws GroupManagementException */ - PaginationResult getDevices(int groupId, PaginationRequest request) throws GroupManagementException; + List getDevices(int groupId, PaginationRequest request) throws GroupManagementException; /** * This method is used to retrieve the device count of a given group. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index f5e57c1ae4..985be91cf0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -1,20 +1,19 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2016, 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 + * 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. + * 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.service; @@ -26,7 +25,6 @@ import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; @@ -427,7 +425,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public PaginationResult getDevices(int groupId, PaginationRequest request) + public List getDevices(int groupId, PaginationRequest request) throws GroupManagementException { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); try { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java index 30fbae49e4..0e7772fa0c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java @@ -23,6 +23,7 @@ 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.Device; import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; @@ -39,19 +40,14 @@ import java.util.List; public class GroupPersistTests extends BaseDeviceManagementTest { private static final Log log = LogFactory.getLog(GroupPersistTests.class); - GroupDAO groupDAO = GroupManagementDAOFactory.getGroupDAO(); int groupId = -1; + private GroupDAO groupDAO; @BeforeClass @Override - public void init() { - try { - initDataSource(); - } catch (Exception e) { - String msg = "Error occurred while initializing data source."; - log.error(msg, e); - Assert.fail(msg, e); - } + public void init() throws Exception { + initDataSource(); + groupDAO = GroupManagementDAOFactory.getGroupDAO(); } @Test @@ -176,6 +172,68 @@ public class GroupPersistTests extends BaseDeviceManagementTest { } @Test(dependsOnMethods = {"updateGroupTest"}) + public void addDeviceToGroupTest() { + Device initialTestDevice = TestDataHolder.initialTestDevice; + try { + GroupManagementDAOFactory.beginTransaction(); + groupDAO.addDevice(groupId, initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID); + GroupManagementDAOFactory.commitTransaction(); + log.debug("Device added to group."); + } catch (GroupManagementDAOException e) { + GroupManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while adding device '" + initialTestDevice.getName() + "'."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + + try { + GroupManagementDAOFactory.openConnection(); + List groupedDevices = groupDAO.getDevices(groupId, TestDataHolder.SUPER_TENANT_ID); + Assert.assertNotEquals(groupedDevices.size(), 0, "No device found"); + Assert.assertNotNull(groupedDevices.get(0), "Device is null"); + Assert.assertEquals(groupedDevices.get(0).getId(), initialTestDevice.getId(), "Device ids not matched"); + } catch (GroupManagementDAOException e) { + String msg = "Error occurred while retrieving group details."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the data source."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = {"addDeviceToGroupTest"}) + public void removeDeviceFromGroupTest() { + Device initialTestDevice = TestDataHolder.initialTestDevice; + try { + GroupManagementDAOFactory.beginTransaction(); + groupDAO.removeDevice(groupId, initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID); + GroupManagementDAOFactory.commitTransaction(); + log.debug("Group added to database."); + } catch (GroupManagementDAOException e) { + GroupManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while adding device '" + initialTestDevice.getName() + "'."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = {"removeDeviceFromGroupTest"}) public void deleteGroupTest() { DeviceGroup group = getGroupById(groupId); int groupId = 0; @@ -201,4 +259,5 @@ public class GroupPersistTests extends BaseDeviceManagementTest { group = getGroupById(groupId); Assert.assertNull(group, "Group not deleted"); } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/log4j.properties b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/log4j.properties index dc3d465fc0..e415fd607d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/log4j.properties +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/log4j.properties @@ -1,29 +1,31 @@ # -# Copyright 2009 WSO2, Inc. (http://wso2.com) +# Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. +# 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. +# 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. # # # This is the log4j configuration file used by WSO2 Carbon # # IMPORTANT : Please do not remove or change the names of any -# of the Appenders defined here. The layout pattern & log file +# of the Appender defined here. The layout pattern & log file # can be changed using the WSO2 Carbon Management Console, and those # settings will override the settings in this file. # -log4j.rootLogger=INFO, STD_OUT +log4j.rootLogger=DEBUG, STD_OUT # Redirect log messages to console log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender From 2f0a3388a6fab59c8e161d968cce722fc41b0512 Mon Sep 17 00:00:00 2001 From: charithag Date: Tue, 29 Mar 2016 18:01:21 +0530 Subject: [PATCH 4/5] Implemented missing methods in group management. --- .../mgt/core/group/mgt/dao/GroupDAO.java | 13 +++- .../mgt/core/group/mgt/dao/GroupDAOImpl.java | 32 +++++++- .../GroupManagementProviderService.java | 17 +++++ .../GroupManagementProviderServiceImpl.java | 76 +++++++++++++++++-- .../mgt/core/dao/GroupPersistTests.java | 4 +- 5 files changed, 131 insertions(+), 11 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java index 00fdd97a44..a353ff25c6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java @@ -67,11 +67,22 @@ public interface GroupDAO { /** * Get the list of Device Groups in tenant. * + * @param request for pagination. + * @param tenantId of user's tenant. + * @return List of all Device Groups in tenant. + * @throws GroupManagementDAOException + */ + List getGroups(PaginationRequest request, int tenantId) throws GroupManagementDAOException; + + + /** + * Get count of Device Groups in tenant. + * * @param tenantId of user's tenant. * @return List of all Device Groups in tenant. * @throws GroupManagementDAOException */ - List getGroups(int tenantId) throws GroupManagementDAOException; + int getGroupCount(int tenantId) throws GroupManagementDAOException; /** * Get the list of Groups that matches with the given DeviceGroup name. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java index 0a2004dff2..702e20c44a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java @@ -147,16 +147,21 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public List getGroups(int tenantId) throws GroupManagementDAOException { + public List getGroups(PaginationRequest request, int tenantId) + throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; List deviceGroupList = null; try { Connection conn = GroupManagementDAOFactory.getConnection(); String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " - + "FROM DM_GROUP WHERE TENANT_ID = ?"; + + "FROM DM_GROUP WHERE TENANT_ID = ? LIMIT ?, ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); + //noinspection JpaQueryApiInspection + stmt.setInt(2, request.getStartIndex()); + //noinspection JpaQueryApiInspection + stmt.setInt(3, request.getRowCount()); resultSet = stmt.executeQuery(); deviceGroupList = new ArrayList<>(); while (resultSet.next()) { @@ -170,6 +175,28 @@ public class GroupDAOImpl implements GroupDAO { return deviceGroupList; } + @Override + public int getGroupCount(int tenantId) throws GroupManagementDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT COUNT(ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP WHERE TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + resultSet = stmt.executeQuery(); + if (resultSet.next()) { + return resultSet.getInt("DEVICE_COUNT"); + } else { + return 0; + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while getting group count'", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + } + @Override public List findInGroups(String groupName, int tenantId) throws GroupManagementDAOException { @@ -363,6 +390,7 @@ public class GroupDAOImpl implements GroupDAO { stmt.setInt(3, tenantId); //noinspection JpaQueryApiInspection stmt.setInt(4, request.getStartIndex()); + //noinspection JpaQueryApiInspection stmt.setInt(5, request.getRowCount()); rs = stmt.executeQuery(); devices = new ArrayList<>(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java index 7c47929802..b202917b6d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java @@ -15,6 +15,7 @@ * specific language governing permissions and limitations * under the License. */ + package org.wso2.carbon.device.mgt.core.service; import org.wso2.carbon.device.mgt.common.Device; @@ -78,6 +79,22 @@ public interface GroupManagementProviderService { */ List findInGroups(String groupName, String username) throws GroupManagementException; + /** + * Get all device groups in tenant + * + * @return list of groups + * @throws GroupManagementException + */ + List getGroups(PaginationRequest request) throws GroupManagementException; + + /** + * Get all device group count in tenant + * + * @return group count + * @throws GroupManagementException + */ + int getGroupCount() throws GroupManagementException; + /** * Get device groups of user * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index 985be91cf0..02788d78ac 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -15,6 +15,7 @@ * specific language governing permissions and limitations * under the License. */ + package org.wso2.carbon.device.mgt.core.service; import org.apache.commons.logging.Log; @@ -211,6 +212,46 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid return groupsWithData; } + @Override + public List getGroups(PaginationRequest request) throws GroupManagementException { + List deviceGroups = new ArrayList<>(); + try { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + GroupManagementDAOFactory.openConnection(); + deviceGroups = this.groupDAO.getGroups(request, tenantId); + } catch (GroupManagementDAOException e) { + throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e); + } catch (SQLException e) { + throw new GroupManagementException("Error occurred while opening a connection to the data source.", e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + List groupsWithData = new ArrayList<>(); + for (DeviceGroupBuilder groupBroker : deviceGroups) { + groupBroker.setUsers(this.getUsers(groupBroker.getId())); + groupBroker.setRoles(this.getRoles(groupBroker.getId())); + groupsWithData.add(groupBroker.getGroup()); + } + return groupsWithData; + } + + @Override + public int getGroupCount() throws GroupManagementException { + try { + int count; + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + GroupManagementDAOFactory.openConnection(); + count = groupDAO.getGroupCount(tenantId); + return count; + } catch (GroupManagementDAOException e) { + throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e); + } catch (SQLException e) { + throw new GroupManagementException("Error occurred while opening a connection to the data source.", e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + } + /** * {@inheritDoc} */ @@ -415,9 +456,14 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid public List getDevices(int groupId) throws GroupManagementException { try { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + GroupManagementDAOFactory.getConnection(); return this.groupDAO.getDevices(groupId, tenantId); } catch (GroupManagementDAOException e) { throw new GroupManagementException("Error occurred while getting devices in group.", e); + } catch (SQLException e) { + throw new GroupManagementException("Error occurred while opening a connection to the data source.", e); + } finally { + GroupManagementDAOFactory.closeConnection(); } } @@ -429,9 +475,14 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid throws GroupManagementException { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); try { + GroupManagementDAOFactory.getConnection(); return this.groupDAO.getDevices(groupId, request, tenantId); } catch (GroupManagementDAOException e) { throw new GroupManagementException("Error occurred while getting devices in group.", e); + } catch (SQLException e) { + throw new GroupManagementException("Error occurred while opening a connection to the data source.", e); + } finally { + GroupManagementDAOFactory.closeConnection(); } } @@ -442,17 +493,14 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid public int getDeviceCount(int groupId) throws GroupManagementException { try { int count; - GroupManagementDAOFactory.beginTransaction(); + GroupManagementDAOFactory.getConnection(); count = groupDAO.getDeviceCount(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId()); - GroupManagementDAOFactory.commitTransaction(); return count; } catch (GroupManagementDAOException e) { - GroupManagementDAOFactory.rollbackTransaction(); - throw new GroupManagementException("Error occurred while retrieving device count of group " + - "'" + groupId + "'.", e); - } catch (TransactionManagementException e) { - throw new GroupManagementException("Error occurred while initiating transaction.", e); + throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e); + } catch (SQLException e) { + throw new GroupManagementException("Error occurred while opening a connection to the data source.", e); } finally { GroupManagementDAOFactory.closeConnection(); } @@ -473,11 +521,18 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid return false; } int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + GroupManagementDAOFactory.beginTransaction(); this.groupDAO.addDevice(groupId, device.getId(), tenantId); + GroupManagementDAOFactory.commitTransaction(); } catch (DeviceManagementException e) { throw new GroupManagementException("Error occurred while retrieving device.", e); } catch (GroupManagementDAOException e) { + GroupManagementDAOFactory.rollbackTransaction(); throw new GroupManagementException("Error occurred while adding device to group '" + groupId + "'.", e); + } catch (TransactionManagementException e) { + throw new GroupManagementException("Error occurred while initiating transaction.", e); + } finally { + GroupManagementDAOFactory.closeConnection(); } return true; } @@ -497,11 +552,18 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid return false; } int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + GroupManagementDAOFactory.beginTransaction(); this.groupDAO.removeDevice(groupId, device.getId(), tenantId); + GroupManagementDAOFactory.commitTransaction(); } catch (DeviceManagementException e) { throw new GroupManagementException("Error occurred while retrieving device.", e); + } catch (TransactionManagementException e) { + throw new GroupManagementException("Error occurred while initiating transaction.", e); } catch (GroupManagementDAOException e) { + GroupManagementDAOFactory.rollbackTransaction(); throw new GroupManagementException("Error occurred while adding device to group '" + groupId + "'.", e); + } finally { + GroupManagementDAOFactory.closeConnection(); } return true; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java index 0e7772fa0c..29bfa22a5d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java @@ -24,6 +24,7 @@ import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; @@ -154,7 +155,8 @@ public class GroupPersistTests extends BaseDeviceManagementTest { public void getGroupTest() { try { GroupManagementDAOFactory.openConnection(); - List groups = groupDAO.getGroups(TestDataHolder.SUPER_TENANT_ID); + PaginationRequest paginationRequest = new PaginationRequest(0, 1000); + List groups = groupDAO.getGroups(paginationRequest, TestDataHolder.SUPER_TENANT_ID); Assert.assertNotEquals(groups.size(), 0, "No groups found"); Assert.assertNotNull(groups.get(0), "Group is null"); log.debug("No of Groups found: " + groups.size()); From 3e4ccf63379681c2c5d92838c767de6e29170bd9 Mon Sep 17 00:00:00 2001 From: charithag Date: Wed, 30 Mar 2016 01:44:04 +0530 Subject: [PATCH 5/5] Add missing features and component from IoTS-1.0.0-M4 --- .../pom.xml | 94 ++++ .../carbon/apimgt/annotations/api/API.java | 36 ++ .../pom.xml | 171 ++++++++ .../ApiApplicationRegistrationService.java | 58 +++ ...ApiApplicationRegistrationServiceImpl.java | 129 ++++++ .../extension/api/util/APIUtil.java | 60 +++ .../api/util/RegistrationProfile.java | 92 ++++ .../src/main/webapp/META-INF/permissions.xml | 52 +++ .../webapp/META-INF/webapp-classloading.xml | 35 ++ .../src/main/webapp/WEB-INF/cxf-servlet.xml | 39 ++ .../src/main/webapp/WEB-INF/web.xml | 52 +++ .../pom.xml | 118 +++++ .../APIManagementProviderService.java | 70 +++ .../APIManagementProviderServiceImpl.java | 406 ++++++++++++++++++ .../constants/ApiApplicationConstants.java | 31 ++ .../extension/dto/ApiApplicationKey.java | 53 +++ .../exception/APIManagerException.java | 60 +++ ...ApplicationManagerExtensionDataHolder.java | 69 +++ ...ationManagerExtensionServiceComponent.java | 79 ++++ .../extension/util/APIManagerUtil.java | 55 +++ components/apimgt-extensions/pom.xml | 36 +- .../carbon/device/mgt/common/Feature.java | 35 +- .../pom.xml | 61 ++- .../feature/mgt/GenericFeatureManager.java | 76 ++++ .../feature/mgt/annotations/DeviceType.java | 29 ++ .../feature/mgt/annotations/Feature.java | 36 ++ .../FeatureManagementLifecycleListener.java | 71 +++ .../feature/mgt/util/AnnotationUtil.java | 221 ++++++++++ .../pom.xml | 62 +++ .../src/main/resources/p2.inf | 2 +- .../pom.xml | 117 +++++ .../src/main/resources/CDMF_DEFAULT_IDP.xml | 44 ++ .../src/main/resources/build.properties | 19 + .../src/main/resources/jwt.properties | 54 +++ .../src/main/resources/p2.inf | 3 + features/jwt-client/pom.xml | 42 ++ pom.xml | 67 ++- 37 files changed, 2692 insertions(+), 42 deletions(-) create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/API.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/RegistrationProfile.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/permissions.xml create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/webapp-classloading.xml create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/cxf-servlet.xml create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/constants/ApiApplicationConstants.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/dto/ApiApplicationKey.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/exception/APIManagerException.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/GenericFeatureManager.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/DeviceType.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/Feature.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/lifecycle/listener/FeatureManagementLifecycleListener.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java create mode 100644 features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml create mode 100644 features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/CDMF_DEFAULT_IDP.xml create mode 100644 features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/build.properties create mode 100644 features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/jwt.properties create mode 100644 features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/p2.inf create mode 100644 features/jwt-client/pom.xml diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml new file mode 100644 index 0000000000..6715d66cbe --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml @@ -0,0 +1,94 @@ + + + + + + + apimgt-extensions + org.wso2.carbon.devicemgt + 1.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.apimgt.annotations + 1.1.0-SNAPSHOT + bundle + WSO2 Carbon - API Management Annotations + WSO2 Carbon - API Management Custom Annotation Module + http://wso2.org + + + + org.eclipse.osgi + org.eclipse.osgi + + + org.eclipse.osgi + org.eclipse.osgi.services + + + org.wso2.carbon + org.wso2.carbon.logging + + + javax.ws.rs + jsr311-api + + + + + + org.apache.felix + maven-scr-plugin + + + org.apache.felix + maven-bundle-plugin + 1.4.0 + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.device.mgt.version} + API Management Extentions - Custom Annotations + + org.wso2.carbon.apimgt.annotations.* + + + org.osgi.framework, + org.osgi.service.component, + org.apache.commons.logging, + javax.servlet, + javax.xml.*, + org.apache.commons.lang, + + + scribe;scope=compile|runtime;inline=false; + + + + + + + + \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/API.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/API.java new file mode 100644 index 0000000000..04ecd9ed70 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/API.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2016, 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.apimgt.annotations.api; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface API { + + String name(); + + String version(); + + String context(); + + String[] tags(); +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml new file mode 100644 index 0000000000..bfe5a9177b --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml @@ -0,0 +1,171 @@ + + + + + + apimgt-extensions + org.wso2.carbon.devicemgt + 1.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + 1.1.0-SNAPSHOT + org.wso2.carbon.apimgt.application.extension.api + war + WSO2 Carbon - API Application Management API + This module provides capability to create api manager application. + http://wso2.org + + + + + org.apache.cxf + cxf-rt-frontend-jaxws + provided + + + org.apache.cxf + cxf-rt-frontend-jaxrs + provided + + + org.apache.cxf + cxf-rt-transports-http + provided + + + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-jaxrs + + + javax + javaee-web-api + provided + + + javax.ws.rs + jsr311-api + provided + + + commons-httpclient.wso2 + commons-httpclient + provided + + + + org.wso2.carbon + org.wso2.carbon.utils + provided + + + org.bouncycastle.wso2 + bcprov-jdk15on + + + org.wso2.carbon + org.wso2.carbon.user.api + + + org.wso2.carbon + org.wso2.carbon.queuing + + + org.wso2.carbon + org.wso2.carbon.base + + + org.apache.axis2.wso2 + axis2 + + + org.igniterealtime.smack.wso2 + smack + + + org.igniterealtime.smack.wso2 + smackx + + + jaxen + jaxen + + + commons-fileupload.wso2 + commons-fileupload + + + org.apache.ant.wso2 + ant + + + org.apache.ant.wso2 + ant + + + commons-httpclient.wso2 + commons-httpclient + + + org.eclipse.equinox + javax.servlet + + + org.wso2.carbon + org.wso2.carbon.registry.api + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.application.extension + provided + + + + + + + maven-compiler-plugin + + UTF-8 + ${wso2.maven.compiler.source} + ${wso2.maven.compiler.target} + + + + maven-war-plugin + 2.2 + + ${project.artifactId} + + + + + + diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java new file mode 100644 index 0000000000..f6404de2d6 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2016, 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.apimgt.application.extension.api; + +import org.wso2.carbon.apimgt.application.extension.api.util.RegistrationProfile; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +/** + * This is the application registration service that exposed for apimApplicationRegistration + */ +public interface ApiApplicationRegistrationService { + + /** + * This method is used to register an APIM application for tenant domain. + */ + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + Response register(@PathParam("tenantDomain") String tenantDomain, + @QueryParam("applicationName") String applicationName); + + /** + * This method is used to register api application + * + * @param registrationProfile contains the necessary attributes that are needed in order to register an app. + */ + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + Response register(RegistrationProfile registrationProfile); + + @DELETE + Response unregister(@QueryParam("applicationName") String applicationName); +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java new file mode 100644 index 0000000000..00f537c086 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2016, 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.apimgt.application.extension.api; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.simple.JSONObject; +import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; +import org.wso2.carbon.apimgt.application.extension.api.util.RegistrationProfile; +import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants; +import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; +import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.apimgt.application.extension.api.util.APIUtil; +import org.wso2.carbon.user.api.UserStoreException; + +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + + +public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegistrationService { + private static final Log log = LogFactory.getLog(ApiApplicationRegistrationServiceImpl.class); + + @Path("register/tenants/{tenantDomain}") + @POST + public Response register(@PathParam("tenantDomain") String tenantDomain, + @QueryParam("applicationName") String applicationName) { + Response response; + try { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); + if (PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId() == -1) { + String msg = "Invalid tenant domain : " + tenantDomain; + response = Response.status(Response.Status.NOT_ACCEPTABLE).entity(msg).build(); + } + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminUserName(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username); + APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); + ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( + applicationName, ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, false); + return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); + } catch (APIManagerException e) { + String msg = "Error occurred while registering an application '" + applicationName + "'"; + log.error(msg, e); + response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (UserStoreException e) { + String msg = "Failed to retrieve the tenant" + tenantDomain + "'"; + log.error(msg, e); + response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + return response; + } + + @Path("register") + @POST + public Response register(RegistrationProfile registrationProfile) { + Response response; + try { + String username = APIUtil.getAuthenticatedUser(); + APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); + if (registrationProfile.isMappingAnExistingOAuthApp()) { + JSONObject jsonStringObject = new JSONObject(); + jsonStringObject.put(ApiApplicationConstants.JSONSTRING_USERNAME_TAG, username); + jsonStringObject.put(ApiApplicationConstants.JSONSTRING_KEY_TYPE_TAG, + ApiApplicationConstants.DEFAULT_TOKEN_TYPE); + jsonStringObject.put(ApiApplicationConstants.OAUTH_CLIENT_ID, registrationProfile.getConsumerKey()); + jsonStringObject.put(ApiApplicationConstants.OAUTH_CLIENT_SECRET, + registrationProfile.getConsumerSecret()); + jsonStringObject.put(ApiApplicationConstants.JSONSTRING_VALIDITY_PERIOD_TAG, + ApiApplicationConstants.DEFAULT_VALIDITY_PERIOD); + apiManagementProviderService.registerExistingOAuthApplicationToAPIApplication( + jsonStringObject.toJSONString(), registrationProfile.getApplicationName(), + registrationProfile.getConsumerKey(), username, registrationProfile.isAllowedToAllDomains()); + return Response.status(Response.Status.ACCEPTED).entity("OAuth App is mapped as APIM App").build(); + } else { + ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( + registrationProfile.getApplicationName(), registrationProfile.getTags(), + ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, false); + return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); + } + } catch (APIManagerException e) { + String msg = "Error occurred while registering an application '" + + registrationProfile.getApplicationName() + "'"; + log.error(msg, e); + response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return response; + } + + @Path("unregister") + @DELETE + public Response unregister(@QueryParam("applicationName") String applicationName) { + Response response; + try { + String username = APIUtil.getAuthenticatedUser(); + APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); + apiManagementProviderService.removeAPIApplication(applicationName, username); + return Response.status(Response.Status.ACCEPTED).build(); + } catch (APIManagerException e) { + String msg = "Error occurred while removing the application '" + applicationName; + log.error(msg, e); + response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return response; + } +} \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java new file mode 100644 index 0000000000..b15bcd1944 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2016, 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.apimgt.application.extension.api.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +/** + * This class provides utility functions used by REST-API. + */ +public class APIUtil { + + private static Log log = LogFactory.getLog(APIUtil.class); + + public static String getAuthenticatedUser() { + PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + String username = threadLocalCarbonContext.getUsername(); + String tenantDomain = threadLocalCarbonContext.getTenantDomain(); + if (username.endsWith(tenantDomain)) { + return username.substring(0, username.lastIndexOf("@")); + } + return username; + } + + public static String getTenantDomainOftheUser() { + PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + String tenantDomain = threadLocalCarbonContext.getTenantDomain(); + return tenantDomain; + } + + public static APIManagementProviderService getAPIManagementProviderService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + APIManagementProviderService apiManagementProviderService = + (APIManagementProviderService) ctx.getOSGiService(APIManagementProviderService.class, null); + if (apiManagementProviderService == null) { + String msg = "API management provider service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return apiManagementProviderService; + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/RegistrationProfile.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/RegistrationProfile.java new file mode 100644 index 0000000000..c0d231039c --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/RegistrationProfile.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2016, 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.apimgt.application.extension.api.util; + +import org.codehaus.jackson.annotate.JsonIgnoreProperties; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * DTO class to be used when registering an ApiM application. + */ +@XmlRootElement + +@JsonIgnoreProperties(ignoreUnknown = true) +public class RegistrationProfile { + + @XmlElement(required = true) + private String applicationName; + @XmlElement(required = true) + private String tags[]; + @XmlElement(required = true) + private boolean isAllowedToAllDomains; + @XmlElement(required = true) + private boolean isMappingAnExistingOAuthApp; + private String consumerKey; + private String consumerSecret; + + public String getApplicationName() { + return applicationName; + } + + public void setApiApplicationName(String apiApplicationName) { + this.applicationName = apiApplicationName; + } + + public String[] getTags() { + return tags; + } + + public void setTags(String[] tags) { + this.tags = tags; + } + + public boolean isAllowedToAllDomains() { + return isAllowedToAllDomains; + } + + public void setIsAllowedToAllDomains(boolean isAllowedToAllDomains) { + this.isAllowedToAllDomains = isAllowedToAllDomains; + } + + public boolean isMappingAnExistingOAuthApp() { + return isMappingAnExistingOAuthApp; + } + + public void setIsMappingAnExistingOAuthApp(boolean isMappingAnExistingOAuthApp) { + this.isMappingAnExistingOAuthApp = isMappingAnExistingOAuthApp; + } + + public String getConsumerKey() { + return consumerKey; + } + + public void setConsumerKey(String consumerKey) { + this.consumerKey = consumerKey; + } + + public String getConsumerSecret() { + return consumerSecret; + } + + public void setConsumerSecret(String consumerSecret) { + this.consumerSecret = consumerSecret; + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/permissions.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/permissions.xml new file mode 100644 index 0000000000..104c34fe3e --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/permissions.xml @@ -0,0 +1,52 @@ + + + + + + + + + + Register tenant specific application + /permission/super admin + /register/tenants/* + POST + super_admin_user + + + Register application + /device-mgt/api/application/add + /register + POST + application_user + + + Delete application + /device-mgt/api/application/remove + /unregister + DELETE + application_user + + \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/webapp-classloading.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 0000000000..b410b42670 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,35 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 0000000000..c9c72c4ad6 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..7aaaf3002d --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,52 @@ + + + + + WSO2 IoT Server + WSO2 IoT Server + + + CXFServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + + CXFServlet + /* + + + isAdminService + false + + + doAuthentication + true + + + + + managed-api-enabled + false + + diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml new file mode 100644 index 0000000000..3e2d879c8b --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml @@ -0,0 +1,118 @@ + + + + + + + apimgt-extensions + org.wso2.carbon.devicemgt + 1.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + 1.1.0-SNAPSHOT + org.wso2.carbon.apimgt.application.extension + bundle + WSO2 Carbon - API Application Management + This module provides capability to create api manager application. + http://wso2.org + + + + org.wso2.carbon + org.wso2.carbon.registry.core + + + org.wso2.carbon + org.wso2.carbon.core + + + org.wso2.carbon + org.wso2.carbon.utils + + + org.wso2.carbon + org.wso2.carbon.logging + + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.impl + + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.api + + + com.googlecode.json-simple.wso2 + json-simple + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/Abstract* + + + + + org.apache.felix + maven-scr-plugin + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.device.mgt.version} + API Management Application Bundle + org.wso2.carbon.apimgt.application.extension.internal + + org.osgi.framework, + org.osgi.service.component, + org.apache.commons.logging.*, + org.wso2.carbon.user.core.*, + org.wso2.carbon.apimgt.api;version="${carbon.api.mgt.version.range}", + org.wso2.carbon.apimgt.api.model;version="${carbon.api.mgt.version.range}", + org.wso2.carbon.apimgt.impl;version="${carbon.api.mgt.version.range}", + org.wso2.carbon.user.api, + org.wso2.carbon.utils.multitenancy, + org.json.simple, + org.wso2.carbon.context + + + !org.wso2.carbon.apimgt.application.extension.internal, + org.wso2.carbon.apimgt.application.extension.* + + + + + + + + diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java new file mode 100644 index 0000000000..643d66c23d --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2016, 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.apimgt.application.extension; + + +import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; +import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; + +/** + * This comprise on operation that is been done with api manager from CDMF. This service needs to be implemented in APIM. + */ +public interface APIManagementProviderService { + + /** + * Generate and retreive application keys. if the application does exist then + * create it and subscribe to apis that are grouped with the tags. + * + * @param apiApplicationName name of the application. + * @param tags tags of the apis that application needs to be subscribed. + * @param keyType of the application. + * @param username to whom the application is created + * @return consumerkey and secrete of the created application. + * @throws APIManagerException + */ + ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, String tags[], + String keyType, String username, boolean isAllowedAllDomains) + throws APIManagerException; + + /** + * Generate and retreive application keys. if the application does exist then + * create it and subscribe to all apis. + * + * @param apiApplicationName name of the application. + * @param keyType of the application. + * @param username to whom the application is created + * @return consumerkey and secrete of the created application. + * @throws APIManagerException + */ + ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, String keyType, + String username, boolean isAllowedAllDomains) + throws APIManagerException; + + /** + * Register existing Oauth application as apim application. + */ + void registerExistingOAuthApplicationToAPIApplication(String jsonString, String applicationName, String clientId, + String username, boolean isAllowedAllDomains) + throws APIManagerException; + + /** + * Remove APIM Application. + */ + void removeAPIApplication(String applicationName, String username) throws APIManagerException; + +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java new file mode 100644 index 0000000000..7a2af128d8 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java @@ -0,0 +1,406 @@ +/* + * Copyright (c) 2016, 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.apimgt.application.extension; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.simple.JSONObject; +import org.wso2.carbon.apimgt.api.APIConsumer; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.model.API; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.apimgt.api.model.APIKey; +import org.wso2.carbon.apimgt.api.model.Application; +import org.wso2.carbon.apimgt.api.model.SubscribedAPI; +import org.wso2.carbon.apimgt.api.model.Subscriber; +import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants; +import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; +import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; +import org.wso2.carbon.apimgt.application.extension.util.APIManagerUtil; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.APIManagerFactory; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; + +import java.util.Date; +import java.util.Map; +import java.util.Set; + +/** + * This class represents an implementation of APIManagementProviderService. + */ +public class APIManagementProviderServiceImpl implements APIManagementProviderService { + + private static final Log log = LogFactory.getLog(APIManagementProviderServiceImpl.class); + + /** + * {@inheritDoc} + */ + @Override + public ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, String keyType, + String username, boolean isAllowedAllDomains) + throws APIManagerException { + try { + APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username); + String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain()); + int applicationId = createApplicationAndSubscribeToAllAPIs(apiApplicationName, username); + Application[] applications = apiConsumer.getApplications(apiConsumer.getSubscriber(username), groupId); + Application application = null; + for (Application app : applications) { + if (app.getId() == applicationId) { + application = app; + } + } + if (application == null) { + throw new APIManagerException("Api application creation failed for " + apiApplicationName + + " to the user " + username); + } + APIKey retrievedApiApplicationKey = null; + for (APIKey apiKey : application.getKeys()) { + String applicationKeyType = apiKey.getType(); + if (applicationKeyType != null && applicationKeyType.equals(keyType)) { + retrievedApiApplicationKey = apiKey; + break; + } + } + if (retrievedApiApplicationKey != null) { + ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); + apiApplicationKey.setConsumerKey(retrievedApiApplicationKey.getConsumerKey()); + apiApplicationKey.setConsumerSecret(retrievedApiApplicationKey.getConsumerSecret()); + return apiApplicationKey; + } + String[] allowedDomains = new String[1]; + if (isAllowedAllDomains) { + allowedDomains[0] = ApiApplicationConstants.ALLOWED_DOMAINS; + } else { + allowedDomains[0] = APIManagerUtil.getTenantDomain(); + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put(ApiApplicationConstants.JSONSTRING_USERNAME_TAG, username); + String ownerJsonString = jsonObject.toJSONString(); + Map keyDetails = apiConsumer.requestApprovalForApplicationRegistration(username, + apiApplicationName, + keyType, "", + allowedDomains, + ApiApplicationConstants.DEFAULT_VALIDITY_PERIOD, + "null", groupId, + ownerJsonString); + ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); + apiApplicationKey.setConsumerKey((String) keyDetails.get(APIConstants.FrontEndParameterNames + .CONSUMER_KEY)); + apiApplicationKey.setConsumerSecret((String) keyDetails.get( + APIConstants.FrontEndParameterNames.CONSUMER_SECRET)); + return apiApplicationKey; + } catch (APIManagementException e) { + throw new APIManagerException("Failed to register a api application : " + apiApplicationName, e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void registerExistingOAuthApplicationToAPIApplication(String jsonString, String applicationName, + String clientId, String username, + boolean isAllowedAllDomains) + throws APIManagerException { + try { + APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username); + if (apiConsumer != null) { + String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain()); + createApplication(apiConsumer, applicationName, username, groupId); + String[] allowedDomains = new String[1]; + if (isAllowedAllDomains) { + allowedDomains[0] = ApiApplicationConstants.ALLOWED_DOMAINS; + } else { + allowedDomains[0] = APIManagerUtil.getTenantDomain(); + } + apiConsumer.mapExistingOAuthClient(jsonString, username, clientId, applicationName, + ApiApplicationConstants.DEFAULT_TOKEN_TYPE, allowedDomains); + } + } catch (APIManagementException e) { + throw new APIManagerException( + "Failed registering the OAuth app [ clientId " + clientId + " ] with api manager application", e); + } + } + + @Override + public void removeAPIApplication(String applicationName, String username) throws APIManagerException { + try { + APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username); + if (apiConsumer != null) { + String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain()); + Application[] applications = apiConsumer.getApplications(new Subscriber(username), groupId); + for (Application application : applications) { + if (application.getName().equals(applicationName)) { + apiConsumer.removeApplication(application); + break; + } + } + } + } catch (APIManagementException e) { + throw new APIManagerException( + "Failed to remove the application [ application name " + applicationName + " ]", e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, String tags[], + String keyType, String username, + boolean isAllowedAllDomains) + throws APIManagerException { + try { + APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username); + String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain()); + int applicationId = createApplicationAndSubscribeToAPIs(apiApplicationName, tags, username); + Application[] applications = apiConsumer.getApplications(apiConsumer.getSubscriber(username), groupId); + Application application = null; + for (Application app : applications) { + if (app.getId() == applicationId) { + application = app; + } + } + if (application == null) { + throw new APIManagerException( + "Api application creation failed for " + apiApplicationName + " to the user " + username); + } + + APIKey retrievedApiApplicationKey = null; + for (APIKey apiKey : application.getKeys()) { + String applicationKeyType = apiKey.getType(); + if (applicationKeyType != null && applicationKeyType.equals(keyType)) { + retrievedApiApplicationKey = apiKey; + break; + } + } + if (retrievedApiApplicationKey != null) { + ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); + apiApplicationKey.setConsumerKey(retrievedApiApplicationKey.getConsumerKey()); + apiApplicationKey.setConsumerSecret(retrievedApiApplicationKey.getConsumerSecret()); + return apiApplicationKey; + } + String[] allowedDomains = new String[1]; + if (isAllowedAllDomains) { + allowedDomains[0] = ApiApplicationConstants.ALLOWED_DOMAINS; + } else { + allowedDomains[0] = APIManagerUtil.getTenantDomain(); + } + String validityTime = "3600"; + String ownerJsonString = "{\"username\":\"" + username + "\"}"; + Map keyDetails = apiConsumer.requestApprovalForApplicationRegistration(username, + apiApplicationName, + keyType, "", + allowedDomains, + validityTime, + "null", + groupId, + ownerJsonString); + ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); + apiApplicationKey.setConsumerKey((String) keyDetails.get(APIConstants.FrontEndParameterNames + .CONSUMER_KEY)); + apiApplicationKey.setConsumerSecret((String) keyDetails.get( + APIConstants.FrontEndParameterNames.CONSUMER_SECRET)); + return apiApplicationKey; + } catch (APIManagementException e) { + throw new APIManagerException("Failed to register a api application : " + apiApplicationName, e); + } + } + + private int createApplication(APIConsumer apiConsumer, String applicationName, String username, String groupId) + throws APIManagerException { + try { + if (apiConsumer != null) { + if (apiConsumer.getSubscriber(username) == null) { + String tenantDomain = MultitenantUtils.getTenantDomain(username); + addSubscriber(username, "", groupId, APIManagerUtil.getTenantId(tenantDomain)); + } + Application application = apiConsumer.getApplicationsByName(username, applicationName, groupId); + if (application == null) { + Subscriber subscriber = apiConsumer.getSubscriber(username); + application = new Application(applicationName, subscriber); + application.setTier(ApiApplicationConstants.DEFAULT_TIER); + application.setGroupId(groupId); + return apiConsumer.addApplication(application, username); + } else { + if (log.isDebugEnabled()) { + log.debug("Application [" + applicationName + "] already exists for Subscriber [" + username + + "]"); + } + return application.getId(); + } + } else { + throw new APIManagerException("Failed to retrieve the api consumer for username" + username); + } + } catch (APIManagementException e) { + throw new APIManagerException("Failed to create application [name:" + applicationName + " , username:" + + username + ", " + "groupId:" + groupId, e); + } + } + + private void addSubscription(APIConsumer apiConsumer, APIIdentifier apiId, int applicationId, String username) + throws APIManagerException { + try { + if (apiConsumer != null) { + APIIdentifier apiIdentifier = new APIIdentifier(apiId.getProviderName(), apiId.getApiName(), + apiId.getVersion()); + apiIdentifier.setTier(ApiApplicationConstants.DEFAULT_TIER); + apiConsumer.addSubscription(apiIdentifier, username, applicationId); + if (log.isDebugEnabled()) { + log.debug("Successfully created subscription for API : " + apiId + " from application : " + + applicationId); + } + } else { + throw new APIManagerException("API provider configured for the given API configuration is null. " + + "Thus, the API is not published"); + } + } catch (APIManagementException e) { + throw new APIManagerException("Failed to create subscription for api name : " + apiId.getApiName(), e); + } + } + + + private void addSubscriber(String subscriberName, String subscriberEmail, String groupId, int tenantId) + throws APIManagerException { + if (log.isDebugEnabled()) { + log.debug("Creating subscriber with name " + subscriberName); + } + try { + APIConsumer consumer = APIManagerFactory.getInstance().getAPIConsumer(subscriberName); + if (consumer != null) { + Subscriber subscriber = new Subscriber(subscriberName); + subscriber.setSubscribedDate(new Date()); + subscriber.setEmail(subscriberEmail); + subscriber.setTenantId(tenantId); + consumer.addSubscriber(subscriber, groupId); + if (log.isDebugEnabled()) { + log.debug("Successfully created subscriber with name : " + subscriberName + " with groupID : " + + groupId); + } + } else { + throw new APIManagerException("API provider configured for the given API configuration is null. " + + "Thus, the API is not published"); + } + } catch (APIManagementException e) { + throw new APIManagerException("API provider configured for the given API configuration is null. " + + "Thus, the API is not published", e); + } + } + + /** + * This method registers an api application and then subscribe the application to the api. + * + * @param apiApplicationName name of the application. + * @param tags are used subscribe the apis with the tag. + * @param username subscription is created for the user. + * @throws APIManagerException + */ + private int createApplicationAndSubscribeToAPIs(String apiApplicationName, String tags[], String username) + throws APIManagerException { + try { + APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username); + String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain()); + int applicationId = createApplication(apiConsumer, apiApplicationName, username, groupId); + Subscriber subscriber = apiConsumer.getSubscriber(username); + Set userVisibleAPIs = null; + for (String tag : tags) { + Set tagAPIs = apiConsumer.getAPIsWithTag(tag); + if (userVisibleAPIs == null) { + userVisibleAPIs = tagAPIs; + } else { + userVisibleAPIs.addAll(tagAPIs); + } + } + if (userVisibleAPIs != null) { + Set subscribedAPIs = apiConsumer.getSubscribedAPIs(subscriber, apiApplicationName, + groupId); + for (API userVisbleAPI : userVisibleAPIs) { + APIIdentifier apiIdentifier = userVisbleAPI.getId(); + boolean isSubscribed = false; + if (subscribedAPIs != null) { + for (SubscribedAPI subscribedAPI : subscribedAPIs) { + if (subscribedAPI.getApiId().equals(apiIdentifier)) { + isSubscribed = true; + } + } + } + if (!isSubscribed) { + addSubscription(apiConsumer, apiIdentifier, applicationId, username); + } + } + } + return applicationId; + } catch (APIManagementException e) { + throw new APIManagerException("Failed to fetch device apis information for the user " + username, e); + } + } + + /** + * This method registers an api application and then subscribe the application to the api. + * + * @param username subscription is created for the user. + * @throws APIManagerException + */ + private int createApplicationAndSubscribeToAllAPIs(String apiApplicationName, String username) + throws APIManagerException { + try { + APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username); + String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain()); + int applicationId = createApplication(apiConsumer, apiApplicationName, username, groupId); + String tenantDomain = MultitenantUtils.getTenantDomain(username); + Set userVisibleAPIs = apiConsumer.getAllPublishedAPIs(tenantDomain); + Subscriber subscriber = apiConsumer.getSubscriber(username); + Set subscribedAPIs = apiConsumer.getSubscribedAPIs(subscriber); + for (API visibleApi : userVisibleAPIs) { + APIIdentifier apiIdentifier = visibleApi.getId(); + boolean isSubscribed = false; + for (SubscribedAPI subscribedAPI : subscribedAPIs) { + if (subscribedAPI.getApiId().equals(apiIdentifier)) { + isSubscribed = true; + } + } + if (!isSubscribed) { + addSubscription(apiConsumer, apiIdentifier, applicationId, username); + } + } + return applicationId; + } catch (APIManagementException e) { + throw new APIManagerException("Failed to fetch device apis information for the user " + username, e); + } + } + + private String getLoggedInUserGroupId(String username, String tenantDomain) throws APIManagerException { + JSONObject loginInfoJsonObj = new JSONObject(); + try { + APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username); + loginInfoJsonObj.put("user", username); + if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + loginInfoJsonObj.put("isSuperTenant", true); + } else { + loginInfoJsonObj.put("isSuperTenant", false); + } + String loginInfoString = loginInfoJsonObj.toString(); + return apiConsumer.getGroupIds(loginInfoString); + } catch (APIManagementException e) { + throw new APIManagerException("Unable to get groupIds of user " + username, e); + } + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/constants/ApiApplicationConstants.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/constants/ApiApplicationConstants.java new file mode 100644 index 0000000000..821256a2af --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/constants/ApiApplicationConstants.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2016, 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.apimgt.application.extension.constants; + +public class ApiApplicationConstants { + public static final String DEFAULT_TOKEN_TYPE = "PRODUCTION"; + public static final String DEFAULT_TIER = "Unlimited"; + public static final String ALLOWED_DOMAINS = "ALL"; + public static final String OAUTH_CLIENT_ID = "client_id"; + public static final String OAUTH_CLIENT_SECRET = "client_secret"; + public static final String DEFAULT_VALIDITY_PERIOD = "3600"; + public static final String JSONSTRING_USERNAME_TAG = "username"; + public static final String JSONSTRING_KEY_TYPE_TAG = "key_type"; + public static final String JSONSTRING_VALIDITY_PERIOD_TAG = "validityPeriod"; +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/dto/ApiApplicationKey.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/dto/ApiApplicationKey.java new file mode 100644 index 0000000000..58e3b713e1 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/dto/ApiApplicationKey.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2016, 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.apimgt.application.extension.dto; + +import org.json.simple.JSONObject; +import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants; + +/** + * This holds api application consumer key and secret. + */ +public class ApiApplicationKey { + private String consumerKey; + private String consumerSecret; + + public String getConsumerKey() { + return this.consumerKey; + } + + public void setConsumerKey(String consumerKey) { + this.consumerKey = consumerKey; + } + + public String getConsumerSecret() { + return this.consumerSecret; + } + + public void setConsumerSecret(String consumerSecret) { + this.consumerSecret = consumerSecret; + } + + public String toString() { + JSONObject obj = new JSONObject(); + obj.put(ApiApplicationConstants.OAUTH_CLIENT_ID, this.getConsumerKey()); + obj.put(ApiApplicationConstants.OAUTH_CLIENT_SECRET, this.getConsumerSecret()); + return obj.toString(); + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/exception/APIManagerException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/exception/APIManagerException.java new file mode 100644 index 0000000000..b77bb584f4 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/exception/APIManagerException.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2016, 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.apimgt.application.extension.exception; + +/** + * Handles the exceptions related to API management. + */ +public class APIManagerException extends Exception { + + private static final long serialVersionUID = -8933142342423122660L; + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public APIManagerException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public APIManagerException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public APIManagerException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public APIManagerException() { + super(); + } + + public APIManagerException(Throwable cause) { + super(cause); + } + +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java new file mode 100644 index 0000000000..6f360ae649 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2016, 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.apimgt.application.extension.internal; + +import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; +import org.wso2.carbon.user.core.service.RealmService; +import org.wso2.carbon.user.core.tenant.TenantManager; + +public class APIApplicationManagerExtensionDataHolder { + private static APIApplicationManagerExtensionDataHolder thisInstance = new APIApplicationManagerExtensionDataHolder(); + private APIManagementProviderService apiManagementProviderService; + private RealmService realmService; + private TenantManager tenantManager; + + private APIApplicationManagerExtensionDataHolder() { + } + + + public static APIApplicationManagerExtensionDataHolder getInstance() { + return thisInstance; + } + + public APIManagementProviderService getAPIManagementProviderService() { + return apiManagementProviderService; + } + + public void setAPIManagementProviderService( + APIManagementProviderService apiManagementProviderService) { + this.apiManagementProviderService = apiManagementProviderService; + } + + public RealmService getRealmService() { + if (realmService == null) { + throw new IllegalStateException("Realm service is not initialized properly"); + } + return realmService; + } + + public void setRealmService(RealmService realmService) { + this.realmService = realmService; + this.setTenantManager(realmService); + } + + private void setTenantManager(RealmService realmService) { + if (realmService == null) { + throw new IllegalStateException("Realm service is not initialized properly"); + } + this.tenantManager = realmService.getTenantManager(); + } + + public TenantManager getTenantManager() { + return tenantManager; + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java new file mode 100644 index 0000000000..557d47aa11 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2016, 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.apimgt.application.extension.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext;; +import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; +import org.wso2.carbon.apimgt.application.extension.APIManagementProviderServiceImpl; +import org.wso2.carbon.user.core.service.RealmService; + +/** + * @scr.component name="org.wso2.carbon.apimgt.application.extension.internal.APIApplicationManagerExtensionServiceComponent" + * @scr.reference name="realm.service" + * immediate="true" + * interface="org.wso2.carbon.user.core.service.RealmService" + * cardinality="1..1" + * policy="dynamic" + * bind="setRealmService" + * unbind="unsetRealmService" + */ +public class APIApplicationManagerExtensionServiceComponent { + + private static Log log = LogFactory.getLog(APIApplicationManagerExtensionServiceComponent.class); + + protected void activate(ComponentContext componentContext) { + if (log.isDebugEnabled()) { + log.debug("Initializing device extension bundle"); + } + APIManagementProviderService apiManagementProviderService = new APIManagementProviderServiceImpl(); + APIApplicationManagerExtensionDataHolder.getInstance().setAPIManagementProviderService(apiManagementProviderService); + BundleContext bundleContext = componentContext.getBundleContext(); + bundleContext.registerService(APIManagementProviderService.class.getName(), apiManagementProviderService, null); + } + + protected void deactivate(ComponentContext componentContext) { + //do nothing + } + + /** + * Sets Realm Service. + * + * @param realmService An instance of RealmService + */ + protected void setRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Setting Realm Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setRealmService(realmService); + } + + /** + * Unsets Realm Service. + * + * @param realmService An instance of RealmService + */ + protected void unsetRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Unsetting Realm Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setRealmService(null); + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java new file mode 100644 index 0000000000..96dba4cfb4 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2016, 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.apimgt.application.extension.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; +import org.wso2.carbon.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.user.api.TenantManager; +import org.wso2.carbon.user.api.UserStoreException; + +public final class APIManagerUtil { + + private static final Log log = LogFactory.getLog(APIManagerUtil.class); + + /** + * returns the tenant Id of the specific tenant Domain + */ + public static int getTenantId(String tenantDomain) throws APIManagerException { + try { + if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + return MultitenantConstants.SUPER_TENANT_ID; + } + TenantManager tenantManager = APIApplicationManagerExtensionDataHolder.getInstance().getTenantManager(); + int tenantId = tenantManager.getTenantId(tenantDomain); + if (tenantId == -1) { + throw new APIManagerException("invalid tenant Domain :" + tenantDomain); + } + return tenantId; + } catch (UserStoreException e) { + throw new APIManagerException("invalid tenant Domain :" + tenantDomain); + } + } + + public static String getTenantDomain() { + return PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + } +} diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index 2ff22c9086..c17a81051c 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -1,21 +1,21 @@ + ~ Copyright (c) 2016, 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. + --> @@ -27,7 +27,6 @@ 4.0.0 - org.wso2.carbon.devicemgt apimgt-extensions 1.1.0-SNAPSHOT pom @@ -36,6 +35,9 @@ org.wso2.carbon.apimgt.webapp.publisher + org.wso2.carbon.apimgt.application.extension + org.wso2.carbon.apimgt.application.extension.api + org.wso2.carbon.apimgt.annotations diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Feature.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Feature.java index a2dd906220..375b8d4562 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Feature.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Feature.java @@ -1,22 +1,23 @@ /* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2016, 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 + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.device.mgt.common; +import javax.xml.bind.annotation.XmlElement; import java.io.Serializable; import java.util.List; @@ -27,8 +28,11 @@ public class Feature implements Serializable { private String name; private String description; private String deviceType; + private String method; + private String type; private List metadataEntries; + @XmlElement public int getId() { return id; } @@ -37,6 +41,7 @@ public class Feature implements Serializable { this.id = id; } + @XmlElement public String getCode() { return code; } @@ -45,6 +50,7 @@ public class Feature implements Serializable { this.code = code; } + @XmlElement public String getName() { return name; } @@ -61,6 +67,7 @@ public class Feature implements Serializable { this.metadataEntries = metadataEntries; } + @XmlElement public String getDeviceType() { return deviceType; } @@ -69,6 +76,7 @@ public class Feature implements Serializable { this.deviceType = deviceType; } + @XmlElement public String getDescription() { return description; } @@ -77,6 +85,24 @@ public class Feature implements Serializable { this.description = description; } + @XmlElement + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + @XmlElement + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + public static class MetadataEntry implements Serializable { private int id; @@ -98,5 +124,4 @@ public class Feature implements Serializable { this.value = value; } } - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml index 3a89167525..2eb681d946 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml @@ -1,4 +1,22 @@ + + @@ -40,6 +58,38 @@ org.wso2.carbon org.wso2.carbon.utils + + org.wso2.orbit.org.scannotation + scannotation + + + org.eclipse.osgi + org.eclipse.osgi + + + org.eclipse.osgi + org.eclipse.osgi.services + + + org.wso2.tomcat + tomcat + + + org.wso2.tomcat + tomcat-servlet-api + + + javax.ws.rs + jsr311-api + + + org.apache.axis2.wso2 + axis2 + + + commons-lang.wso2 + commons-lang + @@ -59,7 +109,7 @@ org.wso2.carbon.governance.api.*, - javax.xml.namespace, + javax.xml.namespace;resolution:=optional, org.wso2.carbon.context, org.wso2.carbon.device.mgt.common, org.wso2.carbon.device.mgt.common.license.mgt, @@ -69,7 +119,14 @@ org.wso2.carbon.registry.core.session, javax.xml.bind, org.wso2.carbon.utils, - org.apache.commons.logging + org.apache.commons.logging, + org.apache.catalina, + org.apache.catalina.core, + javax.servlet;resolution:=optional, + javax.xml.*;resolution:=optional, + org.apache.commons.lang, + javax.ws.rs;resolution:=optional, + org.scannotation diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/GenericFeatureManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/GenericFeatureManager.java new file mode 100644 index 0000000000..2da3394542 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/GenericFeatureManager.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.device.mgt.extensions.feature.mgt; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.Feature; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * This stores the features for device types that are mentioned through the annotations. + */ +public class GenericFeatureManager { + + private static final Log log = LogFactory.getLog(GenericFeatureManager.class); + private static Map> featureSet = new HashMap<>(); + private static GenericFeatureManager instance = new GenericFeatureManager(); + + private GenericFeatureManager() { + } + + public static GenericFeatureManager getInstance() { + return instance; + } + + /** + * @param deviceTypeFeatures feature list for each device type. + */ + public void addFeatures(Map> deviceTypeFeatures) { + this.featureSet.putAll(deviceTypeFeatures); + } + + /** + * @param deviceType + * @param featureName + * @return the extracted feature for the which matches the feature name and device type. + */ + public Feature getFeature(String deviceType, String featureName) { + Feature extractedFeature = null; + List deviceFeatureList = featureSet.get(deviceType); + for (Feature feature : deviceFeatureList) { + if (feature.getName().equalsIgnoreCase(featureName)) { + extractedFeature = feature; + } + } + return extractedFeature; + } + + /** + * @param deviceType returns the features for the device type. + * @return + */ + public List getFeatures(String deviceType) { + return featureSet.get(deviceType); + } + +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/DeviceType.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/DeviceType.java new file mode 100644 index 0000000000..7c7d635889 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/DeviceType.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface DeviceType { + String value(); +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/Feature.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/Feature.java new file mode 100644 index 0000000000..da0040f982 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/Feature.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Feature { + + String code(); + + String name(); + + String description(); + + String type(); +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/lifecycle/listener/FeatureManagementLifecycleListener.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/lifecycle/listener/FeatureManagementLifecycleListener.java new file mode 100644 index 0000000000..57ae592ee6 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/lifecycle/listener/FeatureManagementLifecycleListener.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.device.mgt.extensions.feature.mgt.lifecycle.listener; + +import org.apache.catalina.Lifecycle; +import org.apache.catalina.LifecycleEvent; +import org.apache.catalina.LifecycleListener; +import org.apache.catalina.core.StandardContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.Feature; +import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager; +import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType; +import org.wso2.carbon.device.mgt.extensions.feature.mgt.util.AnnotationUtil; + +import javax.servlet.ServletContext; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@SuppressWarnings("unused") +public class FeatureManagementLifecycleListener implements LifecycleListener { + + private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0"; + + private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled"; + + private static final Log log = LogFactory.getLog(FeatureManagementLifecycleListener.class); + private static final String UNLIMITED = "Unlimited"; + + @Override + public void lifecycleEvent(LifecycleEvent lifecycleEvent) { + if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) { + StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); + ServletContext servletContext = context.getServletContext(); + String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); + boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); + if (isManagedApi) { + try { + AnnotationUtil annotationUtil = new AnnotationUtil(context); + Set annotatedAPIClasses = annotationUtil.scanStandardContext(DeviceType.class.getName()); + Map> features = annotationUtil.extractFeatures(annotatedAPIClasses); + if (features != null && !features.isEmpty()) { + GenericFeatureManager.getInstance().addFeatures(features); + } + } catch (IOException e) { + log.error("Error enconterd while discovering annotated classes.", e); + } catch (ClassNotFoundException e) { + log.error("Error while scanning class for annotations.", e); + } + } + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java new file mode 100644 index 0000000000..621de44372 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.extensions.feature.mgt.util; + +import org.apache.catalina.core.StandardContext; +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.scannotation.AnnotationDB; +import org.scannotation.WarUrlFinder; +import org.wso2.carbon.device.mgt.common.Feature; +import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType; + +import javax.servlet.ServletContext; +import javax.ws.rs.DELETE; +import javax.ws.rs.FormParam; +import javax.ws.rs.GET; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.OPTIONS; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * This has the utility function to extract feature information. + */ +public class AnnotationUtil { + + private static final Log log = LogFactory.getLog(AnnotationUtil.class); + + private static final String PACKAGE_ORG_APACHE = "org.apache"; + private static final String PACKAGE_ORG_CODEHAUS = "org.codehaus"; + private static final String PACKAGE_ORG_SPRINGFRAMEWORK = "org.springframework"; + public static final String STRING_ARR = "string_arr"; + public static final String STRING = "string"; + private Class featureClazz; + private ClassLoader classLoader; + private ServletContext servletContext; + + + public AnnotationUtil(final StandardContext context) { + servletContext = context.getServletContext(); + classLoader = servletContext.getClassLoader(); + } + + /** + * Scan the context for classes with annotations + */ + public Set scanStandardContext(String className) throws IOException { + AnnotationDB db = new AnnotationDB(); + db.addIgnoredPackages(PACKAGE_ORG_APACHE); + db.addIgnoredPackages(PACKAGE_ORG_CODEHAUS); + db.addIgnoredPackages(PACKAGE_ORG_SPRINGFRAMEWORK); + URL[] libPath = WarUrlFinder.findWebInfLibClasspaths(servletContext); + URL classPath = WarUrlFinder.findWebInfClassesPath(servletContext); + URL[] urls = (URL[]) ArrayUtils.add(libPath, libPath.length, classPath); + db.scanArchives(urls); + + //Returns a list of classes with given Annotation + return db.getAnnotationIndex().get(className); + } + + /** + * Method identifies the URL templates and context by reading the annotations of a class + */ + public Map> extractFeatures(Set entityClasses) throws ClassNotFoundException { + Map> features = null; + if (entityClasses != null && !entityClasses.isEmpty()) { + features = new HashMap<>(); + for (final String className : entityClasses) { + final Map> featureMap = + AccessController.doPrivileged(new PrivilegedAction>>() { + public Map> run() { + Map> featureMap = new HashMap<>(); + try { + Class clazz = classLoader.loadClass(className); + Class deviceTypeClazz = (Class) classLoader.loadClass( + DeviceType.class.getName()); + Annotation deviceTypeAnno = clazz.getAnnotation(deviceTypeClazz); + if (deviceTypeAnno != null) { + Method[] deviceTypeMethod = deviceTypeClazz.getMethods(); + String deviceType = invokeMethod(deviceTypeMethod[0], deviceTypeAnno, STRING); + featureClazz = + (Class) classLoader.loadClass( + org.wso2.carbon.device.mgt.extensions.feature.mgt + .annotations.Feature.class.getName()); + List featureList = getFeatures(clazz.getDeclaredMethods()); + featureMap.put(deviceType, featureList); + } + } catch (Throwable e) { + log.error("Failed to load the annotation from the features in the " + + "class " + className, e); + } + return featureMap; + } + }); + + features.putAll(featureMap); + } + } + return features; + } + + private List getFeatures(Method[] annotatedMethods) throws Throwable { + List featureList = new ArrayList<>(); + for (Method method : annotatedMethods) { + Annotation methodAnnotation = method.getAnnotation(featureClazz); + if (methodAnnotation != null) { + Annotation[] annotations = method.getDeclaredAnnotations(); + for (int i = 0; i < annotations.length; i++) { + if (annotations[i].annotationType().getName().equals( + org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature.class.getName())) { + Feature feature = new Feature(); + Method[] featureAnnoMethods = featureClazz.getMethods(); + Annotation featureAnno = method.getAnnotation(featureClazz); + + for (int k = 0; k < featureAnnoMethods.length; k++) { + switch (featureAnnoMethods[k].getName()) { + case "name": + feature.setName(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); + break; + case "code": + feature.setCode(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); + break; + case "description": + feature.setDescription(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); + break; + case "type": + feature.setType(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); + break; + } + } + //Extracting method with which feature is exposed + if (annotations[i].annotationType().getName().equals(GET.class.getName())) { + feature.setMethod(HttpMethod.GET); + } + if (annotations[i].annotationType().getName().equals(POST.class.getName())) { + feature.setMethod(HttpMethod.POST); + } + if (annotations[i].annotationType().getName().equals(OPTIONS.class.getName())) { + feature.setMethod(HttpMethod.OPTIONS); + } + if (annotations[i].annotationType().getName().equals(DELETE.class.getName())) { + feature.setMethod(HttpMethod.DELETE); + } + if (annotations[i].annotationType().getName().equals(PUT.class.getName())) { + feature.setMethod(HttpMethod.PUT); + } + try { + Class formParamClazz = (Class) classLoader.loadClass( + FormParam.class.getName()); + Method[] formMethods = formParamClazz.getMethods(); + //Extract method parameter information and store same as feature meta info + List metaInfoList = new ArrayList<>(); + Annotation[][] paramAnnotations = method.getParameterAnnotations(); + for (int j = 0; j < paramAnnotations.length; j++) { + for (Annotation anno : paramAnnotations[j]) { + if (anno.annotationType().getName().equals(FormParam.class.getName())) { + Feature.MetadataEntry metadataEntry = new Feature.MetadataEntry(); + metadataEntry.setId(j); + metadataEntry.setValue(invokeMethod(formMethods[0], anno, STRING)); + metaInfoList.add(metadataEntry); + } + } + } + feature.setMetadataEntries(metaInfoList); + } catch (ClassNotFoundException e) { + log.debug("No Form Param found for class " + featureClazz.getName()); + } + featureList.add(feature); + } + } + } + } + return featureList; + } + + /** + * When an annotation and method is passed, this method invokes that executes said method against the annotation + */ + private String invokeMethod(Method method, Annotation annotation, String returnType) throws Throwable { + InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation); + switch (returnType) { + case STRING: + return (String) methodHandler.invoke(annotation, method, null); + case STRING_ARR: + return ((String[]) methodHandler.invoke(annotation, method, null))[0]; + default: + return null; + } + } +} \ No newline at end of file diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml index 59bc2b3dd6..36d8339dda 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml @@ -1,4 +1,22 @@ + + org.wso2.carbon.devicemgt @@ -22,6 +40,14 @@ org.wso2.carbon.devicemgt org.wso2.carbon.apimgt.webapp.publisher + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.annotations + + + org.wso2.orbit.org.scannotation + scannotation + @@ -51,6 +77,33 @@ + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-jaxrs-war + package + + copy + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.application.extension.api + war + true + + ${project.build.directory}/maven-shared-archive-resources/webapps/ + + ApiApplicationRegistration.war + + + + + + org.wso2.maven carbon-p2-plugin @@ -75,6 +128,15 @@ org.wso2.carbon.devicemgt:org.wso2.carbon.apimgt.webapp.publisher:${carbon.device.mgt.version} + + org.wso2.carbon.devicemgt:org.wso2.carbon.apimgt.application.extension:${carbon.device.mgt.version} + + + org.wso2.carbon.devicemgt:org.wso2.carbon.apimgt.annotations:${carbon.device.mgt.version} + + + org.wso2.orbit.org.scannotation:scannotation:${scannotation.version} + org.wso2.carbon.core.server:${carbon.kernel.version} diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/src/main/resources/p2.inf b/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/src/main/resources/p2.inf index fe2cbf1e96..d4cb94274f 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/src/main/resources/p2.inf +++ b/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/src/main/resources/p2.inf @@ -1,3 +1,3 @@ instructions.configure = \ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt-cdmf);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.devicemgt.ui_${feature.version}/jaggeryapps/devicemgt-cdmf,target:${installFolder}/../../deployment/server/jaggeryapps/devicemgt-cdmf,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.ui_${feature.version}/jaggeryapps/devicemgt-cdmf,target:${installFolder}/../../deployment/server/jaggeryapps/devicemgt-cdmf,overwrite:true);\ \ No newline at end of file diff --git a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml new file mode 100644 index 0000000000..0e188d4ef7 --- /dev/null +++ b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml @@ -0,0 +1,117 @@ + + + + + + + + org.wso2.carbon.devicemgt + jwt-client-feature + 1.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.identity.jwt.client.extension.feature + pom + 1.1.0-SNAPSHOT + WSO2 Carbon - JWT Client Feature + http://wso2.org + This feature contains jwt client implementation from which we can get a access token using the jwt + grant type handler + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.identity.jwt.client.extension + + + org.wso2.orbit.com.nimbusds + nimbus-jose-jwt + + + + + + + maven-resources-plugin + 2.6 + + + copy-resources + generate-resources + + copy-resources + + + src/main/resources + + + resources + + build.properties + p2.inf + + + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + p2-feature-generation + package + + p2-feature-gen + + + org.wso2.carbon.identity.jwt.client.extension + ../../../features/etc/feature.properties + + + org.wso2.carbon.p2.category.type:server + org.eclipse.equinox.p2.type.group:false + + + + + org.wso2.carbon.devicemgt:org.wso2.carbon.identity.jwt.client.extension:${carbon.device.mgt.version} + + + org.wso2.orbit.com.nimbusds:nimbus-jose-jwt:${nimbus.orbit.version} + + + + org.wso2.carbon.core.server:${carbon.kernel.version} + + + + + + + + + diff --git a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/CDMF_DEFAULT_IDP.xml b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/CDMF_DEFAULT_IDP.xml new file mode 100644 index 0000000000..2741e45be0 --- /dev/null +++ b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/CDMF_DEFAULT_IDP.xml @@ -0,0 +1,44 @@ + + + + CDMF_DEFAULT_IDP + CDMF_DEFAULT_IDP + + https://localhost:9443/oauth2/token + true + + + + + + + + + + + + + MIIFkzCCA3sCBAKkVfcwDQYJKoZIhvcNAQEFBQAwgY0xCzAJBgNVBAYTAlNMMRAwDgYDVQQIEwdXZXN0ZXJuMRAwDgYDVQQHEwdDb2xvbWJvMQ0wCwYDVQQKEwRXU08yMRQwEgYDVQQLEwtFbmdpbmVlcmluZzESMBAGA1UEAxMJbG9jYWxob3N0MSEwHwYJKoZIhvcNAQkBFhJpb3RzZXJ2ZXJAd3NvMi5jb20wHhcNMTUxMjE3MTMxMTA0WhcNMTcxMjE2MTMxMTA0WjCBjTELMAkGA1UEBhMCU0wxEDAOBgNVBAgTB1dlc3Rlcm4xEDAOBgNVBAcTB0NvbG9tYm8xDTALBgNVBAoTBFdTTzIxFDASBgNVBAsTC0VuZ2luZWVyaW5nMRIwEAYDVQQDEwlsb2NhbGhvc3QxITAfBgkqhkiG9w0BCQEWEmlvdHNlcnZlckB3c28yLmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALkiGVQ9tZOKIi/gD/toV+enq+neqOBGYQ8Fq/ABOWnK2QpGWm81+Rets5GbQ6W//D8C5TOBGqK7z+LAgdmILr1XLkvrXWoan0GPdDJ1wpc2/6XDZvM5f7Y8cmRqVPJv7AF+ImgF9dqv97gYCiujy+nNHd5Nk/60pco2LBV5SyLqqrzKXEnSGrS4zoYWpPeJ9YrXPEkW7A6AxTQK0yU9Ej4TktgafbTueythrLomKiZJj4wPxm2lA2lAZscDdws9NWrI5z/LUVLbUMxrY10Nig1liX5b1mrUk5bb1d2tqwkPrpRILKoOBJtI674SQS3GziiUiCJGIO/EGGRn1AJsC/SvnnEez3WKY/DgJ6102MWK/yWtY8NYHUX2anwMBS7UpT5A4BXdsfBz3R+iPF99FxdAGGsS4GQuuPocZaycLqoPCxpTSSxBsKMUcKpn3yaiQRd6uDuiTNt7odDOQj0Tno7uokh/HILgbzvj9EExDOsdwLVvqYmUHBPeLmiICWXfi4kyH/twPOZtV9eVnfWYx5Kwg+2Y4fIb3q4ABr0hzxaMYHQo6NOukSH1BcdAWiQIXbSFFaTZD8p6OfiZpHcQ59HT/Z8GBlCFL2xkYJFmOhXI/Cu+xrcwqEIInv7d8w3eiNQ7MneomEptLbBk9+kMsP0ubo34oOGHR9qk3Lj580c/AgMBAAEwDQYJKoZIhvcNAQEFBQADggIBADw70g2/wrgzrAM8OXBlthGbCEaXZpKwq9IJN0qu+/l+PNwF7csQhj+qW+zMrWaH1DGWJroaei1+NFFrj/pvp61rF/ZeTPGVJd7puCq++SevqIrzKyAEBtwtpXmcFhBpV/FrQAv3ODOJ3bN2wSRPZHUvARTBB3RaUI06g1jCaBzjDEGoMfSxdr5/Ty2WxTI9u9RlIs3Q52AiOmROtLPiEQZQIqfNO3cxCEWojHxPqVEZA/kQYy+rryj4H0zzSrj7QFlQhsMDw5j8bv9AcvTEGmwp29avsgnceDWinI6lwtd8zqh0ZW9QJdH0BRNCM/EkTlTUHeEg04/sOgOrlWcvEfVxDqNEtbUzU9UFxl0lkQkuRn1UdxZlvhWaFnel5iRC9b7OZvi2mkVujLyxEWlJB1tuyMLQxu6PfabBVODP5V8/+uyiiK/gwrB5rYl8RHxGoznJnI1Y3HVzKlA849CrMBaY5vnhE03cNja7QroPzLmmuXBLk2LbI1lu5nJAqKpBUPMI/IU3pF4Q7VTD2ZANI+ktGgGlM8AK4OJHWOhj8W289pWTHVjG8syPLTsaYkhgLjzZl/g9cUwn/96NJNvzd3dkT+7VgE+BJOLofq25CjZcN1M7MhWdl3vbWNj9vzL0+FCnwca8UecfvFS39PIekIvqbtP+Gw8NiYOUGIllZ0JH + + + + \ No newline at end of file diff --git a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/build.properties b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/build.properties new file mode 100644 index 0000000000..33bb0980d3 --- /dev/null +++ b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/build.properties @@ -0,0 +1,19 @@ +# +# Copyright (c) 2016, 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. +# + +custom = true diff --git a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/jwt.properties b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/jwt.properties new file mode 100644 index 0000000000..503301fb80 --- /dev/null +++ b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/jwt.properties @@ -0,0 +1,54 @@ +# +# Copyright (c) 2016, 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. +# + +#issuer of the JWT +iss=CDMF_DEFAULT_IDP + +TokenEndpoint=https://localhost:9443/oauth2/token + +#audience of JWT claim +#comma seperated values +aud=https://localhost:9443/oauth2/token + +#expiration time of JWT (number of minutes from the current time) +exp=1000 + +#issued at time of JWT (number of minutes from the current time) +iat=0 + +#nbf time of JWT (number of minutes from current time) +nbf=0 + +#skew between IDP and issuer(seconds) +skew=0 + +# JWT Id +#jti=token123 + +#KeyStore to cryptographic credentials +#KeyStore=src/main/resources/wso2carbon.jks + +#Password of the KeyStore +#KeyStorePassword=wso2carbon + +#Alias of the SP's private key +#PrivateKeyAlias=wso2carbon + +#Private key password to retrieve the private key used to sign +#AuthnRequest and LogoutRequest messages +#PrivateKeyPassword=wso2carbon diff --git a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/p2.inf b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/p2.inf new file mode 100644 index 0000000000..9e8c8bd070 --- /dev/null +++ b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/p2.inf @@ -0,0 +1,3 @@ +instructions.configure = \ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.identity.jwt.client.extension_${feature.version}/jwt.properties,target:${installFolder}/../../conf/etc/jwt.properties,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.identity.jwt.client.extension_${feature.version}/CDMF_DEFAULT_IDP.xml,target:${installFolder}/../../conf/identity/identity-providers/CDMF_DEFAULT_IDP.xml,overwrite:true);\ diff --git a/features/jwt-client/pom.xml b/features/jwt-client/pom.xml new file mode 100644 index 0000000000..6566c5fe96 --- /dev/null +++ b/features/jwt-client/pom.xml @@ -0,0 +1,42 @@ + + + + + + + + org.wso2.carbon.devicemgt + carbon-devicemgt + 1.1.0-SNAPSHOT + ../../pom.xml + + + 4.0.0 + jwt-client-feature + 1.1.0-SNAPSHOT + pom + WSO2 Carbon - Dynamic Client Registration Feature + http://wso2.org + + + org.wso2.carbon.identity.jwt.client.extension.feature + + + diff --git a/pom.xml b/pom.xml index 95f2ec384c..0eff5a4175 100644 --- a/pom.xml +++ b/pom.xml @@ -1,21 +1,21 @@ + ~ Copyright (c) 2016, 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. + --> @@ -50,6 +50,7 @@ features/dynamic-client-registration features/oauth-extensions features/email-sender + features/jwt-client @@ -200,6 +201,11 @@ org.wso2.carbon.apimgt.webapp.publisher ${carbon.device.mgt.version} + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.annotations + ${carbon.device.mgt.version} + org.wso2.carbon.devicemgt org.wso2.carbon.dynamic.client.registration @@ -275,6 +281,21 @@ zip ${carbon.device.mgt.version} + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.application.extension + ${carbon.device.mgt.version} + + + org.wso2.carbon.devicemgt + org.wso2.carbon.identity.jwt.client.extension + ${carbon.device.mgt.version} + + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.application.extension.api + ${carbon.device.mgt.version} + @@ -1209,6 +1230,11 @@ jackson-jaxrs ${jackson.version} + + org.codehaus.jackson + jackson-core-asl + ${jackson.version} + org.wso2.carbon.commons @@ -1306,6 +1332,12 @@ commons-collections ${commons-collections.version} + + javax + javaee-web-api + 6.0 + provided + @@ -1682,7 +1714,8 @@ 2.6.0.wso2v1 - 4.3.0 + 5.0.3 + (5.0.0,6.0.0] 5.0.11-SNAPSHOT