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 new file mode 100644 index 0000000000..0be33284e6 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java @@ -0,0 +1,115 @@ +/* + * 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.common.group.mgt; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; +import java.util.List; + +/** + * Holds Device Group details and expose to external access + */ +@XmlRootElement +public class DeviceGroup implements Serializable { + + private String description; + private String name; + private Long dateOfCreation; + private Long dateOfLastUpdate; + private String owner; + private List users; + private List roles; + + @XmlElement + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @XmlElement + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlElement + public Long getDateOfCreation() { + return dateOfCreation; + } + + public void setDateOfCreation(Long dateOfCreation) { + this.dateOfCreation = dateOfCreation; + } + + @XmlElement + public Long getDateOfLastUpdate() { + return dateOfLastUpdate; + } + + public void setDateOfLastUpdate(Long dateOfLastUpdate) { + this.dateOfLastUpdate = dateOfLastUpdate; + } + + @XmlElement + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + @XmlElement + public List getUsers() { + return users; + } + + protected void setUsers(List users) { + this.users = users; + } + + @XmlElement + public List getRoles() { + return roles; + } + + protected void setRoles(List roles) { + this.roles = roles; + } + + protected DeviceGroup getGroup() { + DeviceGroup deviceGroup = new DeviceGroup(); + deviceGroup.setDescription(getDescription()); + deviceGroup.setName(getName()); + deviceGroup.setDateOfCreation(getDateOfCreation()); + deviceGroup.setDateOfLastUpdate(getDateOfLastUpdate()); + deviceGroup.setOwner(getOwner()); + deviceGroup.setUsers(getUsers()); + deviceGroup.setRoles(getRoles()); + return deviceGroup; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupManagementException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupManagementException.java new file mode 100644 index 0000000000..1347882018 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupManagementException.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.device.mgt.common.group.mgt; + +/** + * This class represents a custom exception specified for group management + */ +public class GroupManagementException extends Exception { + + private static final long serialVersionUID = -312678248574816874L; + private String errorMessage; + + public GroupManagementException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public GroupManagementException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public GroupManagementException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public GroupManagementException() { + super(); + } + + public GroupManagementException(Throwable cause) { + super(cause); + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupUser.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupUser.java new file mode 100644 index 0000000000..1932c50309 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupUser.java @@ -0,0 +1,52 @@ +/* + * 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.common.group.mgt; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; +import java.util.List; + +/** + * This class holds Device Group user name and assigned group roles of user. Exposed to external access + */ +@XmlRootElement +public class GroupUser implements Serializable { + private String username; + private List groupRoles; + + @XmlElement + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @XmlElement + public List getGroupRoles() { + return groupRoles; + } + + public void setGroupRoles(List groupRoles) { + this.groupRoles = groupRoles; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceTypeDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceTypeDAO.java index b59781b876..d7217c90d1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceTypeDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceTypeDAO.java @@ -33,6 +33,8 @@ public interface DeviceTypeDAO { List getDeviceTypes() throws DeviceManagementDAOException; + List getDeviceTypes(int tenantId) throws DeviceManagementDAOException; + DeviceType getDeviceType(int id) throws DeviceManagementDAOException; DeviceType getDeviceType(String name) throws DeviceManagementDAOException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java index 6e90b21288..0014e56f6f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java @@ -80,6 +80,35 @@ public class DeviceTypeDAOImpl implements DeviceTypeDAO { } } + @Override + public List getDeviceTypes(int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List deviceTypes = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = + "SELECT ID AS DEVICE_TYPE_ID, NAME AS DEVICE_TYPE FROM DM_DEVICE_TYPE where PROVIDER_TENANT_ID =" + + "? OR SHARED_WITH_ALL_TENANTS = TRUE"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + rs = stmt.executeQuery(); + + while (rs.next()) { + DeviceType deviceType = new DeviceType(); + deviceType.setId(rs.getInt("DEVICE_TYPE_ID")); + deviceType.setName(rs.getString("DEVICE_TYPE")); + deviceTypes.add(deviceType); + } + return deviceTypes; + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the registered device types", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + } + @Override public DeviceType getDeviceType(int id) throws DeviceManagementDAOException { Connection conn; 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 new file mode 100644 index 0000000000..99098ad07e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java @@ -0,0 +1,61 @@ +/* + * 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.group.mgt; + +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; + +import java.util.List; + +/** + * This class is used to expose protected methods to the core. Use with internal access only. + */ +public class DeviceGroupBuilder extends DeviceGroup { + + /** + * Set device group to be decorated with the builder + * + * @param deviceGroup to decorate + */ + public DeviceGroupBuilder(DeviceGroup deviceGroup) { + this.setDescription(deviceGroup.getDescription()); + this.setName(deviceGroup.getName()); + this.setDateOfCreation(deviceGroup.getDateOfCreation()); + this.setDateOfLastUpdate(deviceGroup.getDateOfLastUpdate()); + this.setOwner(deviceGroup.getOwner()); + this.setUsers(deviceGroup.getUsers()); + this.setRoles(deviceGroup.getRoles()); + } + + @Override + public void setUsers(List users) { + super.setUsers(users); + } + + @Override + public void setRoles(List roles) { + super.setRoles(roles); + } + + @Override + public DeviceGroup getGroup() { + return super.getGroup(); + } + +} 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 new file mode 100644 index 0000000000..dbb98c2e74 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java @@ -0,0 +1,101 @@ +/* + * 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.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.group.mgt.DeviceGroup; +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. + */ +public interface GroupDAO { + /** + * Add new Device Group + * + * @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 + * + * @param deviceGroup group to update + * @throws GroupManagementDAOException + */ + void updateGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException; + + /** + * Delete an existing Device Group + * + * @param groupName group Id to delete + * @throws GroupManagementDAOException + */ + void deleteGroup(String groupName, int tenantId) throws GroupManagementDAOException; + + /** + * Get device group by Id + * + * @param groupName id of Device Group + * @return Device Group + * @throws GroupManagementDAOException + */ + DeviceGroupBuilder getGroup(String groupName, int tenantId) throws GroupManagementDAOException; + + /** + * Get the list 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; + + /** + * 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 + * @return List of DeviceGroup that matches with the given DeviceGroup name. + * @throws GroupManagementDAOException + */ + List getGroups(String groupName, int tenantId) throws GroupManagementDAOException; + + boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException; + + void addDeviceToGroup(String groupName, Device device, int tenantId) throws GroupManagementDAOException; + + void addDevicesToGroup(String groupName, Set devices, int tenantId) throws GroupManagementDAOException; + + void removeDeviceFromGroup(String groupName, DeviceIdentifier id, + int tenantId) throws GroupManagementDAOException; + + boolean isDeviceMappedToGroup(String groupName, DeviceIdentifier id, + int tenantId) throws GroupManagementDAOException; + + int getDeviceCount(String groupName, 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 new file mode 100644 index 0000000000..767e6ef367 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java @@ -0,0 +1,234 @@ +/* + * 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.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.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +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 + */ +public class GroupDAOImpl implements GroupDAO { + + @Override + public int addGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs; + int groupId = -1; + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "INSERT INTO DM_GROUP(DESCRIPTION, GROUP_NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, " + + "OWNER, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?)"; + stmt = conn.prepareStatement(sql, new String[]{"id"}); + stmt.setString(1, deviceGroup.getDescription()); + stmt.setString(2, deviceGroup.getName()); + stmt.setLong(3, new Date().getTime()); + stmt.setLong(4, new Date().getTime()); + stmt.setString(5, deviceGroup.getOwner()); + stmt.setInt(6, tenantId); + stmt.executeUpdate(); + rs = stmt.getGeneratedKeys(); + if (rs.next()) { + groupId = rs.getInt(1); + } + return groupId; + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while adding deviceGroup '" + + deviceGroup.getName() + "'", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void updateGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException { + PreparedStatement stmt = null; + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "UPDATE DM_GROUP SET DESCRIPTION = ?, GROUP_NAME = ?, DATE_OF_LAST_UPDATE = ?, OWNER = ? " + + "WHERE NAME = ? 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(6, tenantId); + stmt.executeUpdate(); + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while updating deviceGroup '" + + deviceGroup.getName() + "'", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void deleteGroup(String groupName, int tenantId) throws GroupManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + try { + conn = GroupManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_GROUP WHERE NAME = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, groupName); + stmt.setInt(2, tenantId); + stmt.executeUpdate(); + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while deleting group '" + groupName + "'", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public DeviceGroupBuilder getGroup(String groupName, 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 = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, groupName); + stmt.setInt(2, tenantId); + resultSet = stmt.executeQuery(); + if (resultSet.next()) { + return GroupManagementDAOUtil.loadGroup(resultSet); + } else { + return null; + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while obtaining information of Device Group '" + + groupName + "'", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + } + + @Override + public List getGroups(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_ENROLLMENT, DATE_OF_LAST_UPDATE, OWNER " + + "FROM DM_GROUP WHERE TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + resultSet = stmt.executeQuery(); + deviceGroupList = new ArrayList<>(); + while (resultSet.next()) { + deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet)); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return deviceGroupList; + } + + @Override + public List getGroups(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 " + + "FROM DM_GROUP WHERE GROUP_NAME LIKE ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, "%" + groupName + "%"); + stmt.setInt(2, tenantId); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + deviceGroups.add(GroupManagementDAOUtil.loadGroup(resultSet)); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while listing Device Groups by name '" + + groupName + "' in tenant '" + tenantId + "'", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return deviceGroups; + } + + @Override + public boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException { + PreparedStatement stmt = null; + ResultSet rst = 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(); + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" + + groupName + "'", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, rst); + } + } + + @Override + public void addDeviceToGroup(String group, Device device, int tenantId) throws GroupManagementDAOException { + + } + + @Override + public void addDevicesToGroup(String group, Set devices, + int tenantId) throws GroupManagementDAOException { + + } + + @Override + public void removeDeviceFromGroup(String group, DeviceIdentifier id, + int tenantId) throws GroupManagementDAOException { + + } + + @Override + public boolean isDeviceMappedToGroup(String group, DeviceIdentifier id, + int tenantId) throws GroupManagementDAOException { + return false; + } + + @Override + public int getDeviceCount(String groupName, int tenantId) throws GroupManagementDAOException { + return 0; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOException.java new file mode 100644 index 0000000000..da5c258909 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOException.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.group.mgt.dao; + +/** + * Custom exception class for group management data access related exceptions. + */ +public class GroupManagementDAOException extends Exception { + + private static final long serialVersionUID = 2021891706072918864L; + private String message; + + /** + * Constructs a new exception with the specified detail message and nested exception. + * + * @param message error message + * @param nestedException exception + */ + public GroupManagementDAOException(String message, Exception nestedException) { + super(message, nestedException); + setErrorMessage(message); + } + + /** + * Constructs a new exception with the specified detail message and cause. + * + * @param message the detail message. + * @param cause the cause of this exception. + */ + public GroupManagementDAOException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + /** + * Constructs a new exception with the specified detail message + * + * @param message the detail message. + */ + public GroupManagementDAOException(String message) { + super(message); + setErrorMessage(message); + } + + /** + * Constructs a new exception with the specified and cause. + * + * @param cause the cause of this exception. + */ + public GroupManagementDAOException(Throwable cause) { + super(cause); + } + + public String getMessage() { + return message; + } + + public void setErrorMessage(String errorMessage) { + this.message = errorMessage; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOFactory.java new file mode 100644 index 0000000000..0cba989b40 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOFactory.java @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.wso2.carbon.device.mgt.core.group.mgt.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException; +import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; +import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Hashtable; +import java.util.List; + +/** + * This class represents factory for group management data operations + */ +public class GroupManagementDAOFactory { + + private static final Log log = LogFactory.getLog(GroupManagementDAOFactory.class); + private static DataSource dataSource; + private static ThreadLocal currentConnection = new ThreadLocal(); + + /** + * Get instance of GroupDAO + * + * @return instance of GroupDAO implementation + */ + public static GroupDAO getGroupDAO() { + return new GroupDAOImpl(); + } + + /** + * Initialize factory with datasource configs + * + * @param config data source configuration + */ + public static void init(DataSourceConfig config) { + dataSource = resolveDataSource(config); + } + + /** + * Initialize factory with existing datasource + * + * @param dtSource an existing datasource + */ + public static void init(DataSource dtSource) { + dataSource = dtSource; + } + + /** + * Begin transaction with datasource for write data + * + * @throws TransactionManagementException + */ + public static void beginTransaction() throws TransactionManagementException { + Connection conn = currentConnection.get(); + if (conn != null) { + throw new IllegalTransactionStateException("A transaction is already active within the context of " + + "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + + "transaction is already active is a sign of improper transaction handling"); + } + try { + conn = dataSource.getConnection(); + conn.setAutoCommit(false); + currentConnection.set(conn); + } catch (SQLException e) { + throw new TransactionManagementException("Error occurred while retrieving config.datasource connection", e); + } + } + + /** + * Open connection to the datasource for read data + * + * @throws SQLException + */ + public static void openConnection() throws SQLException { + Connection conn = currentConnection.get(); + if (conn != null) { + throw new IllegalTransactionStateException("A transaction is already active within the context of " + + "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + + "transaction is already active is a sign of improper transaction handling"); + } + conn = dataSource.getConnection(); + currentConnection.set(conn); + } + + /** + * Get current connection to datasource + * + * @return current connection + * @throws SQLException + */ + public static Connection getConnection() throws SQLException { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + return conn; + } + + /** + * Commit current transaction to the datasource + */ + public static void commitTransaction() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + try { + conn.commit(); + } catch (SQLException e) { + log.error("Error occurred while committing the transaction", e); + } + } + + /** + * Rollback current transaction on failure + */ + public static void rollbackTransaction() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + try { + conn.rollback(); + } catch (SQLException e) { + log.warn("Error occurred while roll-backing the transaction", e); + } + } + + /** + * Close data connection associated with current transaction + */ + public static void closeConnection() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + try { + conn.close(); + } catch (SQLException e) { + log.warn("Error occurred while close the connection"); + } + currentConnection.remove(); + } + + + /** + * Resolve data source from the data source definition + * + * @param config data source configuration + * @return data source resolved from the data source definition + */ + private static DataSource resolveDataSource(DataSourceConfig config) { + DataSource dataSource = null; + if (config == null) { + throw new RuntimeException( + "Device Management Repository data source configuration " + "is null and " + + "thus, is not initialized"); + } + JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition(); + if (jndiConfig != null) { + if (log.isDebugEnabled()) { + log.debug("Initializing Device Management Repository data source using the JNDI " + + "Lookup Definition"); + } + List jndiPropertyList = + jndiConfig.getJndiProperties(); + if (jndiPropertyList != null) { + Hashtable jndiProperties = new Hashtable<>(); + for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) { + jndiProperties.put(prop.getName(), prop.getValue()); + } + dataSource = GroupManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), jndiProperties); + } else { + dataSource = GroupManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), null); + } + } + return dataSource; + } + +} 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 new file mode 100644 index 0000000000..fa3e52c436 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOUtil.java @@ -0,0 +1,93 @@ +/* + * 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.group.mgt.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; + +import javax.naming.InitialContext; +import javax.sql.DataSource; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Hashtable; + +/** + * This class represents utilities required to work with group management data + */ +public final class GroupManagementDAOUtil { + + private static final Log log = LogFactory.getLog(GroupManagementDAOUtil.class); + + /** + * Cleanup resources used to transaction + * + * @param stmt Prepared statement used + * @param rs Obtained results set + */ + public static void cleanupResources(PreparedStatement stmt, ResultSet rs) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing result set", e); + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing prepared statement", e); + } + } + } + + /** + * Lookup datasource using name and jndi properties + * + * @param dataSourceName Name of datasource to lookup + * @param jndiProperties Hash table of JNDI Properties + * @return datasource looked + */ + public static DataSource lookupDataSource(String dataSourceName, + final Hashtable jndiProperties) { + try { + if (jndiProperties == null || jndiProperties.isEmpty()) { + return (DataSource) InitialContext.doLookup(dataSourceName); + } + final InitialContext context = new InitialContext(jndiProperties); + return (DataSource) context.lookup(dataSourceName); + } catch (Exception e) { + throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); + } + } + + public static DeviceGroupBuilder loadGroup(ResultSet resultSet) throws SQLException { + DeviceGroupBuilder group = new DeviceGroupBuilder(new DeviceGroup()); + group.setDescription(resultSet.getString("DESCRIPTION")); + group.setName(resultSet.getString("GROUP_NAME")); + group.setDateOfCreation(resultSet.getLong("DATE_OF_ENROLLMENT")); + 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/service/GroupManagementServiceProvider.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProvider.java new file mode 100644 index 0000000000..7d81ad7657 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProvider.java @@ -0,0 +1,255 @@ +/* + * 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.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; + +import java.util.List; + +/** + * Interface for Group Management Services + */ +public interface GroupManagementServiceProvider { + + /** + * Add new device group and create default role with default permissions + * + * @param deviceGroup to add + * @param defaultRole of the deviceGroup + * @param defaultPermissions of the default role + * @return id of the new group + * @throws GroupManagementException + */ + int createGroup(DeviceGroup deviceGroup, String defaultRole, + String[] defaultPermissions) throws GroupManagementException; + + /** + * Update existing device group + * + * @param deviceGroup to update + * @throws GroupManagementException + */ + void updateGroup(DeviceGroup deviceGroup) throws GroupManagementException; + + /** + * Delete existing device group + * + * @param groupName of the group to delete + * @throws GroupManagementException + */ + boolean deleteGroup(String groupName) throws GroupManagementException; + + /** + * Get device group specified by groupId + * + * @param groupName of the group of the group + * @return group + * @throws GroupManagementException + */ + DeviceGroup getGroup(String groupName) throws GroupManagementException; + + /** + * Get list of device groups matched with %groupName% + * + * @param groupName of the groups. + * @param username of user + * @return List of Groups that matches with the given DeviceGroup name. + * @throws GroupManagementException + */ + List findGroups(String groupName, String username) throws GroupManagementException; + + /** + * Get device groups of user + * + * @param username of the user + * @return list of groups + * @throws GroupManagementException + */ + List getGroups(String username) throws GroupManagementException; + + /** + * Get device group count of user + * + * @param username of the user + * @return group count + * @throws GroupManagementException + */ + int getGroupCount(String username) throws GroupManagementException; + + /** + * Share device group with user specified by role + * + * @param username of the user + * @param groupName 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) + 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 sharingRole to be un shared + * @return is group un shared + * @throws GroupManagementException + */ + boolean unshareGroup(String userName, String groupName, String sharingRole) + throws GroupManagementException; + + /** + * Add new sharing role for device group + * + * @param userName of the user + * @param groupName 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) + throws GroupManagementException; + + /** + * Remove existing sharing role for device group + * + * @param groupName of the group + * @param roleName to remove + * @return is role removed + * @throws GroupManagementException + */ + boolean removeGroupSharingRole(String groupName, String roleName) throws GroupManagementException; + + /** + * Get all sharing roles for device group + * + * @param groupName of the group + * @return list of roles + * @throws GroupManagementException + */ + List getRoles(String groupName) throws GroupManagementException; + + /** + * Get specific device group sharing roles for user + * + * @param userName of the user + * @param groupName of the group + * @return list of roles + * @throws GroupManagementException + */ + List getRoles(String userName, String groupName) throws GroupManagementException; + + /** + * Get device group users + * + * @param groupName of the group + * @return list of group users + * @throws GroupManagementException + */ + List getUsers(String groupName) throws GroupManagementException; + + /** + * Get all devices in device group + * + * @param groupName of the group + * @return list of group devices + * @throws GroupManagementException + */ + List getDevices(String groupName) throws GroupManagementException; + + /** + * Get all devices in device group + * + * @param groupName 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; + + /** + * This method is used to retrieve the device count of a given group. + * + * @param groupName Name of the group + * @return returns the device count. + * @throws GroupManagementException + */ + int getDeviceCount(String groupName) throws GroupManagementException; + + /** + * Add device to device group + * + * @param deviceId of the device + * @param groupName of the group + * @return is device added + * @throws GroupManagementException + */ + boolean addDevice(DeviceIdentifier deviceId, String groupName) throws GroupManagementException; + + /** + * Remove device from device group + * + * @param deviceId of the device + * @param groupName of the group + * @return is device removed + * @throws GroupManagementException + */ + boolean removeDevice(DeviceIdentifier deviceId, String groupName) throws GroupManagementException; + + /** + * Get device group permissions of user + * + * @param username of the user + * @param groupName of the group + * @return array of permissions + * @throws GroupManagementException + */ + String[] getPermissions(String username, String groupName) throws GroupManagementException; + + /** + * Get device groups of user with permission + * + * @param username of the user + * @param permission to filter + * @return group list with specified permissions + * @throws GroupManagementException + */ + List getGroups(String username, String permission) throws GroupManagementException; + + /** + * Check user is authorized for specific permission of device group + * + * @param username of the user + * @param groupName to authorize + * @param permission to authorize + * @return is user authorized for permission + * @throws GroupManagementException + */ + boolean isAuthorized(String username, String groupName, 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/GroupManagementServiceProviderImpl.java new file mode 100644 index 0000000000..2923ee944a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProviderImpl.java @@ -0,0 +1,622 @@ +/* + * 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.service; + +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.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; +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 org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.user.api.Permission; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; +import org.wso2.carbon.user.core.util.UserCoreUtil; + +import java.sql.SQLException; +import java.util.*; + +public class GroupManagementServiceProviderImpl implements GroupManagementServiceProvider { + + private static Log log = LogFactory.getLog(GroupManagementServiceProviderImpl.class); + + private GroupDAO groupDAO; + + /** + * Set groupDAO from GroupManagementDAOFactory when class instantiate. + */ + public GroupManagementServiceProviderImpl() { + this.groupDAO = GroupManagementDAOFactory.getGroupDAO(); + } + + /** + * {@inheritDoc} + */ + @Override + public int createGroup(DeviceGroup deviceGroup, String defaultRole, String[] defaultPermissions) + throws GroupManagementException { + if (deviceGroup == null) { + throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException()); + } + DeviceGroupBuilder groupBroker = new DeviceGroupBuilder(deviceGroup); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + int groupId = -1; + try { + GroupManagementDAOFactory.beginTransaction(); + boolean nameIsExists = this.groupDAO.isGroupExist(deviceGroup.getName(), tenantId); + if (!nameIsExists) { + groupId = this.groupDAO.addGroup(groupBroker, tenantId); + GroupManagementDAOFactory.commitTransaction(); + } else { + return -2; + } + } catch (GroupManagementDAOException e) { + GroupManagementDAOFactory.rollbackTransaction(); + throw new GroupManagementException("Error occurred while adding deviceGroup " + + "'" + deviceGroup.getName() + "' to database.", e); + } catch (TransactionManagementException e) { + throw new GroupManagementException("Error occurred while initiating transaction.", e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + if (groupId == -1) { + return -1; + } + addGroupSharingRole(groupBroker.getOwner(), deviceGroup.getName(), defaultRole, defaultPermissions); + if (log.isDebugEnabled()) { + log.debug("DeviceGroup added: " + groupBroker.getName()); + } + return groupId; + } + + /** + * {@inheritDoc} + */ + @Override + public void updateGroup(DeviceGroup deviceGroup) throws GroupManagementException { + if (deviceGroup == null) { + throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException()); + } + try { + GroupManagementDAOFactory.beginTransaction(); + this.groupDAO.updateGroup(deviceGroup, CarbonContext.getThreadLocalCarbonContext().getTenantId()); + GroupManagementDAOFactory.commitTransaction(); + } catch (GroupManagementDAOException e) { + GroupManagementDAOFactory.rollbackTransaction(); + throw new GroupManagementException("Error occurred while modifying deviceGroup " + + "'" + deviceGroup.getName() + "'.", e); + } catch (TransactionManagementException e) { + throw new GroupManagementException("Error occurred while initiating transaction.", e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean deleteGroup(String groupName) throws GroupManagementException { + String roleName; + DeviceGroup deviceGroup = getGroup(groupName); + if (deviceGroup == null) { + return false; + } + List groupRoles = getRoles(groupName); + 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); + } + } catch (DeviceManagementException e) { + throw new GroupManagementException("Error occurred while removing device from group.", e); + } + try { + GroupManagementDAOFactory.beginTransaction(); + this.groupDAO.deleteGroup(groupName, CarbonContext.getThreadLocalCarbonContext().getTenantId()); + GroupManagementDAOFactory.commitTransaction(); + if (log.isDebugEnabled()) { + log.debug("DeviceGroup " + deviceGroup.getName() + " removed."); + } + return true; + } catch (GroupManagementDAOException e) { + GroupManagementDAOFactory.rollbackTransaction(); + throw new GroupManagementException("Error occurred while removing group " + + "'" + groupName + "' data.", e); + } catch (TransactionManagementException e) { + throw new GroupManagementException("Error occurred while initiating transaction.", e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public DeviceGroup getGroup(String groupName) throws GroupManagementException { + DeviceGroupBuilder groupBroker; + try { + GroupManagementDAOFactory.openConnection(); + groupBroker = this.groupDAO.getGroup(groupName, CarbonContext.getThreadLocalCarbonContext().getTenantId()); + } catch (GroupManagementDAOException e) { + throw new GroupManagementException("Error occurred while obtaining group " + groupName, 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)); + return groupBroker.getGroup(); + } else { + return null; + } + } + + /** + * {@inheritDoc} + */ + @Override + public List findGroups(String groupName, String owner) throws GroupManagementException { + List deviceGroups = new ArrayList<>(); + try { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + GroupManagementDAOFactory.openConnection(); + deviceGroups = this.groupDAO.getGroups(groupName, tenantId); + } catch (GroupManagementDAOException e) { + throw new GroupManagementException("Error occurred while finding group " + groupName, 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.getName())); + groupBroker.setRoles(this.getRoles(groupBroker.getName())); + groupsWithData.add(groupBroker.getGroup()); + } + return groupsWithData; + } + + /** + * {@inheritDoc} + */ + @Override + public List getGroups(String username) throws GroupManagementException { + UserStoreManager userStoreManager; + try { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) + .getUserStoreManager(); + String[] roleList = userStoreManager.getRoleListOfUser(username); + 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); + } + } + } + return new ArrayList<>(groups.values()); + } catch (UserStoreException e) { + throw new GroupManagementException("Error occurred while getting user store manager.", e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public int getGroupCount(String username) throws GroupManagementException { + return this.getGroups(username).size(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean shareGroup(String username, String groupName, String sharingRole) + throws GroupManagementException { + return modifyGroupShare(username, groupName, sharingRole, true); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean unshareGroup(String username, String groupName, 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); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean addGroupSharingRole(String username, String groupName, String roleName, + String[] permissions) + throws GroupManagementException { + UserStoreManager userStoreManager; + String role; + String[] userNames = 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(); + role = "Internal/group-" + groupName + "-" + roleName; + userNames[0] = username; + Permission[] carbonPermissions = new Permission[permissions.length]; + for (int i = 0; i < permissions.length; i++) { + carbonPermissions[i] = new Permission(permissions[i], CarbonConstants.UI_PERMISSION_ACTION); + } + 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); + throw new GroupManagementException(errorMsg, e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean removeGroupSharingRole(String groupName, String roleName) + throws GroupManagementException { + UserStoreManager userStoreManager; + String role; + try { + DeviceGroup deviceGroup = getGroup(groupName); + if (deviceGroup == null) { + return false; + } + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) + .getUserStoreManager(); + role = "Internal/group-" + groupName + "-" + roleName; + userStoreManager.deleteRole(role); + return true; + } catch (UserStoreException userStoreEx) { + String errorMsg = "User store error in adding role to group id:" + groupName; + log.error(errorMsg, userStoreEx); + throw new GroupManagementException(errorMsg, userStoreEx); + } + } + + /** + * {@inheritDoc} + */ + @Override + public List getRoles(String groupName) throws GroupManagementException { + UserStoreManager userStoreManager; + String[] roles; + List groupRoles; + try { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) + .getUserStoreManager(); + 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 + "-", "")); + } + } + return groupRoles; + } catch (UserStoreException userStoreEx) { + String errorMsg = "User store error in adding role to group id:" + groupName; + log.error(errorMsg, userStoreEx); + throw new GroupManagementException(errorMsg, userStoreEx); + } + } + + /** + * {@inheritDoc} + */ + @Override + public List getRoles(String username, String groupName) throws GroupManagementException { + UserStoreManager userStoreManager; + List groupRoleList = new ArrayList<>(); + try { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) + .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 + "-", ""); + groupRoleList.add(roleName); + } + } + return groupRoleList; + } catch (UserStoreException e) { + throw new GroupManagementException("Error occurred while getting user store manager.", e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public List getUsers(String groupName) 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); + for (String role : rolesForGroup) { + String[] users = userStoreManager.getUserListOfRole("Internal/group-" + groupName + "-" + role); + for (String user : users) { + GroupUser groupUser; + if (groupUserHashMap.containsKey(user)) { + groupUser = groupUserHashMap.get(user); + groupUser.getGroupRoles().add(role); + } else { + groupUser = new GroupUser(); + groupUser.setUsername(user); + groupUser.setGroupRoles(new ArrayList()); + groupUser.getGroupRoles().add(role); + groupUserHashMap.put(user, groupUser); + } + } + } + return new ArrayList<>(groupUserHashMap.values()); + } catch (UserStoreException e) { + String errorMsg = "User store error in fetching user list for group id:" + groupName; + log.error(errorMsg, e); + throw new GroupManagementException(errorMsg, e); + } + } + + /** + * {@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); +// } + } + + /** + * {@inheritDoc} + */ + @Override + public PaginationResult getDevices(String groupName, 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); +// } + } + + /** + * {@inheritDoc} + */ + @Override + public int getDeviceCount(String groupName) throws GroupManagementException { + try { + int count; + GroupManagementDAOFactory.beginTransaction(); + count = groupDAO.getDeviceCount(groupName, + 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); + } catch (TransactionManagementException e) { + throw new GroupManagementException("Error occurred while initiating transaction.", e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean addDevice(DeviceIdentifier deviceId, String groupName) + throws GroupManagementException { + Device device; + DeviceGroup deviceGroup; + try { + device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId); + deviceGroup = this.getGroup(groupName); + if (device == null || deviceGroup == null) { + return false; + } + DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().modifyEnrollment(device); + } catch (DeviceManagementException e) { + throw new GroupManagementException("Error occurred while adding device in to deviceGroup.", e); + } + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean removeDevice(DeviceIdentifier deviceId, String groupName) + throws GroupManagementException { + Device device; + DeviceGroup deviceGroup; + try { + device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId); + deviceGroup = this.getGroup(groupName); + if (device == null || deviceGroup == null) { + return false; + } + DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().modifyEnrollment(device); + } catch (DeviceManagementException e) { + throw new GroupManagementException("Error occurred while removing device from deviceGroup.", e); + } + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public String[] getPermissions(String username, String groupName) throws GroupManagementException { + UserRealm userRealm; + List roles = getRoles(username, groupName); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); + List lstPermissions = new ArrayList<>(); + String[] resourceIds = userRealm.getAuthorizationManager().getAllowedUIResourcesForUser(username, "/"); + if (resourceIds != null) { + for (String resourceId : resourceIds) { + for (String roleName : roles) { + if (userRealm.getAuthorizationManager(). + isRoleAuthorized("Internal/group-" + groupName + "-" + roleName, resourceId, + CarbonConstants.UI_PERMISSION_ACTION)) { + lstPermissions.add(resourceId); + } + } + } + } + String[] permissions = lstPermissions.toArray(new String[lstPermissions.size()]); + return UserCoreUtil.optimizePermissions(permissions); + } catch (UserStoreException e) { + throw new GroupManagementException("Error occurred while getting user realm.", e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public List getGroups(String username, String permission) + throws GroupManagementException { + UserRealm userRealm; + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + 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); + } + } + } + return new ArrayList<>(groups.values()); + } catch (UserStoreException e) { + throw new GroupManagementException("Error occurred while getting user realm.", e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isAuthorized(String username, String groupName, String permission) + throws GroupManagementException { + UserRealm userRealm; + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); + List roles = this.getRoles(username, groupName); + for (String role : roles) { + if (userRealm.getAuthorizationManager() + .isRoleAuthorized("Internal/group-" + groupName + "-" + role, permission, + CarbonConstants.UI_PERMISSION_ACTION)) { + return true; + } + } + return false; + } catch (UserStoreException e) { + throw new GroupManagementException("Error occurred while getting user realm.", e); + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index dd68cf7a85..629787f529 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -168,12 +168,6 @@ public final class DeviceManagerUtil { return propertiesMap; } - public static int getTenantId() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - return ctx.getTenantId(); - } - - public static List convertDevices(List devices) { List deviceIdentifiers = new ArrayList<>();