revert-70aa11f8
hasuniea 9 years ago
commit b17cc43476

@ -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;
}

@ -34,41 +34,42 @@ public interface OperationManager {
* @param operation Operation to be added
* @param devices List of DeviceIdentifiers to execute the operation
* @throws OperationManagementException If some unusual behaviour is observed while adding the
* operation
* 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.
*
* @param deviceId DeviceIdentifier of the device
* @throws OperationManagementException If some unusual behaviour is observed while fetching the
* operation list.
* 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.
*
* @param deviceId DeviceIdentifier of the device
* @throws OperationManagementException If some unusual behaviour is observed while fetching the
* operation list.
* 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;
}

@ -65,6 +65,10 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
return providers.get(type);
}
public Map<String, DeviceManagementService> getAllDeviceManagementServices() {
return providers;
}
@Override
public void notifyObserver() {
synchronized (providers) {

@ -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;
}

@ -122,7 +122,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
stmt.setInt(4, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
device = DeviceManagementDAOUtil.loadDevice(rs);
device = DeviceManagementDAOUtil.loadMatchingDevice(rs);
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while listing devices for type " +
@ -133,6 +133,40 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
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);
}
} 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 HashMap<Integer, Device> getDevice(DeviceIdentifier deviceIdentifier) throws DeviceManagementDAOException {
Connection conn;

@ -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,44 @@ 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 {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@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 {
@ -95,13 +129,14 @@ public class EnrolmentDAOImpl implements EnrolmentDAO {
}
}
@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,8 +207,8 @@ public class EnrolmentDAOImpl implements EnrolmentDAO {
}
@Override
public EnrolmentInfo getEnrolment(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
public EnrolmentInfo getEnrollment(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = 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,35 +35,37 @@ 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 {
private static final Log log = LogFactory.getLog(DeviceManagementDAOUtil.class);
private static final Log log = LogFactory.getLog(DeviceManagementDAOUtil.class);
public static void cleanupResources(Connection conn, 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);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(Connection conn, 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);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
@ -82,46 +84,46 @@ public final class DeviceManagementDAOUtil {
}
}
/**
* Get id of the current tenant.
*
* @return tenant id
* @throws DeviceManagementDAOException if an error is observed when getting tenant id
*/
public static int getTenantId() throws DeviceManagementDAOException {
CarbonContext context = CarbonContext.getThreadLocalCarbonContext();
int tenantId = context.getTenantId();
if (tenantId != MultitenantConstants.INVALID_TENANT_ID) {
return tenantId;
}
String tenantDomain = context.getTenantDomain();
if (tenantDomain == null) {
String msg = "Tenant domain is not properly set and thus, is null";
throw new DeviceManagementDAOException(msg);
}
TenantManager tenantManager = DeviceManagementDataHolder.getInstance().getTenantManager();
try {
tenantId = tenantManager.getTenantId(tenantDomain);
} catch (UserStoreException e) {
String msg =
"Error occurred while retrieving id from the domain of tenant " + tenantDomain;
throw new DeviceManagementDAOException(msg);
}
return tenantId;
}
/**
* Get id of the current tenant.
*
* @return tenant id
* @throws DeviceManagementDAOException if an error is observed when getting tenant id
*/
public static int getTenantId() throws DeviceManagementDAOException {
CarbonContext context = CarbonContext.getThreadLocalCarbonContext();
int tenantId = context.getTenantId();
if (tenantId != MultitenantConstants.INVALID_TENANT_ID) {
return tenantId;
}
String tenantDomain = context.getTenantDomain();
if (tenantDomain == null) {
String msg = "Tenant domain is not properly set and thus, is null";
throw new DeviceManagementDAOException(msg);
}
TenantManager tenantManager = DeviceManagementDataHolder.getInstance().getTenantManager();
try {
tenantId = tenantManager.getTenantId(tenantDomain);
} catch (UserStoreException e) {
String msg =
"Error occurred while retrieving id from the domain of tenant " + tenantDomain;
throw new DeviceManagementDAOException(msg);
}
return tenantId;
}
public static DataSource lookupDataSource(String dataSourceName,
final Hashtable<Object, Object> 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 DataSource lookupDataSource(String dataSourceName,
final Hashtable<Object, Object> 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 Device loadDevice(ResultSet rs) throws SQLException {
Device device = new Device();
@ -144,21 +146,58 @@ public final class DeviceManagementDAOUtil {
return enrolmentInfo;
}
public static Device loadDevice(ResultSet rs) throws SQLException {
Device device = new Device();
device.setId(rs.getInt("DEVICE_ID"));
device.setName(rs.getString("DEVICE_NAME"));
device.setDescription(rs.getString("DESCRIPTION"));
device.setType(rs.getString("DEVICE_TYPE"));
device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION"));
device.setEnrolmentInfo(loadEnrolment(rs));
return device;
}
public static Device loadDevice(ResultSet rs) throws SQLException {
Device device = new Device();
device.setId(rs.getInt("DEVICE_ID"));
device.setName(rs.getString("DEVICE_NAME"));
device.setDescription(rs.getString("DESCRIPTION"));
device.setType(rs.getString("DEVICE_TYPE"));
device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION"));
device.setEnrolmentInfo(loadEnrolment(rs));
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"));
deviceType.setName(rs.getString("NAME"));
return deviceType;
}
public static DeviceType loadDeviceType(ResultSet rs) throws SQLException {
DeviceType deviceType = new DeviceType();
deviceType.setId(rs.getInt("ID"));
deviceType.setName(rs.getString("NAME"));
return deviceType;
}
}

@ -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;
@ -76,44 +78,54 @@ public class OperationManagerImpl implements OperationManager {
log.debug("operation:[" + operation.toString() + "]");
for (DeviceIdentifier deviceIdentifier : deviceIds) {
log.debug("device identifier id:[" + deviceIdentifier.getId() + "] type:[" +
deviceIdentifier.getType() + "]");
deviceIdentifier.getType() + "]");
}
}
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
List<EnrolmentInfo> enrolments;
try {
DeviceManagementDAOFactory.openConnection();
enrolments = deviceDAO.getEnrolmentsByStatus(deviceIds, EnrolmentInfo.Status.ACTIVE, tenantId);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection the data " +
"source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
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());
List<DeviceIdentifier> authorizedDeviceList = DeviceManagementDataHolder.getInstance().
getDeviceAccessAuthorizationService().isUserAuthorized(deviceIds).getAuthorizedDevices();
if (authorizedDeviceList.size() > 0) {
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
List<EnrolmentInfo> enrolments;
try {
DeviceManagementDAOFactory.openConnection();
enrolments = deviceDAO.getEnrolmentsByStatus(deviceIds, EnrolmentInfo.Status.ACTIVE, tenantId);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection the data " +
"source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
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());
}
OperationManagementDAOFactory.commitTransaction();
return operationId;
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
throw new OperationManagementException("Error occurred while adding operation", e);
} catch (DeviceManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
throw new OperationManagementException("Error occurred while retrieving device metadata", e);
} catch (TransactionManagementException e) {
throw new OperationManagementException("Error occurred while initiating the transaction", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
} else {
log.info("User : " + getUser() + " is not authorized to perform operations on given device-list.");
}
OperationManagementDAOFactory.commitTransaction();
return operationId;
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
throw new OperationManagementException("Error occurred while adding operation", e);
} catch (DeviceManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
throw new OperationManagementException("Error occurred while retrieving device metadata", e);
} catch (TransactionManagementException e) {
throw new OperationManagementException("Error occurred while initiating the transaction", e);
} finally {
OperationManagementDAOFactory.closeConnection();
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" +
this.getUser(), e);
}
return -1;
}
@Override
@ -121,45 +133,58 @@ public class OperationManagerImpl implements OperationManager {
int enrolmentId;
List<Operation> operations = new ArrayList<>();
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 given device " +
"Identifier:" + deviceId.getId() + " and given type" + deviceId.getType());
}
List<? extends org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> operationList =
operationDAO.getOperationsForDevice(enrolmentId);
for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) {
Operation operation = OperationDAOUtil.convertOperation(dtoOperation);
operations.add(operation);
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 given device " +
"Identifier:" + deviceId.getId() + " and given type" +
deviceId.getType());
}
List<? extends org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> operationList =
operationDAO.getOperationsForDevice(enrolmentId);
for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) {
Operation operation = OperationDAOUtil.convertOperation(dtoOperation);
operations.add(operation);
}
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
"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() + "'");
} catch (SQLException 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());
}
return operations;
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
"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() + "'");
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
} finally {
OperationManagementDAOFactory.closeConnection();
} 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,113 +192,130 @@ 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 {
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());
}
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);
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());
}
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());
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
"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);
} catch (SQLException 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());
}
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);
} catch (DeviceManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the device " +
"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);
} finally {
OperationManagementDAOFactory.closeConnection();
} 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 {
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 given device " +
"Identifier:" + deviceId.getId() + " and given type" + deviceId.getType());
}
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())) {
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 (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())) {
dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
} else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type
.POLICY.equals(dtoOperation.getType())) {
dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
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 given device " +
"Identifier:" + deviceId.getId() + " and given type" +
deviceId.getType());
}
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())) {
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 (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())) {
dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
} 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);
}
} 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);
} catch (SQLException e) {
throw new OperationManagementException(
"Error occurred while opening a connection to the data source", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
operation = OperationDAOUtil.convertOperation(dtoOperation);
} else {
log.info("User : " + getUser() + " is not authorized to fetch operations on device : "
+ deviceId.getId());
}
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);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
} finally {
OperationManagementDAOFactory.closeConnection();
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while authorizing access to the devices for user : " +
this.getUser(), e);
}
return operation;
}
@Override
@ -284,39 +326,52 @@ public class OperationManagerImpl implements OperationManager {
}
int enrolmentId;
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);
} 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()));
}
if (operation.getOperationResponse() != null) {
operationDAO.addOperationResponse(enrolmentId, operationId, operation.getOperationResponse());
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);
} 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()));
}
if (operation.getOperationResponse() != null) {
operationDAO.addOperationResponse(enrolmentId, operationId, operation.getOperationResponse());
}
OperationManagementDAOFactory.commitTransaction();
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
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);
} 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());
}
OperationManagementDAOFactory.commitTransaction();
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
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);
} catch (TransactionManagementException e) {
throw new OperationManagementException("Error occurred while initiating a transaction", e);
} finally {
OperationManagementDAOFactory.closeConnection();
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" +
this.getUser(), e);
}
}
@ -324,14 +379,12 @@ public class OperationManagerImpl implements OperationManager {
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);
throw new OperationManagementException("Operation not found for operation id : " + operationId);
}
lookupOperationDAO(operation).deleteOperation(operationId);
OperationManagementDAOFactory.commitTransaction();
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
@ -347,64 +400,75 @@ 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());
log.debug("Operation Id: " + operationId + " Device Type: " + deviceId.getType() + " Device Identifier: " +
deviceId.getId());
}
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 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.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)) {
dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
} 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)) {
dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
}
if (dtoOperation == null) {
throw new OperationManagementException("Operation not found for operation Id:" + operationId +
" device id:" + deviceId.getId());
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 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.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)) {
dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
} 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)) {
dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
}
if (dtoOperation == null) {
throw new OperationManagementException("Operation not found for operation Id:" + operationId +
" device id:" + deviceId.getId());
}
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);
} catch (DeviceManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the device " +
"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);
} finally {
OperationManagementDAOFactory.closeConnection();
}
} else {
log.info("User : " + getUser() + " is not authorized to fetch operations on device : "
+ deviceId.getId());
}
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);
} catch (DeviceManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the device " +
"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);
} finally {
OperationManagementDAOFactory.closeConnection();
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" +
this.getUser(), e);
}
return operation;
}
@ -413,59 +477,69 @@ 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 {
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 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());
dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, dtoOpStatus));
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);
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 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());
dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, dtoOpStatus));
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);
}
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
"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);
} catch (SQLException 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());
}
return operations;
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
"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);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
} finally {
OperationManagementDAOFactory.closeConnection();
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" +
this.getUser(), e);
}
return operations;
}
@Override
@ -473,35 +547,32 @@ 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());
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);
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the operation with operation Id '" +
operationId, e);
operationId, e);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
} finally {
@ -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;

@ -47,13 +47,14 @@ import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService,
PluginInitializationListener {
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 +70,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,26 +140,41 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
EnrolmentInfo existingEnrolmentInfo = existingDevice.getEnrolmentInfo();
EnrolmentInfo newEnrolmentInfo = device.getEnrolmentInfo();
if (existingEnrolmentInfo != null && newEnrolmentInfo != null) {
if (existingEnrolmentInfo.equals(newEnrolmentInfo)) {
device.setId(existingDevice.getId());
device.getEnrolmentInfo().setDateOfEnrolment(existingEnrolmentInfo.getDateOfEnrolment());
this.modifyEnrollment(device);
status = true;
} else {
if (!EnrolmentInfo.Status.REMOVED.equals(existingEnrolmentInfo.getStatus())) {
this.setStatus(deviceIdentifier, existingEnrolmentInfo.getOwner(), EnrolmentInfo.Status.INACTIVE);
//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(enrolmentInfo.getDateOfEnrolment());
device.getEnrolmentInfo().setId(enrolmentInfo.getId());
this.modifyEnrollment(device);
status = true;
break;
}
int enrolmentId;
}
if (!status) {
int enrolmentId, updateStatus = 0;
try {
//Remove the existing enrollment
DeviceManagementDAOFactory.beginTransaction();
enrolmentId = enrolmentDAO.addEnrollment(existingDevice.getId(), newEnrolmentInfo, tenantId);
DeviceManagementDAOFactory.commitTransaction();
if (log.isDebugEnabled()) {
log.debug("An enrolment is successfully updated 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() + "'");
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 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();
@ -168,7 +184,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} finally {
DeviceManagementDAOFactory.closeConnection();
}
status = true;
}
}
} else {
@ -177,7 +192,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 +234,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 +249,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 +291,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,21 +667,69 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return device;
}
@Override
public List<DeviceType> getAvailableDeviceTypes() throws DeviceManagementException {
List<DeviceType> deviceTypes;
try {
DeviceManagementDAOFactory.openConnection();
deviceTypes = deviceDAO.getDeviceTypes();
} catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while obtaining the device types.", e);
} catch (SQLException e) {
throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
return deviceTypes;
}
@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> deviceTypesInDatabase;
List<DeviceType> deviceTypesResponse = new ArrayList<>();
try {
DeviceManagementDAOFactory.openConnection();
deviceTypesInDatabase = deviceDAO.getDeviceTypes();
Map<String, DeviceManagementService> registeredTypes = pluginRepository.getAllDeviceManagementServices();
DeviceType deviceType;
if (registeredTypes != null && deviceTypesInDatabase != null) {
for (int x = 0; x < deviceTypesInDatabase.size(); x++) {
if (registeredTypes.get(deviceTypesInDatabase.get(x).getName()) != null) {
deviceType = new DeviceType();
deviceType.setId(deviceTypesInDatabase.get(x).getId());
deviceType.setName(deviceTypesInDatabase.get(x).getName());
deviceTypesResponse.add(deviceType);
}
}
}
} catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while obtaining the device types.", e);
} catch (SQLException e) {
throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
return deviceTypesResponse;
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceId, Device device) throws DeviceManagementException {
@ -698,7 +778,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 {

@ -26,46 +26,46 @@
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>bundle</packaging>
<name>WSO2 Carbon - OAuth Back End Authenticator </name>
<name>WSO2 Carbon - OAuth Back End Authenticator</name>
<artifactId>org.wso2.carbon.identity.authenticator.backend.oauth</artifactId>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.base</artifactId>
</dependency>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.core</artifactId>
</dependency>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.application.authentication.framework</artifactId>
</dependency>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core.services</artifactId>
</dependency>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth</artifactId>
</dependency>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.application.common</artifactId>
</dependency>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth.stub</artifactId>
@ -89,14 +89,15 @@
<Bundle-Name>${pom.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>Identity backend Bundle</Bundle-Description>
<Bundle-Activator>org.wso2.carbon.identity.authenticator.backend.oauth.internal.OauthAuthenticatorServiceComponent</Bundle-Activator>
<Bundle-Activator>
org.wso2.carbon.identity.authenticator.backend.oauth.internal.OauthAuthenticatorServiceComponent
</Bundle-Activator>
<Private-Package>
org.wso2.org.wso2.carbon.identity.authenticator.backend.oauth.internal
</Private-Package>
<Export-Package>
org.wso2.carbon.identity.authenticator.backend.oauth.*
</Export-Package>
</instructions>
</configuration>
</plugin>

@ -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 {
@ -81,11 +81,12 @@ public class PermissionBasedScopeValidator extends OAuth2ScopeValidator {
User authzUser = accessTokenDO.getAuthzUser();
if ((permission != null) && (authzUser != null)) {
String username = authzUser.getUserName();
String userStore = authzUser.getUserStoreDomain();
int tenantId = OAuthExtUtils.getTenantId(authzUser.getTenantDomain());
UserRealm userRealm = OAuthExtensionsDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
if (userRealm != null && userRealm.getAuthorizationManager() != null) {
status = userRealm.getAuthorizationManager()
.isUserAuthorized(username, permission.getPath(),
.isUserAuthorized(userStore +"/"+ username, permission.getPath(),
PermissionMethod.UI_EXECUTE);
}
}

@ -742,7 +742,7 @@ public class PolicyDAOImpl implements PolicyDAO {
try {
conn = this.getConnection();
String query = "UPDATE DM_POLICY SET NAME = ?, PROFILE_ID = ?, PRIORITY = ?, COMPLIANCE = ?," +
" UPDATED = ?, DESCRIPTION = ? WHERE ID = ? AND TENANT_ID = ?";
" UPDATED = ?, DESCRIPTION = ?, OWNERSHIP_TYPE = ? WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(query);
stmt.setString(1, policy.getPolicyName());
stmt.setInt(2, policy.getProfile().getProfileId());
@ -750,8 +750,9 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setString(4, policy.getCompliance());
stmt.setInt(5, 1);
stmt.setString(6, policy.getDescription());
stmt.setInt(7, policy.getId());
stmt.setInt(8, tenantId);
stmt.setString(7, policy.getOwnershipType());
stmt.setInt(8, policy.getId());
stmt.setInt(9, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {

@ -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 param = request.getContext().findParameter("nonSecuredEndPoints");
String skippedEndPoint;
if (param != null && !param.isEmpty()) {
//Add the nonSecured end-points to cache
StringTokenizer tokenizer = new StringTokenizer(param, ",");
while (tokenizer.hasMoreTokens()) {
skippedEndPoint = ctx + tokenizer.nextToken();
skippedEndPoint = skippedEndPoint.replace("\n", "").replace("\r", "").trim();
if(!skippedEndPoint.endsWith("/")) {
skippedEndPoint = skippedEndPoint + "/";
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 = contextPath + tokenizer.nextToken();
skippedEndPoint = skippedEndPoint.replace("\n", "").replace("\r", "").trim();
if(!skippedEndPoint.endsWith("/")) {
skippedEndPoint = skippedEndPoint + "/";
}
nonSecuredEndpoints.put(skippedEndPoint, "true");
}
nonSecuredEndpoints.put(skippedEndPoint, "true");
}
if (nonSecuredEndpoints.containsKey(uri)) {
return 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
@ -111,6 +111,10 @@ public class OAuthAuthenticator implements WebappAuthenticator {
AuthenticatorFrameworkDataHolder.getInstance().getoAuth2TokenValidationService().validate(dto);
if (oAuth2TokenValidationResponseDTO.isValid()) {
String username = oAuth2TokenValidationResponseDTO.getAuthorizedUser();
//Remove the userstore domain from username
if (username.contains("/")) {
username = username.substring(username.indexOf('/') + 1);
}
authenticationInfo.setUsername(username);
authenticationInfo.setTenantDomain(MultitenantUtils.getTenantDomain(username));
authenticationInfo.setTenantId(Utils.getTenantIdOFUser(username));

@ -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
);

@ -501,6 +501,10 @@
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>xerces.wso2</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
@ -597,6 +601,10 @@
<groupId>commons-collections.wso2</groupId>
<artifactId>commons-collections</artifactId>
</exclusion>
<exclusion>
<groupId>xerces.wso2</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
@ -825,6 +833,10 @@
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
@ -1427,7 +1439,7 @@
<properties>
<testng.version>6.1.1</testng.version>
<carbon.kernel.version>4.4.1</carbon.kernel.version>
<carbon.kernel.version>4.4.2</carbon.kernel.version>
<carbon.p2.plugin.version>1.5.4</carbon.p2.plugin.version>
<maven-buildnumber-plugin.version>1.3</maven-buildnumber-plugin.version>
@ -1471,7 +1483,7 @@
<carbon.identity.version>5.0.2</carbon.identity.version>
<!-- Carbon Multi-tenancy -->
<carbon.multitenancy.version>4.5.0-m1</carbon.multitenancy.version>
<carbon.multitenancy.version>4.5.0</carbon.multitenancy.version>
<!-- Carbon Registry -->
<carbon.registry.version>4.4.8</carbon.registry.version>

Loading…
Cancel
Save