Fixed EMM-945, EMM-910, EMM-911, EMM-870

4.x.x
harshanl 9 years ago
parent 3608df2981
commit 026a7c187a

@ -0,0 +1,61 @@
/*
* 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.common.authorization;
/**
* Custom exception class which wraps exceptions occurred inside DeviceAccessAuthorization service.
*/
public class DeviceAccessAuthorizationException extends Exception {
private static final long serialVersionUID = -3151279331929070297L;
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public DeviceAccessAuthorizationException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public DeviceAccessAuthorizationException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public DeviceAccessAuthorizationException(String msg) {
super(msg);
setErrorMessage(msg);
}
public DeviceAccessAuthorizationException() {
super();
}
public DeviceAccessAuthorizationException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,79 @@
/*
* 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.common.authorization;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import java.util.List;
/**
* This represents the contract of DeviceAccessAuthorization service which will be used to check the authorization when
* accessing the device information and performing MDM operations on devices.
*/
public interface DeviceAccessAuthorizationService {
/**
* This method will check whether the currently logged-in user has the access to the device identified by the given
* DeviceIdentifier.
*
* @param deviceIdentifier - DeviceIdentifier of the device to be checked.
* @return Boolean authorization result.
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
*/
boolean isUserAuthorized(DeviceIdentifier deviceIdentifier) throws DeviceAccessAuthorizationException;
/**
* This method will check whether the currently logged-in user has the access to the devices identified by the given
* DeviceIdentifier list.
*
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices &
* unauthorized devices.
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
*/
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers) throws
DeviceAccessAuthorizationException;
/**
* This method will check whether the given user has the access to the device identified by the given
* DeviceIdentifier.
*
* @param deviceIdentifier - DeviceIdentifier of the device to be checked.
* @param username - Username of the user to be checked for authorization.
* @return Boolean authorization result.
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
*/
boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String username) throws
DeviceAccessAuthorizationException;
/**
* This method will check whether the given user has the access to the devices identified by the given
* DeviceIdentifier list.
*
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
* @param username - Username of the user to be checked for authorization.
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices &
* unauthorized devices.
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
*/
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username) throws
DeviceAccessAuthorizationException;
}

@ -0,0 +1,58 @@
/*
* 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.common.authorization;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a DeviceAuthorizationResult including a list of authorized devices and a list of unauthorized devices.
*/
public class DeviceAuthorizationResult {
private List<DeviceIdentifier> authorizedDevices = new ArrayList<>();
private List<DeviceIdentifier> unauthorizedDevices = new ArrayList<>();
public List<DeviceIdentifier> getAuthorizedDevices() {
return authorizedDevices;
}
public void setAuthorizedDevices(List<DeviceIdentifier> authorizedDevices) {
this.authorizedDevices = authorizedDevices;
}
public void setUnauthorizedDevices(
List<DeviceIdentifier> unauthorizedDevices) {
this.unauthorizedDevices = unauthorizedDevices;
}
public void addAuthorizedDevice(DeviceIdentifier deviceIdentifier) {
authorizedDevices.add(deviceIdentifier);
}
public List<DeviceIdentifier> getUnauthorizedDevices() {
return unauthorizedDevices;
}
public void addUnauthorizedDevice(DeviceIdentifier deviceIdentifier) {
unauthorizedDevices.add(deviceIdentifier);
}
}

@ -31,7 +31,8 @@ public interface TenantConfigurationManagementService {
* @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while adding the
* configuration.
*/
public boolean saveConfiguration(TenantConfiguration tenantConfiguration, String resourcePath) throws ConfigurationManagementException;
boolean saveConfiguration(TenantConfiguration tenantConfiguration, String resourcePath) throws
ConfigurationManagementException;
/**
* Method to retrieve the list of general tenant configurations.
@ -40,6 +41,6 @@ public interface TenantConfigurationManagementService {
* @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while fetching the
* operation list.
*/
public TenantConfiguration getConfiguration(String resourcePath) throws ConfigurationManagementException;
TenantConfiguration getConfiguration(String resourcePath) throws ConfigurationManagementException;
}

@ -25,12 +25,50 @@ import java.util.List;
*/
public interface NotificationManagementService {
public boolean addNotification(Notification notification) throws NotificationManagementException;
public boolean updateNotification(Notification notification) throws NotificationManagementException;
public boolean updateNotificationStatus(int notificationId, Notification.Status status) throws
/**
* Method to add a notification to the database.
*
* @param notification - Notification to be added to database.
* @return boolean status of the operation.
* @throws NotificationManagementException if something goes wrong while adding the Notification.
*/
boolean addNotification(Notification notification) throws NotificationManagementException;
/**
* Method to update a notification in the database.
*
* @param notification - Notification to be updated in the database.
* @return boolean status of the operation.
* @throws NotificationManagementException if something goes wrong while updating the Notification.
*/
boolean updateNotification(Notification notification) throws NotificationManagementException;
/**
* Method to update the notification status of a Notification in the database.
*
* @param notificationId - Notification id of the notification to be updated.
* @param status - New notification status.
* @return boolean status of the operation.
* @throws NotificationManagementException if something goes wrong while updating the Notification.
*/
boolean updateNotificationStatus(int notificationId, Notification.Status status) throws
NotificationManagementException;
public List<Notification> getAllNotifications() throws NotificationManagementException;
public List<Notification> getNotificationsByStatus(Notification.Status status) throws
/**
* Method to fetch all the notifications in the database.
*
* @return List of all Notifications in the database.
* @throws NotificationManagementException
*/
List<Notification> getAllNotifications() throws NotificationManagementException;
/**
*
* @param status - Status of the notifications to be fetched from database.
* @return A list of notifications matching the given status.
* @throws NotificationManagementException if something goes wrong while fetching the Notification.
*/
List<Notification> getNotificationsByStatus(Notification.Status status) throws
NotificationManagementException;
}

@ -36,7 +36,7 @@ public interface OperationManager {
* @throws OperationManagementException If some unusual behaviour is observed while adding the
* operation
*/
public int addOperation(Operation operation, List<DeviceIdentifier> devices) throws OperationManagementException;
int addOperation(Operation operation, List<DeviceIdentifier> devices) throws OperationManagementException;
/**
* Method to retrieve the list of all operations to a device.
@ -45,7 +45,7 @@ public interface OperationManager {
* @throws OperationManagementException If some unusual behaviour is observed while fetching the
* operation list.
*/
public List<? extends Operation> getOperations(DeviceIdentifier deviceId) throws OperationManagementException;
List<? extends Operation> getOperations(DeviceIdentifier deviceId) throws OperationManagementException;
/**
* Method to retrieve the list of available operations to a device.
@ -54,21 +54,22 @@ public interface OperationManager {
* @throws OperationManagementException If some unusual behaviour is observed while fetching the
* operation list.
*/
public List<? extends Operation> getPendingOperations(
List<? extends Operation> getPendingOperations(
DeviceIdentifier deviceId) throws OperationManagementException;
public Operation getNextPendingOperation(DeviceIdentifier deviceId) throws OperationManagementException;
Operation getNextPendingOperation(DeviceIdentifier deviceId) throws OperationManagementException;
public void updateOperation(DeviceIdentifier deviceId, Operation operation) throws OperationManagementException;
void updateOperation(DeviceIdentifier deviceId, Operation operation) throws OperationManagementException;
public void deleteOperation(int operationId) throws OperationManagementException;
void deleteOperation(int operationId) throws OperationManagementException;
public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId)
Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId)
throws OperationManagementException;
public List<? extends Operation> getOperationsByDeviceAndStatus(DeviceIdentifier identifier,
Operation.Status status) throws OperationManagementException, DeviceManagementException;
List<? extends Operation> getOperationsByDeviceAndStatus(DeviceIdentifier identifier,
Operation.Status status)
throws OperationManagementException, DeviceManagementException;
public Operation getOperation(int operationId) throws OperationManagementException;
Operation getOperation(int operationId) throws OperationManagementException;
}

@ -33,7 +33,7 @@ public interface PermissionManagerService {
* @throws PermissionManagementException If some unusual behaviour is observed while adding the
* permission.
*/
public boolean addPermission(Permission permission) throws PermissionManagementException;
boolean addPermission(Permission permission) throws PermissionManagementException;
/**
*
@ -42,6 +42,6 @@ public interface PermissionManagerService {
* @throws PermissionManagementException If some unusual behaviour is observed while fetching the
* permission.
*/
public Permission getPermission(Properties properties) throws PermissionManagementException;
Permission getPermission(Properties properties) throws PermissionManagementException;
}

@ -24,10 +24,10 @@ import java.util.List;
public interface ApplicationManagementProviderService extends ApplicationManager {
public void updateApplicationListInstalledInDevice(DeviceIdentifier deviceIdentifier,
void updateApplicationListInstalledInDevice(DeviceIdentifier deviceIdentifier,
List<Application> applications) throws ApplicationManagementException;
public List<Application> getApplicationListForDevice(DeviceIdentifier deviceIdentifier)
List<Application> getApplicationListForDevice(DeviceIdentifier deviceIdentifier)
throws ApplicationManagementException;
}

@ -0,0 +1,262 @@
/*
* 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.authorization;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
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.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAuthorizationResult;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implementation of DeviceAccessAuthorization service.
*/
public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthorizationService {
private final static String EMM_ADMIN_PERMISSION = "/device-mgt/admin-device-access";
private static Log log = LogFactory.getLog(DeviceAccessAuthorizationServiceImpl.class);
public static final class PermissionMethod {
private PermissionMethod() {
throw new AssertionError();
}
public static final String READ = "read";
public static final String WRITE = "write";
public static final String DELETE = "delete";
public static final String ACTION = "action";
public static final String UI_EXECUTE = "ui.execute";
}
public DeviceAccessAuthorizationServiceImpl() {
try {
this.addAdminPermissionToRegistry();
} catch (PermissionManagementException e) {
log.error("Unable to add the emm-admin permission to the registry.", e);
}
}
@Override
public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier) throws DeviceAccessAuthorizationException {
boolean status;
String username = this.getUserName();
int tenantId = this.getTenantId();
if (username == null || username.isEmpty()) {
return false;
}
try {
//Check for admin users. If the user is an admin user we authorize the access to that device.
status = isAdminUser(username, tenantId);
} catch (UserStoreException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
deviceIdentifier.getId() + " for the user : " + username, e);
}
//Check for device ownership. If the user is the owner of the device we allow the access.
if (!status) {
try {
Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
getDevice(deviceIdentifier);
EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) {
status = true;
}
} catch (DeviceManagementException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
deviceIdentifier.getId() + " for the user : " + username, e);
}
}
return status;
}
@Override
public DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers) throws
DeviceAccessAuthorizationException {
boolean status;
DeviceAuthorizationResult deviceAuthorizationResult = new DeviceAuthorizationResult();
String username = this.getUserName();
int tenantId = this.getTenantId();
if (username == null || username.isEmpty()) {
return deviceAuthorizationResult;
}
try {
//Check for admin users. If the user is an admin user we authorize the access to that device.
status = isAdminUser(username, tenantId);
} catch (UserStoreException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : " +
username, e);
}
//Check for device ownership. If the user is the owner of the device we allow the access.
if (!status) {
try {
//Get the list of devices of the user
List<Device> devicesOfUser = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
getDevicesOfUser(username);
//Convert device-list to a Map
Map<String, String> ownershipData = this.getOwnershipOfDevices(devicesOfUser);
for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
if (ownershipData.containsKey(deviceIdentifier.getId())) {
deviceAuthorizationResult.addAuthorizedDevice(deviceIdentifier);
} else {
deviceAuthorizationResult.addUnauthorizedDevice(deviceIdentifier);
}
}
} catch (DeviceManagementException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : "
+ username, e);
}
} else {
deviceAuthorizationResult.setAuthorizedDevices(deviceIdentifiers);
}
return deviceAuthorizationResult;
}
@Override
public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String username)
throws DeviceAccessAuthorizationException {
boolean status;
int tenantId = this.getTenantId();
if (username == null || username.isEmpty()) {
return false;
}
try {
//Check for admin users. If the user is an admin user we authorize the access to that device.
status = isAdminUser(username, tenantId);
} catch (UserStoreException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
deviceIdentifier.getId() + " for the user : " + username, e);
}
//Check for device ownership. If the user is the owner of the device we allow the access.
if (!status) {
try {
Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
getDevice(deviceIdentifier);
EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) {
status = true;
}
} catch (DeviceManagementException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
deviceIdentifier.getId() + " for the user : " + username, e);
}
}
return status;
}
@Override
public DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username)
throws DeviceAccessAuthorizationException {
boolean status;
int tenantId = this.getTenantId();
DeviceAuthorizationResult deviceAuthorizationResult = new DeviceAuthorizationResult();
if (username == null || username.isEmpty()) {
return null;
}
try {
//Check for admin users. If the user is an admin user we authorize the access to that device.
status = isAdminUser(username, tenantId);
} catch (UserStoreException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : " +
username, e);
}
//Check for device ownership. If the user is the owner of the device we allow the access.
if (!status) {
try {
Device device;
EnrolmentInfo enrolmentInfo;
for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
getDevice(deviceIdentifier);
enrolmentInfo = device.getEnrolmentInfo();
if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) {
deviceAuthorizationResult.addAuthorizedDevice(deviceIdentifier);
} else {
deviceAuthorizationResult.addUnauthorizedDevice(deviceIdentifier);
}
}
} catch (DeviceManagementException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : "
+ username, e);
}
} else {
deviceAuthorizationResult.setAuthorizedDevices(deviceIdentifiers);
}
return deviceAuthorizationResult;
}
private boolean isAdminUser(String username, int tenantId) throws UserStoreException {
UserRealm userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
if (userRealm != null && userRealm.getAuthorizationManager() != null) {
return userRealm.getAuthorizationManager()
.isUserAuthorized(username, PermissionUtils.getAbsolutePermissionPath(EMM_ADMIN_PERMISSION),
PermissionMethod.UI_EXECUTE);
}
return false;
}
private String getUserName() {
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String tenantDomain = MultitenantUtils.getTenantDomain(username);
if (username.endsWith(tenantDomain)) {
return username.substring(0, username.lastIndexOf("@"));
}
return username;
}
private int getTenantId() {
return PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
}
private boolean addAdminPermissionToRegistry() throws PermissionManagementException {
Permission permission = new Permission();
permission.setPath(PermissionUtils.getAbsolutePermissionPath(EMM_ADMIN_PERMISSION));
return PermissionUtils.putPermission(permission);
}
private Map<String, String> getOwnershipOfDevices(List<Device> devices) {
Map<String, String> ownershipData = new HashMap<>();
EnrolmentInfo enrolmentInfo;
String owner;
for (Device device : devices) {
enrolmentInfo = device.getEnrolmentInfo();
if (enrolmentInfo != null) {
owner = enrolmentInfo.getOwner();
if (owner != null && !owner.isEmpty()) {
ownershipData.put(device.getDeviceIdentifier(), owner);
}
}
}
return ownershipData;
}
}

@ -69,7 +69,8 @@ public class WebAppDeploymentLifecycleListener implements LifecycleListener {
// update the permission path to absolute permission path
permission.setPath(PermissionUtils.getAbsolutePermissionPath(permission.getPath()));
permission.setUrl(PermissionUtils.getAbsoluteContextPathOfAPI(contextPath, apiVersion,
permission.getUrl()));
permission.getUrl()).toLowerCase());
permission.setMethod(permission.getMethod().toUpperCase());
PermissionManagerServiceImpl.getInstance().addPermission(permission);
}
}

@ -76,7 +76,7 @@ public interface DeviceDAO {
int removeDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve a device of a given device-identifier.
* This method is used to retrieve a device of a given device-identifier and tenant-id.
*
* @param deviceIdentifier device id.
* @param tenantId tenant id.
@ -85,6 +85,18 @@ public interface DeviceDAO {
*/
Device getDevice(DeviceIdentifier deviceIdentifier, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve a device of a given device-identifier, enrollment status and tenant-id.
*
* @param deviceIdentifier device id.
* @param status enrollment status.
* @param tenantId tenant id.
* @return returns the device object.
* @throws DeviceManagementDAOException
*/
Device getDevice(DeviceIdentifier deviceIdentifier, EnrolmentInfo.Status status,int tenantId)
throws DeviceManagementDAOException;
/**
*
* @param deviceIdentifier device id.

@ -110,8 +110,8 @@ public class DeviceManagementDAOFactory {
return new DeviceTypeDAOImpl();
}
public static EnrolmentDAO getEnrollmentDAO() {
return new EnrolmentDAOImpl();
public static EnrollmentDAO getEnrollmentDAO() {
return new EnrollmentDAOImpl();
}
public static ApplicationDAO getApplicationDAO() {

@ -21,13 +21,17 @@ package org.wso2.carbon.device.mgt.core.dao;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo.Status;
public interface EnrolmentDAO {
import java.util.List;
public interface EnrollmentDAO {
int addEnrollment(int deviceId, EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementDAOException;
int updateEnrollment(int deviceId, EnrolmentInfo enrolmentInfo,
int tenantId) throws DeviceManagementDAOException;
int updateEnrollment(EnrolmentInfo enrolmentInfo) throws DeviceManagementDAOException;
int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException;
boolean setStatus(int deviceId, String currentOwner, Status status,
@ -35,6 +39,9 @@ public interface EnrolmentDAO {
Status getStatus(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException;
EnrolmentInfo getEnrolment(int deviceId, String currentUser, int tenantId) throws DeviceManagementDAOException;
EnrolmentInfo getEnrollment(int deviceId, String currentUser, int tenantId) throws DeviceManagementDAOException;
List<EnrolmentInfo> getEnrollmentsOfUser(int deviceId, String user, int tenantId) throws
DeviceManagementDAOException;
}

@ -121,6 +121,40 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
stmt.setInt(3, tenantId);
stmt.setInt(4, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
device = DeviceManagementDAOUtil.loadMatchingDevice(rs);
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while listing devices for type " +
"'" + deviceIdentifier.getType() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return device;
}
@Override
public Device getDevice(DeviceIdentifier deviceIdentifier, EnrolmentInfo.Status status, int tenantId) throws
DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
Device device = null;
try {
conn = this.getConnection();
String sql = "SELECT d1.ID AS 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 d.ID, d.DESCRIPTION, d.NAME, " +
"t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " +
"t.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " +
"AND TENANT_ID = ? AND e.STATUS = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceIdentifier.getType());
stmt.setString(2, deviceIdentifier.getId());
stmt.setInt(3, tenantId);
stmt.setInt(4, tenantId);
stmt.setString(5, status.toString());
rs = stmt.executeQuery();
if (rs.next()) {
device = DeviceManagementDAOUtil.loadDevice(rs);
}

@ -21,13 +21,15 @@ package org.wso2.carbon.device.mgt.core.dao.impl;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.EnrolmentDAO;
import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class EnrolmentDAOImpl implements EnrolmentDAO {
public class EnrollmentDAOImpl implements EnrollmentDAO {
@Override
public int addEnrollment(int deviceId, EnrolmentInfo enrolmentInfo,
@ -68,11 +70,12 @@ public class EnrolmentDAOImpl implements EnrolmentDAO {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int enrolmentId = -1;
int status = -1;
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, " +
"DATE_OF_ENROLMENT = ?, DATE_OF_LAST_UPDATE = ? WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?";
"DATE_OF_ENROLMENT = ?, DATE_OF_LAST_UPDATE = ? WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?" +
" AND ID = ?";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, enrolmentInfo.getOwnership().toString());
stmt.setString(2, enrolmentInfo.getStatus().toString());
@ -81,13 +84,14 @@ public class EnrolmentDAOImpl implements EnrolmentDAO {
stmt.setInt(5, deviceId);
stmt.setString(6, enrolmentInfo.getOwner());
stmt.setInt(7, tenantId);
stmt.setInt(8, enrolmentInfo.getId());
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
enrolmentId = rs.getInt(1);
status = 1;
}
return enrolmentId;
return status;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e);
} finally {
@ -95,13 +99,44 @@ public class EnrolmentDAOImpl implements EnrolmentDAO {
}
}
@Override
public int updateEnrollment(EnrolmentInfo enrolmentInfo) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int status = -1;
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, " +
"DATE_OF_ENROLMENT = ?, DATE_OF_LAST_UPDATE = ? WHERE ID = ?";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, enrolmentInfo.getOwnership().toString());
stmt.setString(2, enrolmentInfo.getStatus().toString());
stmt.setTimestamp(3, new Timestamp(enrolmentInfo.getDateOfEnrolment()));
stmt.setTimestamp(4, new Timestamp(new Date().getTime()));
stmt.setInt(5, enrolmentInfo.getId());
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
status = 1;
}
return status;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public int removeEnrollment(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int enrolmentId = -1;
int status = -1;
try {
conn = this.getConnection();
String sql = "DELETE DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?";
@ -113,9 +148,9 @@ public class EnrolmentDAOImpl implements EnrolmentDAO {
rs = stmt.getGeneratedKeys();
if (rs.next()) {
enrolmentId = rs.getInt(1);
status = 1;
}
return enrolmentId;
return status;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while removing device enrolment", e);
} finally {
@ -172,7 +207,7 @@ public class EnrolmentDAOImpl implements EnrolmentDAO {
}
@Override
public EnrolmentInfo getEnrolment(int deviceId, String currentOwner,
public EnrolmentInfo getEnrollment(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
@ -199,6 +234,36 @@ public class EnrolmentDAOImpl implements EnrolmentDAO {
}
}
@Override
public List<EnrolmentInfo> getEnrollmentsOfUser(int deviceId, String user, int tenantId)
throws DeviceManagementDAOException {
List<EnrolmentInfo> enrolmentInfos = new ArrayList<>();
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
EnrolmentInfo enrolmentInfo = null;
try {
conn = this.getConnection();
String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " +
"DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setString(2, user);
stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
while (rs.next()) {
enrolmentInfo = this.loadEnrolment(rs);
enrolmentInfos.add(enrolmentInfo);
}
return enrolmentInfos;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the enrolments " +
"information of user '" + user + "' upon device '" + deviceId + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}
@ -210,6 +275,7 @@ public class EnrolmentDAOImpl implements EnrolmentDAO {
enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime());
enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS")));
enrolmentInfo.setId(rs.getInt("ID"));
return enrolmentInfo;
}

@ -35,7 +35,9 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public final class DeviceManagementDAOUtil {
@ -155,6 +157,43 @@ public final class DeviceManagementDAOUtil {
return device;
}
//This method will retrieve most appropriate device information when there are multiple device enrollments for
//a single device. We'll give the highest priority to active devices.
public static Device loadMatchingDevice(ResultSet rs) throws SQLException {
Map<EnrolmentInfo.Status, Device> deviceMap = new HashMap<>();
Device device = loadDevice(rs);
if (EnrolmentInfo.Status.ACTIVE.equals(device.getEnrolmentInfo().getStatus())) {
return device;
}
while (rs.next()) {
device = loadDevice(rs);
if (EnrolmentInfo.Status.ACTIVE.equals(device.getEnrolmentInfo().getStatus())) {
return device;
}
if (device.getEnrolmentInfo() != null) {
deviceMap.put(device.getEnrolmentInfo().getStatus(), device);
}
}
if (deviceMap.containsKey(EnrolmentInfo.Status.INACTIVE)) {
return deviceMap.get(EnrolmentInfo.Status.INACTIVE);
} else if (deviceMap.containsKey(EnrolmentInfo.Status.UNREACHABLE)) {
return deviceMap.get(EnrolmentInfo.Status.UNREACHABLE);
} else if (deviceMap.containsKey(EnrolmentInfo.Status.DISENROLLMENT_REQUESTED)) {
return deviceMap.get(EnrolmentInfo.Status.DISENROLLMENT_REQUESTED);
} else if (deviceMap.containsKey(EnrolmentInfo.Status.CREATED)) {
return deviceMap.get(EnrolmentInfo.Status.CREATED);
} else if (deviceMap.containsKey(EnrolmentInfo.Status.REMOVED)) {
return deviceMap.get(EnrolmentInfo.Status.REMOVED);
} else if (deviceMap.containsKey(EnrolmentInfo.Status.UNCLAIMED)) {
return deviceMap.get(EnrolmentInfo.Status.UNCLAIMED);
} else if (deviceMap.containsKey(EnrolmentInfo.Status.SUSPENDED)) {
return deviceMap.get(EnrolmentInfo.Status.SUSPENDED);
} else if (deviceMap.containsKey(EnrolmentInfo.Status.BLOCKED)) {
return deviceMap.get(EnrolmentInfo.Status.BLOCKED);
}
return device;
}
public static DeviceType loadDeviceType(ResultSet rs) throws SQLException {
DeviceType deviceType = new DeviceType();
deviceType.setId(rs.getInt("ID"));

@ -19,6 +19,7 @@
package org.wso2.carbon.device.mgt.core.internal;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig;
@ -41,6 +42,7 @@ public class DeviceManagementDataHolder {
private AppManagementConfig appManagerConfig;
private OperationManager operationManager;
private ConfigurationContextService configurationContextService;
private DeviceAccessAuthorizationService deviceAccessAuthorizationService;
private static DeviceManagementDataHolder thisInstance = new DeviceManagementDataHolder();
@ -143,4 +145,12 @@ public class DeviceManagementDataHolder {
this.configurationContextService = configurationContextService;
}
public DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() {
return deviceAccessAuthorizationService;
}
public void setDeviceAccessAuthorizationService(
DeviceAccessAuthorizationService deviceAccessAuthorizationService) {
this.deviceAccessAuthorizationService = deviceAccessAuthorizationService;
}
}

@ -24,6 +24,7 @@ import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
@ -36,6 +37,7 @@ import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderServ
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagerProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig;
import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfigurationManager;
import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
@ -194,6 +196,12 @@ public class DeviceManagementServiceComponent {
= PermissionManagerServiceImpl.getInstance();
bundleContext.registerService(PermissionManagerService.class.getName(), permissionManagerService, null);
/* Registering DeviceAccessAuthorization Service */
DeviceAccessAuthorizationService deviceAccessAuthorizationService = new DeviceAccessAuthorizationServiceImpl();
DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(deviceAccessAuthorizationService);
bundleContext.registerService(DeviceAccessAuthorizationService.class.getName(),
deviceAccessAuthorizationService, null);
/* Registering App Management service */
try {
AppManagementConfigurationManager.getInstance().initConfig();

@ -24,12 +24,14 @@ import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationDAO;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
@ -79,6 +81,10 @@ public class OperationManagerImpl implements OperationManager {
deviceIdentifier.getType() + "]");
}
}
try {
List<DeviceIdentifier> authorizedDeviceList = DeviceManagementDataHolder.getInstance().
getDeviceAccessAuthorizationService().isUserAuthorized(deviceIds).getAuthorizedDevices();
if (authorizedDeviceList.size() > 0) {
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
List<EnrolmentInfo> enrolments;
@ -95,9 +101,7 @@ public class OperationManagerImpl implements OperationManager {
OperationManagementDAOFactory.beginTransaction();
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto =
OperationDAOUtil.convertOperation(operation);
int operationId = this.lookupOperationDAO(operation).addOperation(operationDto);
for (EnrolmentInfo enrolmentInfo : enrolments) {
operationMappingDAO.addOperationMapping(operationId, enrolmentInfo.getId());
}
@ -114,12 +118,24 @@ public class OperationManagerImpl implements OperationManager {
} finally {
OperationManagementDAOFactory.closeConnection();
}
} else {
log.info("User : " + getUser() + " is not authorized to perform operations on given device-list.");
}
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" +
this.getUser(), e);
}
return -1;
}
@Override
public List<? extends Operation> getOperations(DeviceIdentifier deviceId) throws OperationManagementException {
int enrolmentId;
List<Operation> operations = new ArrayList<>();
try {
boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
isUserAuthorized(deviceId);
if (isUserAuthorized) {
try {
try {
DeviceManagementDAOFactory.openConnection();
@ -130,10 +146,10 @@ public class OperationManagerImpl implements OperationManager {
}
OperationManagementDAOFactory.openConnection();
if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for given device " +
"Identifier:" + deviceId.getId() + " and given type" + deviceId.getType());
"Identifier:" + deviceId.getId() + " and given type" +
deviceId.getType());
}
List<? extends org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> operationList =
operationDAO.getOperationsForDevice(enrolmentId);
@ -142,24 +158,33 @@ public class OperationManagerImpl implements OperationManager {
Operation operation = OperationDAOUtil.convertOperation(dtoOperation);
operations.add(operation);
}
return operations;
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
"operations assigned for '" + deviceId.getType() + "' device '" + deviceId.getId() + "'", e);
"operations assigned for '" + deviceId.getType() +
"' device '" + deviceId.getId() + "'", e);
} catch (DeviceManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving metadata of '" +
deviceId.getType() + "' device carrying the identifier '" + deviceId.getId() + "'");
deviceId.getType() + "' device carrying the identifier '" +
deviceId.getId() + "'");
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
throw new OperationManagementException(
"Error occurred while opening a connection to the data source", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
} else {
log.info("User : " + getUser() + " is not authorized to fetch operations on device : " + deviceId.getId());
}
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while authorizing access to the devices for user : " +
this.getUser(), e);
}
return operations;
}
@Override
public List<? extends Operation> getPendingOperations(
DeviceIdentifier deviceId) throws OperationManagementException {
public List<? extends Operation> getPendingOperations(DeviceIdentifier deviceId) throws
OperationManagementException {
if (log.isDebugEnabled()) {
log.debug("Device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType() + "]");
}
@ -167,64 +192,73 @@ public class OperationManagerImpl implements OperationManager {
List<Operation> operations = new ArrayList<>();
List<org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> dtoOperationList = new ArrayList<>();
try {
boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
isUserAuthorized(deviceId);
if (isUserAuthorized) {
try {
try {
DeviceManagementDAOFactory.openConnection();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
OperationManagementDAOFactory.openConnection();
if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for the given device Identifier:" +
deviceId.getId() + " and given type:" + deviceId.getType());
deviceId.getId() + " and given type:" +
deviceId.getType());
}
dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus(
enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING));
dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus(
enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING));
dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus(
enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING));
dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus(
enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING));
Operation operation;
for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : dtoOperationList) {
operation = OperationDAOUtil.convertOperation(dtoOperation);
operations.add(operation);
}
Collections.sort(operations, new OperationCreateTimeComparator());
return operations;
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
"pending operations assigned for '" + deviceId.getType() + "' device '" +
deviceId.getId() + "'", e);
"pending operations assigned for '" + deviceId.getType() +
"' device '" + deviceId.getId() + "'", e);
} catch (DeviceManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the device " +
"for device Identifier type -'" + deviceId.getType() + "' and device Id '"
+ deviceId.getId() + "'", e);
"for device Identifier type -'" + deviceId.getType() +
"' and device Id '" + deviceId.getId() + "'", e);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
throw new OperationManagementException(
"Error occurred while opening a connection to the data source", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
} else {
log.info("User : " + getUser() + " is not authorized to fetch operations on device : "
+ deviceId.getId());
}
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" +
this.getUser(), e);
}
return operations;
}
@Override
public Operation getNextPendingOperation(DeviceIdentifier deviceId) throws OperationManagementException {
if (log.isDebugEnabled()) {
log.debug("device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType()
+ "]");
log.debug("device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType() + "]");
}
Operation operation = null;
int enrolmentId;
try {
boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
isUserAuthorized(deviceId);
if (isUserAuthorized) {
try {
try {
DeviceManagementDAOFactory.openConnection();
@ -233,47 +267,55 @@ public class OperationManagerImpl implements OperationManager {
} finally {
DeviceManagementDAOFactory.closeConnection();
}
OperationManagementDAOFactory.openConnection();
if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for given device " +
"Identifier:" + deviceId.getId() + " and given type" + deviceId.getType());
"Identifier:" + deviceId.getId() + " and given type" +
deviceId.getType());
}
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO
.getNextOperation(enrolmentId);
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO.
getNextOperation(enrolmentId);
if (dtoOperation != null) {
if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND
.equals(dtoOperation.getType())) {
if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND.
equals(dtoOperation.getType())) {
org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation;
commandOperation =
(org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO
.getOperation(dtoOperation.getId());
(org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO.
getOperation(dtoOperation.getId());
dtoOperation.setEnabled(commandOperation.isEnabled());
} else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG
.equals(dtoOperation.getType())) {
} else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG.
equals(dtoOperation.getType())) {
dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
} else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE
.equals(dtoOperation.getType())) {
} else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE.
equals(dtoOperation.getType())) {
dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
} else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type
.POLICY.equals(dtoOperation.getType())) {
} else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY.
equals(dtoOperation.getType())) {
dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
}
operation = OperationDAOUtil.convertOperation(dtoOperation);
}
return operation;
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving next pending operation", e);
} catch (DeviceManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the device " +
"for device Identifier type -'" + deviceId.getType() + "' and device Id '" + deviceId.getId(), e);
"for device Identifier type -'" + deviceId.getType() +
"' and device Id '" + deviceId.getId(), e);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
throw new OperationManagementException(
"Error occurred while opening a connection to the data source", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
} else {
log.info("User : " + getUser() + " is not authorized to fetch operations on device : "
+ deviceId.getId());
}
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while authorizing access to the devices for user : " +
this.getUser(), e);
}
return operation;
}
@Override
@ -283,23 +325,26 @@ public class OperationManagerImpl implements OperationManager {
log.debug("operation Id:" + operationId + " status:" + operation.getStatus());
}
int enrolmentId;
try {
boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
isUserAuthorized(deviceId);
if (isUserAuthorized) {
try {
try {
DeviceManagementDAOFactory.openConnection();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
throw new OperationManagementException("Error occurred while opening a connection to the" +
" data source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
OperationManagementDAOFactory.beginTransaction();
if (operation.getStatus() != null) {
operationDAO.updateOperationStatus(enrolmentId, operationId,
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status
.valueOf(operation.getStatus().toString()));
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.
valueOf(operation.getStatus().toString()));
}
if (operation.getOperationResponse() != null) {
operationDAO.addOperationResponse(enrolmentId, operationId, operation.getOperationResponse());
@ -307,31 +352,39 @@ public class OperationManagerImpl implements OperationManager {
OperationManagementDAOFactory.commitTransaction();
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
throw new OperationManagementException("Error occurred while updating the operation: " + operationId +
" status:" + operation.getStatus(), e);
throw new OperationManagementException(
"Error occurred while updating the operation: " + operationId + " status:" +
operation.getStatus(), e);
} catch (DeviceManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
throw new OperationManagementException("Error occurred while fetching the device for device identifier: " +
deviceId.getId() + "type:" + deviceId.getType(), e);
throw new OperationManagementException(
"Error occurred while fetching the device for device identifier: " + deviceId.getId() +
"type:" + deviceId.getType(), e);
} catch (TransactionManagementException e) {
throw new OperationManagementException("Error occurred while initiating a transaction", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
} else {
log.info("User : " + getUser() + " is not authorized to update operations on device : "
+ deviceId.getId());
}
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" +
this.getUser(), e);
}
}
@Override
public void deleteOperation(int operationId) throws OperationManagementException {
try {
OperationManagementDAOFactory.beginTransaction();
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operation =
operationDAO.getOperation(operationId);
if (operation == null) {
throw new OperationManagementException("Operation not found for operation id : " + operationId);
}
lookupOperationDAO(operation).deleteOperation(operationId);
OperationManagementDAOFactory.commitTransaction();
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
@ -347,11 +400,15 @@ public class OperationManagerImpl implements OperationManager {
public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId)
throws OperationManagementException {
int enrolmentId;
Operation operation;
Operation operation = null;
if (log.isDebugEnabled()) {
log.debug("Operation Id: " + operationId + " Device Type: " + deviceId.getType() + " Device Identifier: " +
deviceId.getId());
}
try {
boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
isUserAuthorized(deviceId);
if (isUserAuthorized) {
try {
try {
DeviceManagementDAOFactory.openConnection();
@ -362,23 +419,21 @@ public class OperationManagerImpl implements OperationManager {
}
OperationManagementDAOFactory.openConnection();
if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for given device identifier: " +
deviceId.getId() + " type: " + deviceId.getType());
}
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO
.getOperationByDeviceAndId(enrolmentId, operationId);
if (dtoOperation.getType()
.equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) {
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO.
getOperationByDeviceAndId(enrolmentId, operationId);
if (dtoOperation.getType().
equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) {
org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation;
commandOperation =
(org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO.
getOperation(dtoOperation.getId());
dtoOperation.setEnabled(commandOperation.isEnabled());
} else if (dtoOperation.getType()
.equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) {
} else if (dtoOperation.getType().
equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) {
dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
} else if (dtoOperation.getType().equals(
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE)) {
@ -395,17 +450,26 @@ public class OperationManagerImpl implements OperationManager {
operation = OperationDAOUtil.convertOperation(dtoOperation);
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
"operations assigned for '" + deviceId.getType() + "' device '" + deviceId.getId()
+ "'", e);
"operations assigned for '" + deviceId.getType() +
"' device '" + deviceId.getId() + "'", e);
} catch (DeviceManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the device " +
"for device Identifier type -'" + deviceId.getType() + "' and device Id '" +
deviceId.getId() + "'", e);
"for device Identifier type -'" + deviceId.getType() +
"' and device Id '" + deviceId.getId() + "'", e);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening connection to the data source", e);
throw new OperationManagementException("Error occurred while opening connection to the data source",
e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
} else {
log.info("User : " + getUser() + " is not authorized to fetch operations on device : "
+ deviceId.getId());
}
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" +
this.getUser(), e);
}
return operation;
}
@ -413,9 +477,12 @@ public class OperationManagerImpl implements OperationManager {
public List<? extends Operation> getOperationsByDeviceAndStatus(
DeviceIdentifier deviceId, Operation.Status status) throws OperationManagementException {
List<Operation> operations = new ArrayList<>();
List<org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> dtoOperationList =
new ArrayList<>();
List<org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> dtoOperationList = new ArrayList<>();
int enrolmentId;
try {
boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
isUserAuthorized(deviceId);
if (isUserAuthorized) {
try {
try {
DeviceManagementDAOFactory.openConnection();
@ -427,24 +494,19 @@ public class OperationManagerImpl implements OperationManager {
OperationManagementDAOFactory.openConnection();
if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for device id:" + deviceId.getId() + " " +
"type:" + deviceId.getType());
throw new OperationManagementException(
"Device not found for device id:" + deviceId.getId() + " " + "type:" +
deviceId.getType());
}
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status dtoOpStatus = org.wso2.carbon.device
.mgt.core.dto.operation.mgt.Operation.Status.valueOf(status.toString());
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status dtoOpStatus =
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.valueOf(status.toString());
dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, dtoOpStatus));
dtoOperationList.addAll(
configOperationDAO.getOperationsByDeviceAndStatus(enrolmentId,
dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus(enrolmentId,
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING));
dtoOperationList.addAll(
profileOperationDAO.getOperationsByDeviceAndStatus(enrolmentId,
dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus(enrolmentId,
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING));
dtoOperationList.addAll(
policyOperationDAO.getOperationsByDeviceAndStatus(enrolmentId,
dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus(enrolmentId,
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING));
Operation operation;
@ -453,19 +515,31 @@ public class OperationManagerImpl implements OperationManager {
operation = OperationDAOUtil.convertOperation(dtoOperation);
operations.add(operation);
}
return operations;
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
"operations assigned for '" + deviceId.getType() + "' device '" +
"operations assigned for '" + deviceId.getType() +
"' device '" +
deviceId.getId() + "' and status:" + status.toString(), e);
} catch (DeviceManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the device " +
"for device Identifier type -'" + deviceId.getType() + "' and device Id '" + deviceId.getId(), e);
"for device Identifier type -'" + deviceId.getType() +
"' and device Id '" + deviceId.getId(), e);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
throw new OperationManagementException(
"Error occurred while opening a connection to the data source", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
} else {
log.info("User : " + getUser() + " is not authorized to fetch operations on device : "
+ deviceId.getId());
}
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" +
this.getUser(), e);
}
return operations;
}
@Override
@ -473,29 +547,26 @@ public class OperationManagerImpl implements OperationManager {
Operation operation;
try {
OperationManagementDAOFactory.getConnection();
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO.getOperation
(operationId);
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO.
getOperation(operationId);
if (dtoOperation == null) {
throw new OperationManagementException("Operation not found for given Id:" + operationId);
}
if (dtoOperation.getType()
.equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) {
if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) {
org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation;
commandOperation =
(org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO.
getOperation(dtoOperation.getId());
dtoOperation.setEnabled(commandOperation.isEnabled());
} else if (dtoOperation.getType()
.equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) {
} else if (dtoOperation.getType().
equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) {
dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
} else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type
.PROFILE)) {
} else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.
PROFILE)) {
dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
} else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type
.POLICY)) {
} else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.
POLICY)) {
dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
}
operation = OperationDAOUtil.convertOperation(dtoOperation);
@ -538,4 +609,8 @@ public class OperationManagerImpl implements OperationManager {
}
}
private String getUser() {
return CarbonContext.getThreadLocalCarbonContext().getUsername();
}
}

@ -110,7 +110,7 @@ public class OperationDAOImpl implements OperationDAO {
ObjectOutputStream oos = null;
try {
Connection connection = OperationManagementDAOFactory.getConnection();
stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID,DEVICE_ID," +
stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID,ENROLMENT_ID," +
"OPERATION_RESPONSE) VALUES(?, ?, ?)");
bao = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bao);

@ -38,8 +38,27 @@ public interface DeviceManagementProviderService extends OperationManager {
List<Device> getAllDevices() throws DeviceManagementException;
/**
* Method to retrieve all the devices with pagination support.
*
* @param deviceType Device platform
* @param index Starting row number
* @param limit No of rows to fetch
* @return PaginationResult - Result including the required parameters necessary to do pagination.
* @throws DeviceManagementException If some unusual behaviour is observed while fetching the
* devices.
*/
PaginationResult getAllDevices(String deviceType, int index, int limit) throws DeviceManagementException;
/**
* Method to retrieve all the devices with pagination support.
*
* @param index Starting row number
* @param limit No of rows to fetch
* @return PaginationResult - Result including the required parameters necessary to do pagination.
* @throws DeviceManagementException If some unusual behaviour is observed while fetching the
* devices.
*/
PaginationResult getAllDevices(int index, int limit) throws DeviceManagementException;
void sendEnrolmentInvitation(EmailMessageProperties config) throws DeviceManagementException;
@ -129,6 +148,8 @@ public interface DeviceManagementProviderService extends OperationManager {
Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException;
Device getDevice(DeviceIdentifier deviceId, EnrolmentInfo.Status status) throws DeviceManagementException;
List<DeviceType> getAvailableDeviceTypes() throws DeviceManagementException;
boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException;

@ -53,7 +53,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
private DeviceDAO deviceDAO;
private DeviceTypeDAO deviceTypeDAO;
private EnrolmentDAO enrolmentDAO;
private EnrollmentDAO enrollmentDAO;
private DeviceManagementPluginRepository pluginRepository;
private static Log log = LogFactory.getLog(DeviceManagementProviderServiceImpl.class);
@ -69,7 +69,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
private void initDataAccessObjects() {
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
this.enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
this.enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
}
@Override
@ -139,27 +139,42 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
EnrolmentInfo existingEnrolmentInfo = existingDevice.getEnrolmentInfo();
EnrolmentInfo newEnrolmentInfo = device.getEnrolmentInfo();
if (existingEnrolmentInfo != null && newEnrolmentInfo != null) {
if (existingEnrolmentInfo.equals(newEnrolmentInfo)) {
//Get all the enrollments of current user for the same device
List<EnrolmentInfo> enrolmentInfos = this.getEnrollmentsOfUser(existingDevice.getId(), newEnrolmentInfo.getOwner());
for (EnrolmentInfo enrolmentInfo : enrolmentInfos) {
//If the enrollments are same then we'll update the existing enrollment.
if (enrolmentInfo.equals(newEnrolmentInfo)) {
device.setId(existingDevice.getId());
device.getEnrolmentInfo().setDateOfEnrolment(existingEnrolmentInfo.getDateOfEnrolment());
device.getEnrolmentInfo().setDateOfEnrolment(enrolmentInfo.getDateOfEnrolment());
device.getEnrolmentInfo().setId(enrolmentInfo.getId());
this.modifyEnrollment(device);
status = true;
} else {
if (!EnrolmentInfo.Status.REMOVED.equals(existingEnrolmentInfo.getStatus())) {
this.setStatus(deviceIdentifier, existingEnrolmentInfo.getOwner(), EnrolmentInfo.Status.INACTIVE);
break;
}
}
int enrolmentId;
if (!status) {
int enrolmentId, updateStatus = 0;
try {
//Remove the existing enrollment
DeviceManagementDAOFactory.beginTransaction();
enrolmentId = enrolmentDAO.addEnrollment(existingDevice.getId(), newEnrolmentInfo, tenantId);
if (!EnrolmentInfo.Status.REMOVED.equals(existingEnrolmentInfo.getStatus())) {
existingEnrolmentInfo.setStatus(EnrolmentInfo.Status.REMOVED);
updateStatus = enrollmentDAO.updateEnrollment(existingEnrolmentInfo);
}
if ((updateStatus > 0) || EnrolmentInfo.Status.REMOVED.equals(existingEnrolmentInfo.getStatus())) {
enrolmentId = enrollmentDAO.addEnrollment(existingDevice.getId(), newEnrolmentInfo, tenantId);
DeviceManagementDAOFactory.commitTransaction();
if (log.isDebugEnabled()) {
log.debug("An enrolment is successfully updated with the id '" + enrolmentId +
log.debug("An enrolment is successfully added with the id '" + enrolmentId +
"' associated with " + "the device identified by key '" +
device.getDeviceIdentifier() + "', which belongs to " + "platform '" +
device.getType() + " upon the user '" + device.getEnrolmentInfo().getOwner() + "'");
}
status = true;
} else {
log.warn("Unable to update device enrollment for device : " + device.getDeviceIdentifier() +
" belonging to user : " + device.getEnrolmentInfo().getOwner());
}
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while adding enrolment related metadata", e);
@ -168,7 +183,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} finally {
DeviceManagementDAOFactory.closeConnection();
}
status = true;
}
}
} else {
@ -177,7 +191,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
DeviceManagementDAOFactory.beginTransaction();
DeviceType type = deviceTypeDAO.getDeviceType(device.getType());
int deviceId = deviceDAO.addDevice(type.getId(), device, tenantId);
enrolmentId = enrolmentDAO.addEnrollment(deviceId, device.getEnrolmentInfo(), tenantId);
enrolmentId = enrollmentDAO.addEnrollment(deviceId, device.getEnrolmentInfo(), tenantId);
DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
@ -219,7 +233,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
DeviceType type = deviceTypeDAO.getDeviceType(device.getType());
deviceDAO.updateDevice(type.getId(), device, tenantId);
enrolmentDAO.updateEnrollment(device.getId(), device.getEnrolmentInfo(), tenantId);
enrollmentDAO.updateEnrollment(device.getEnrolmentInfo());
DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException e) {
@ -234,6 +248,23 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return status;
}
private List<EnrolmentInfo> getEnrollmentsOfUser(int deviceId, String user)
throws DeviceManagementException {
List<EnrolmentInfo> enrolmentInfos = new ArrayList<>();
try {
DeviceManagementDAOFactory.openConnection();
enrolmentInfos = enrollmentDAO.getEnrollmentsOfUser(deviceId, user, this.getTenantId());
} catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while obtaining the enrollment information device for id " +
"'" + deviceId + "' and user : " + user, e);
} catch (SQLException e) {
throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
return enrolmentInfos;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
DeviceManager deviceManager = this.getDeviceManager(deviceId.getType());
@ -259,7 +290,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.getEnrolmentInfo().setStatus(EnrolmentInfo.Status.REMOVED);
enrolmentDAO.updateEnrollment(device.getId(), device.getEnrolmentInfo(), tenantId);
enrollmentDAO.updateEnrollment(device.getId(), device.getEnrolmentInfo(), tenantId);
deviceDAO.updateDevice(deviceType.getId(), device, tenantId);
DeviceManagementDAOFactory.commitTransaction();
@ -635,6 +666,40 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return device;
}
@Override
public Device getDevice(DeviceIdentifier deviceId, EnrolmentInfo.Status status) throws DeviceManagementException {
Device device;
try {
DeviceManagementDAOFactory.openConnection();
device = deviceDAO.getDevice(deviceId, status, this.getTenantId());
} catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while obtaining the device for id " +
"'" + deviceId.getId() + "'", e);
} catch (SQLException e) {
throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
if (device != null) {
// The changes made here to prevent unit tests getting failed. They failed because when running the unit
// tests there is no osgi services. So getDeviceManager() returns a null.
DeviceManager deviceManager = this.getDeviceManager(deviceId.getType());
if (deviceManager == null) {
if (log.isDebugEnabled()) {
log.debug("Device Manager associated with the device type '" + deviceId.getType() + "' is null. " +
"Therefore, not attempting method 'getDevice'");
}
return device;
}
Device pluginSpecificInfo = deviceManager.getDevice(deviceId);
if (pluginSpecificInfo != null) {
device.setFeatures(pluginSpecificInfo.getFeatures());
device.setProperties(pluginSpecificInfo.getProperties());
}
}
return device;
}
@Override
public List<DeviceType> getAvailableDeviceTypes() throws DeviceManagementException {
List<DeviceType> deviceTypes;
@ -698,7 +763,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
int tenantId = this.getTenantId();
Device device = deviceDAO.getDevice(deviceId, tenantId);
boolean success = enrolmentDAO.setStatus(device.getId(), currentOwner, status, tenantId);
boolean success = enrollmentDAO.setStatus(device.getId(), currentOwner, status, tenantId);
DeviceManagementDAOFactory.commitTransaction();
return success;

@ -32,7 +32,7 @@ import java.sql.SQLException;
public class EnrolmentPersistenceTests extends BaseDeviceManagementTest {
private static final Log log = LogFactory.getLog(EnrolmentPersistenceTests.class);
private EnrolmentDAO enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
private EnrollmentDAO enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
@Test
public void testAddEnrolment() {
@ -47,7 +47,7 @@ public class EnrolmentPersistenceTests extends BaseDeviceManagementTest {
/* Adding dummy enrolment configuration to the device management metadata store */
try {
DeviceManagementDAOFactory.openConnection();
enrolmentDAO.addEnrollment(deviceId, source, TestDataHolder.SUPER_TENANT_ID);
enrollmentDAO.addEnrollment(deviceId, source, TestDataHolder.SUPER_TENANT_ID);
} catch (DeviceManagementDAOException | SQLException e) {
log.error("Error occurred while adding enrollment", e);
} finally {
@ -71,7 +71,7 @@ public class EnrolmentPersistenceTests extends BaseDeviceManagementTest {
EnrolmentInfo enrolmentInfo = null;
try {
DeviceManagementDAOFactory.openConnection();
enrolmentInfo = enrolmentDAO.getEnrolment(deviceId, currentOwner, tenantId);
enrolmentInfo = enrollmentDAO.getEnrollment(deviceId, currentOwner, tenantId);
} catch (SQLException e) {
log.error("Error occurred while retrieving enrolment corresponding to device id '" + deviceId + "'", e);
} finally {

@ -142,7 +142,7 @@ public class DynamicClientRegistrationServiceImpl implements DynamicClientRegist
try {
// Append the username before Application name to make application name unique across two users.
applicationName = userName + "_" + applicationName;
applicationName = replaceInvalidChars(userName) + "_" + applicationName;
// Create the Service Provider
ServiceProvider serviceProvider = new ServiceProvider();
@ -368,4 +368,8 @@ public class DynamicClientRegistrationServiceImpl implements DynamicClientRegist
}
}
private String replaceInvalidChars(String username) {
return username.replaceAll("@","_AT_");
}
}

@ -131,7 +131,8 @@ public class DynamicClientWebAppRegistrationManager {
while (enumeration.hasMoreElements()) {
oAuthAppDetails = new OAuthAppDetails();
webAppName = (String) enumeration.nextElement();
serviceProviderName = DynamicClientWebAppRegistrationUtil.getUserName() + "_" + webAppName;
serviceProviderName = DynamicClientWebAppRegistrationUtil.replaceInvalidChars(DynamicClientWebAppRegistrationUtil.getUserName())
+ "_" + webAppName;
servletContext = DynamicClientWebAppRegistrationManager.webAppContexts.get(webAppName);
requiredDynamicClientRegistration = servletContext.getInitParameter(
DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG);

@ -311,4 +311,8 @@ public class DynamicClientWebAppRegistrationUtil {
}
}
}
public static String replaceInvalidChars(String username) {
return username.replaceAll("@","_AT_");
}
}

@ -72,8 +72,8 @@ public class PermissionBasedScopeValidator extends OAuth2ScopeValidator {
}
Properties properties = new Properties();
properties.put(PermissionBasedScopeValidator.URL_PROPERTY, url);
properties.put(PermissionBasedScopeValidator.HTTP_METHOD_PROPERTY, method);
properties.put(PermissionBasedScopeValidator.URL_PROPERTY, url.toLowerCase());
properties.put(PermissionBasedScopeValidator.HTTP_METHOD_PROPERTY, method.toUpperCase());
PermissionManagerService permissionManagerService = OAuthExtensionsDataHolder.getInstance().
getPermissionManagerService();
try {

@ -97,6 +97,7 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato
PolicyDelegationException {
try {
//ToDo Need to fix this to fetch OSGi service
OperationManager operationManager = new OperationManagerImpl();
operationManager.addOperation(PolicyManagerUtil.transformPolicy(policy), deviceIdentifiers);
} catch (OperationManagementException e) {

@ -77,7 +77,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
public void addDevice() throws DeviceManagementException, PolicyManagementException {
DeviceDAO deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
EnrolmentDAO enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
EnrollmentDAO enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
DeviceType type = DeviceTypeCreator.getDeviceType();
devices = DeviceCreator.getDeviceList(type);
@ -91,7 +91,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
DeviceManagementDAOFactory.beginTransaction();
for (Device device : devices) {
int id = deviceDAO.addDevice(type.getId(), device, -1234);
enrolmentDAO.addEnrollment(id, device.getEnrolmentInfo(), -1234);
enrollmentDAO.addEnrollment(id, device.getEnrolmentInfo(), -1234);
}
} catch (TransactionManagementException e) {
throw new PolicyManagementException("Error occurred while adding device enrolment", e);

@ -26,11 +26,12 @@ import org.testng.annotations.Test;
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.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.ntask.common.TaskException;
import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.core.enforcement.DelegationTask;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
@ -48,7 +49,6 @@ public class PolicyEvaluationTestCase extends BasePolicyManagementDAOTest {
@BeforeClass
@Override
public void init() throws Exception {
PolicyEvaluationPoint evaluationPoint = new SimplePolicyEvaluationTest();
PolicyManagementDataHolder.getInstance().setPolicyEvaluationPoint(evaluationPoint);
}
@ -126,8 +126,8 @@ public class PolicyEvaluationTestCase extends BasePolicyManagementDAOTest {
log.debug("Delegation methods calls started because tasks cannot be started due to osgi constraints.....!");
DelegationTask delegationTask = new DelegationTask();
delegationTask.execute();
//DelegationTask delegationTask = new DelegationTask();
//delegationTask.execute();
}
public void sortPolicies(List<Policy> policyList) {

@ -103,28 +103,28 @@ public class WebappAuthenticationValve extends CarbonTomcatValve {
if(!uri.endsWith("/")) {
uri = uri + "/";
}
String ctx = request.getContextPath();
//Check the context in nonSecuredEndpoints. If so it means current context is a skippedContext.
if (nonSecuredEndpoints.containsKey(uri)) {
return true;
}
String contextPath = request.getContextPath();
//Check the contextPath in nonSecuredEndpoints. If so it means cache is not populated for this web-app.
if (!nonSecuredEndpoints.containsKey(contextPath)) {
String param = request.getContext().findParameter("nonSecuredEndPoints");
String skippedEndPoint;
if (param != null && !param.isEmpty()) {
//Add the nonSecured end-points to cache
StringTokenizer tokenizer = new StringTokenizer(param, ",");
nonSecuredEndpoints.put(contextPath, "true");
while (tokenizer.hasMoreTokens()) {
skippedEndPoint = ctx + tokenizer.nextToken();
skippedEndPoint = contextPath + tokenizer.nextToken();
skippedEndPoint = skippedEndPoint.replace("\n", "").replace("\r", "").trim();
if(!skippedEndPoint.endsWith("/")) {
skippedEndPoint = skippedEndPoint + "/";
}
nonSecuredEndpoints.put(skippedEndPoint, "true");
}
}
}
if (nonSecuredEndpoints.containsKey(uri)) {
return true;
}
}
return false;
}

@ -43,7 +43,7 @@ public class OAuthAuthenticator implements WebappAuthenticator {
private static final String BEARER_TOKEN_TYPE = "bearer";
private static final String RESOURCE_KEY = "resource";
private static APITokenAuthenticator authenticator = new APITokenAuthenticator();
private static final Log log = LogFactory.getLog(OAuthAuthenticator.class);
@Override

@ -87,12 +87,12 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING (
CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER 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_device FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
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
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);

@ -87,12 +87,12 @@ CREATE TABLE DM_ENROLMENT_OP_MAPPING (
CREATE TABLE DM_DEVICE_OPERATION_RESPONSE (
ID INTEGER IDENTITY NOT NULL,
DEVICE_ID INTEGER NOT NULL,
ENROLMENT_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
OPERATION_RESPONSE VARBINARY(max) DEFAULT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_operation_response_device FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
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
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);

@ -96,12 +96,12 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING (
CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER 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_device FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
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
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
)ENGINE = InnoDB;

@ -157,12 +157,12 @@ WHEN (NEW.ID IS NULL)
CREATE TABLE DM_DEVICE_OPERATION_RESPONSE (
ID NUMBER(10) NOT NULL,
DEVICE_ID NUMBER(10) NOT NULL,
ENROLMENT_ID NUMBER(10) NOT NULL,
OPERATION_ID NUMBER(10) NOT NULL,
OPERATION_RESPONSE BLOB DEFAULT NULL,
CONSTRAINT PK_DM_DEVICE_OP_RESPONSE PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_op_res_device FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID),
CONSTRAINT fk_dm_device_op_res_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES
DM_ENROLMENT (ID),
CONSTRAINT fk_dm_device_op_res_operation FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID)
)

@ -82,11 +82,11 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING (
CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE (
ID BIGSERIAL NOT NULL PRIMARY KEY,
DEVICE_ID INTEGER NOT NULL,
ENROLMENT_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
OPERATION_RESPONSE BYTEA DEFAULT NULL,
CONSTRAINT fk_dm_device_operation_response_device FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
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
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);

Loading…
Cancel
Save