Performance improvements

reporting
Charitha Goonetilleke 5 years ago
parent dc05306aa9
commit be705ce81b

@ -102,7 +102,7 @@ public class Utils {
final ProxySelector proxySelector = new ProxySelector() {
@Override
public java.util.List<Proxy> select(URI uri) {
public List<Proxy> select(URI uri) {
List<Proxy> proxyList = new ArrayList<>();
String host = uri.getHost();

@ -94,7 +94,7 @@ public class AnnotationProcessor {
private Class<io.swagger.annotations.Tag> tagClass;
private Class<io.swagger.annotations.Extension> extensionClass;
private Class<io.swagger.annotations.ExtensionProperty> extensionPropertyClass;
private Class<io.swagger.annotations.ApiOperation> apiOperation;
private Class<ApiOperation> apiOperation;
private Class<org.wso2.carbon.apimgt.annotations.api.Scope> scopeClass;
private Class<org.wso2.carbon.apimgt.annotations.api.Scopes> scopesClass;
private Map<String, ApiScope> apiScopes;
@ -119,8 +119,8 @@ public class AnnotationProcessor {
.loadClass(org.wso2.carbon.apimgt.annotations.api.Scope.class.getName());
scopesClass = (Class<org.wso2.carbon.apimgt.annotations.api.Scopes>) classLoader
.loadClass(org.wso2.carbon.apimgt.annotations.api.Scopes.class.getName());
apiOperation = (Class<io.swagger.annotations.ApiOperation>)classLoader
.loadClass((io.swagger.annotations.ApiOperation.class.getName()));
apiOperation = (Class<ApiOperation>)classLoader
.loadClass((ApiOperation.class.getName()));
} catch (ClassNotFoundException e) {
log.error("An error has occurred while loading classes ", e);
}

@ -34,8 +34,8 @@
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.apimgt.integration.generated.client</module>
<module>org.wso2.carbon.apimgt.integration.client</module>
<module>org.wso2.carbon.apimgt.integration.generated.client</module>
<module>org.wso2.carbon.apimgt.integration.client</module>
<module>org.wso2.carbon.apimgt.webapp.publisher</module>
<module>org.wso2.carbon.apimgt.application.extension</module>
<module>org.wso2.carbon.apimgt.application.extension.api</module>

@ -140,7 +140,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
@QueryParam("owner") String owner,
List<String> deviceIdentifiers){
try {
if (DeviceMgtAPIUtils.getDeviceManagementService().updateEnrollment(owner, deviceIdentifiers)) {
if (DeviceMgtAPIUtils.getDeviceManagementService().updateEnrollment(owner, true, deviceIdentifiers)) {
String msg = "Device owner is updated successfully.";
return Response.status(Response.Status.OK).entity(msg).build();
}

@ -52,7 +52,6 @@ public class DeviceMgtAPITestHelper {
deviceType.setName(name != null ? name : DEVICE_TYPE);
DeviceTypeMetaDefinition deviceTypeMetaDefinition = new DeviceTypeMetaDefinition();
deviceTypeMetaDefinition.setClaimable(true);
deviceTypeMetaDefinition.setDescription(DEVICE_TYPE_DESCRIPTION);
PushNotificationConfig pushNotificationConfig =

@ -184,8 +184,6 @@ public interface DeviceManager {
*/
boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) throws DeviceManagementException;
boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException;
boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException;

@ -40,6 +40,8 @@ public class EnrolmentInfo implements Serializable {
@ApiModelProperty(name = "id", value = "ID of the device in the WSO2 EMM device information database.",
required = true)
private int id;
private boolean isTransferred;
@ApiModelProperty(name = "dateOfEnrolment", value = "Date of the device enrollment. This value is not necessary.", required = false )
private Long dateOfEnrolment;
@ApiModelProperty(name = "dateOfLastUpdate", value = "Date of the device's last update. This value is not necessary.", required = false )
@ -72,6 +74,14 @@ public class EnrolmentInfo implements Serializable {
this.id = id;
}
public boolean isTransferred() {
return isTransferred;
}
public void setTransferred(boolean transferred) {
isTransferred = transferred;
}
public Long getDateOfEnrolment() {
return dateOfEnrolment;
}

@ -25,6 +25,7 @@ public class MonitoringOperation {
private String taskName;
private int recurrentTimes;
private boolean responsePersistence = true;
public String getTaskName() {
return taskName;
@ -42,5 +43,21 @@ public class MonitoringOperation {
this.recurrentTimes = recurrentTimes;
}
public boolean hasResponsePersistence() {
return responsePersistence;
}
public void setResponsePersistence(boolean responsePersistence) {
this.responsePersistence = responsePersistence;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof MonitoringOperation) {
MonitoringOperation op = (MonitoringOperation) obj;
return taskName != null && taskName.equals(op.getTaskName());
}
return false;
}
}

@ -18,6 +18,7 @@
package org.wso2.carbon.device.mgt.common;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@ -33,14 +34,14 @@ public class PaginationRequest {
private int groupId;
private String owner;
private String ownerPattern;
private List<String> statusList;
private String deviceType;
private String deviceName;
private String ownership;
private String ownerRole;
private Map<String, Object> property = new HashMap<>();
private Date since;
private String filter;
private Map<String, Object> property = new HashMap<>();
private List<String> statusList = new ArrayList<>();
public PaginationRequest(int start, int rowCount) {
this.startIndex = start;

@ -45,6 +45,8 @@ public interface OperationManager {
Activity addOperation(Operation operation, List<DeviceIdentifier> devices) throws OperationManagementException,
InvalidDeviceException;
void addTaskOperation(String deviceType, Operation operation) throws OperationManagementException;
/**
* Method to retrieve the list of all operations to a device.
*
@ -66,6 +68,17 @@ public interface OperationManager {
*/
PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request)
throws OperationManagementException;
/**
* Method to retrieve the list of operations placed for device with specified status.
*
* @param deviceId - Device Identifier of the device
* @param status - Status of the operation
* @return A List of operations applied to the given device-id.
* @throws OperationManagementException If some unusual behaviour is observed while fetching the
* operation list.
*/
List<? extends Operation> getOperations(DeviceIdentifier deviceId, Operation.Status status)
throws OperationManagementException;
/**
* Method to retrieve the list of available operations to a device.
@ -86,7 +99,7 @@ public interface OperationManager {
void updateOperation(DeviceIdentifier deviceId, Operation operation) throws OperationManagementException;
void updateOperation(int enrolmentId, Operation operation) throws OperationManagementException;
void updateOperation(int enrolmentId, Operation operation, DeviceIdentifier deviceId) throws OperationManagementException;
Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId)
throws OperationManagementException;

@ -43,14 +43,6 @@ public class DeviceTypeMetaDefinition {
this.features = features;
}
public boolean isClaimable() {
return claimable;
}
public void setClaimable(boolean isClaimable) {
this.claimable = isClaimable;
}
public PushNotificationConfig getPushNotificationConfig() {
return pushNotificationConfig;
}

@ -56,15 +56,15 @@ import java.util.Map;
public class DeviceManagementPluginRepository implements DeviceManagerStartupListener {
private Map<DeviceTypeServiceIdentifier, DeviceManagementServiceHolder> providers;
private final Map<DeviceTypeServiceIdentifier, DeviceManagementServiceHolder> providers;
private boolean isInitiated;
private static final Log log = LogFactory.getLog(DeviceManagementPluginRepository.class);
private OperationManagerRepository operationManagerRepository;
private final OperationManagerRepository operationManagerRepository;
private static final long DEFAULT_UPDATE_TIMESTAMP = 900000L;
public DeviceManagementPluginRepository() {
this.operationManagerRepository = new OperationManagerRepository();
providers = Collections.synchronizedMap(new HashMap<DeviceTypeServiceIdentifier, DeviceManagementServiceHolder>());
providers = Collections.synchronizedMap(new HashMap<>());
DeviceManagementServiceComponent.registerStartupListener(this);
}

@ -18,34 +18,34 @@
package org.wso2.carbon.device.mgt.core.archival;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
import org.wso2.carbon.device.mgt.core.archival.beans.*;
import org.wso2.carbon.device.mgt.core.archival.dao.*;
import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDAO;
import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDAOException;
import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDestinationDAOFactory;
import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalSourceDAOFactory;
import org.wso2.carbon.device.mgt.core.archival.dao.DataDeletionDAO;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
public class ArchivalServiceImpl implements ArchivalService {
private static Log log = LogFactory.getLog(ArchivalServiceImpl.class);
private static final Log log = LogFactory.getLog(ArchivalServiceImpl.class);
private ArchivalDAO archivalDAO;
private DataDeletionDAO dataDeletionDAO;
private final ArchivalDAO archivalDAO;
private final DataDeletionDAO dataDeletionDAO;
private static final int EXECUTION_BATCH_SIZE =
DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getArchivalConfiguration()
.getArchivalTaskConfiguration().getBatchSize();
private static final boolean ARCHIVE_PENDING_OPERATIONS =
private static final int ARCHIVAL_LOCK_INTERVAL =
DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getArchivalConfiguration()
.getArchivalTaskConfiguration().isArchivePendingOperations();
private String[] NOT_IN_PROGRESS_OPS = new String[]{"COMPLETED", "ERROR", "REPEATED"};
private String[] NOT_PENDING_OPS = new String[]{"COMPLETED", "ERROR", "REPEATED", "IN_PROGRESS"};
private String[] NOT_PENDING_IN_PROGRESS_OPS = new String[]{"COMPLETED", "ERROR", "REPEATED"};
.getArchivalTaskConfiguration().getArchivalLockInterval();
public ArchivalServiceImpl() {
this.archivalDAO = ArchivalSourceDAOFactory.getDataPurgingDAO();
@ -54,187 +54,160 @@ public class ArchivalServiceImpl implements ArchivalService {
@Override
public void archiveTransactionalRecords() throws ArchivalException {
List<Integer> allOperations;
try {
ArchivalSourceDAOFactory.openConnection();
ArchivalDestinationDAOFactory.openConnection();
beginTransactions();
Timestamp currentTime = new Timestamp(new Date().getTime());
//Purge the largest table, DM_DEVICE_OPERATION_RESPONSE
if (log.isDebugEnabled()) {
log.debug("Fetching All Operations");
log.debug("## Archiving operation responses");
}
allOperations = archivalDAO.getAllOperations();
if (log.isDebugEnabled()) {
log.debug("Fetching All Pending Operations");
}
} catch (ArchivalDAOException e) {
// rollbackTransactions();
String msg = "Rollback the get all operations and get all pending operations";
log.error(msg, e);
throw new ArchivalException(msg, e);
} catch (SQLException e) {
String msg = "An error occurred while connecting to the archival database";
log.error(msg, e);
throw new ArchivalException(msg, e);
} finally {
ArchivalSourceDAOFactory.closeConnection();
ArchivalDestinationDAOFactory.closeConnection();
}
int failAttempts;
List<Integer> candidates = allOperations;
log.info(allOperations.size() + " All Operations.");
List<Integer> nonRemovableMappings = archivalDAO.getNonRemovableOperationMappingIDs(currentTime);
int totalLargeOpResCount = archivalDAO.getLargeOperationResponseCount(currentTime, nonRemovableMappings);
if (!ARCHIVE_PENDING_OPERATIONS) {
try {
ArchivalSourceDAOFactory.openConnection();
ArchivalDestinationDAOFactory.openConnection();
List<Integer> pendingAndIPOperations = archivalDAO.getPendingAndInProgressOperations();
log.info(pendingAndIPOperations.size() +" P&IP Operations");
// Get the diff of operations
candidates.removeAll(pendingAndIPOperations);
} catch (ArchivalDAOException e) {
String msg = "Error occurred while retrieving the pending operations";
log.error(msg, e);
throw new ArchivalException(msg, e);
} catch (SQLException e) {
String msg = "An error occurred while connecting to the archival database";
log.error(msg, e);
throw new ArchivalException(msg, e);
} finally {
ArchivalSourceDAOFactory.closeConnection();
ArchivalDestinationDAOFactory.closeConnection();
if (totalLargeOpResCount > 0) {
int iterationCount = totalLargeOpResCount / EXECUTION_BATCH_SIZE;
int residualRecSize = 0;
if ((totalLargeOpResCount % EXECUTION_BATCH_SIZE) != 0) {
residualRecSize = totalLargeOpResCount % EXECUTION_BATCH_SIZE;
iterationCount++;
}
failAttempts = 0;
for (int iter = 0; iter < iterationCount; iter++) {
try {
if (iter == (iterationCount - 1)) {
archivalDAO.transferLargeOperationResponses(residualRecSize, currentTime, nonRemovableMappings);
archivalDAO.removeLargeOperationResponses(residualRecSize, currentTime, nonRemovableMappings);
} else {
archivalDAO.transferLargeOperationResponses(EXECUTION_BATCH_SIZE, currentTime, nonRemovableMappings);
archivalDAO.removeLargeOperationResponses(EXECUTION_BATCH_SIZE, currentTime, nonRemovableMappings);
}
commitTransactions();
failAttempts = 0;
} catch (ArchivalDAOException e) {
rollbackTransactions();
if (++failAttempts > 3) {
String msg = "Error occurred while trying to archive Large Operation Responses. Abort archiving.";
log.error(msg, e);
throw new ArchivalException(msg, e);
}
String msg = "Error occurred while trying to archive Large Operation Responses. " +
"Failed attempts: " + failAttempts + " Error: " + e.getMessage();
log.warn(msg);
iter--;
}
Thread.sleep(ARCHIVAL_LOCK_INTERVAL);
}
}
}
int total = candidates.size();
int batches = calculateNumberOfBatches(total);
log.info(total + " Operations ready for archiving. " + batches + " iterations to be done.");
int batchSize = EXECUTION_BATCH_SIZE;
if (log.isDebugEnabled()) {
log.debug(total + " Operations ready for archiving. " + batches + " iterations to be done.");
log.debug(batchSize + " is the batch size");
}
for (int i = 1; i <= batches; i++) {
int startIdx = batchSize * (i - 1);
int endIdx = batchSize * i;
if (i == batches) {
endIdx = startIdx + (total % batchSize);
}
if (log.isDebugEnabled()) {
log.debug("\n\n############ Iterating over batch " + i + "[" +
startIdx + "," + endIdx + "] #######");
}
List<Integer> subList = candidates.subList(startIdx, endIdx);
int totalOpResCount = archivalDAO.getOperationResponseCount(currentTime, nonRemovableMappings);
if (log.isDebugEnabled()) {
log.debug("SubList size is: " + subList.size());
if (subList.size() > 0) {
log.debug("First Element is: " + subList.get(0));
log.debug("Last Element is: " + subList.get(subList.size() - 1));
if (totalOpResCount > 0) {
int iterationCount = totalOpResCount / EXECUTION_BATCH_SIZE;
int residualRecSize = 0;
if ((totalOpResCount % EXECUTION_BATCH_SIZE) != 0) {
residualRecSize = totalOpResCount % EXECUTION_BATCH_SIZE;
iterationCount++;
}
}
if (log.isDebugEnabled()) {
for (Integer val : subList) {
if (log.isDebugEnabled()) {
log.debug("Sub List Element: " + val);
failAttempts = 0;
for (int iter = 0; iter < iterationCount; iter++) {
try {
if (iter == (iterationCount - 1)) {
archivalDAO.transferOperationResponses(residualRecSize, currentTime, nonRemovableMappings);
archivalDAO.removeOperationResponses(residualRecSize, currentTime, nonRemovableMappings);
} else {
archivalDAO.transferOperationResponses(EXECUTION_BATCH_SIZE, currentTime, nonRemovableMappings);
archivalDAO.removeOperationResponses(EXECUTION_BATCH_SIZE, currentTime, nonRemovableMappings);
}
commitTransactions();
failAttempts = 0;
} catch (ArchivalDAOException e) {
rollbackTransactions();
if (++failAttempts > 3) {
String msg = "Error occurred while trying to archive Operation Responses. Abort archiving.";
log.error(msg, e);
throw new ArchivalException(msg, e);
}
String msg = "Error occurred while trying to archive Operation Responses. " +
"Failed attempts: " + failAttempts + " Error: " + e.getMessage();
log.warn(msg);
iter--;
}
Thread.sleep(ARCHIVAL_LOCK_INTERVAL);
}
}
try {
beginTransactions();
prepareTempTable(subList);
commitTransactions();
} catch (Exception e) {
rollbackTransactions();
String msg = "Error occurred while preparing the operations.";
log.error(msg, e);
throw new ArchivalException(msg, e);
} finally {
ArchivalSourceDAOFactory.closeConnection();
ArchivalDestinationDAOFactory.closeConnection();
//Purge the notifications table, DM_NOTIFICATION
if (log.isDebugEnabled()) {
log.debug("## Archiving notifications");
}
List<ArchiveOperationResponse> operationResponses = null;
List<ArchiveNotification> notification = null;
List<ArchiveCommandOperation> commandOperations = null;
List<ArchiveProfileOperation> profileOperations = null;
List<ArchiveEnrolmentOperationMap> enrollmentMapping = null;
List<ArchiveOperation> operations = null;
try {
openConnection();
operationResponses = archivalDAO.selectOperationResponses();
notification = archivalDAO.selectNotifications();
enrollmentMapping = archivalDAO.selectEnrolmentMappings();
operations = archivalDAO.selectOperations();
} catch (Exception e) {
String msg = "Error occurred while retrieving data.";
log.error(msg, e);
throw new ArchivalException(msg, e);
} finally {
closeConnection();
archivalDAO.moveNotifications(currentTime);
commitTransactions();
//Purge the enrolment mappings table, DM_ENROLMENT_OP_MAPPING
if (log.isDebugEnabled()) {
log.debug("## Archiving enrolment mappings");
}
try {
beginTransactions();
//Purge the largest table, DM_DEVICE_OPERATION_RESPONSE
if (log.isDebugEnabled()) {
log.debug("## Archiving operation responses");
}
archivalDAO.moveOperationResponses(operationResponses);
//Purge the notifications table, DM_NOTIFICATION
if (log.isDebugEnabled()) {
log.debug("## Archiving notifications");
}
archivalDAO.moveNotifications(notification);
//Purge the enrolment mappings table, DM_ENROLMENT_OP_MAPPING
if (log.isDebugEnabled()) {
log.debug("## Archiving enrolment mappings");
}
archivalDAO.moveEnrolmentMappings(enrollmentMapping);
//Finally, purge the operations table, DM_OPERATION
if (log.isDebugEnabled()) {
log.debug("## Archiving operations");
int opMappingCount = archivalDAO.getOpMappingsCount(currentTime);
if (opMappingCount > 0) {
int iterationCount = opMappingCount / EXECUTION_BATCH_SIZE;
int residualRecSize = 0;
if ((opMappingCount % EXECUTION_BATCH_SIZE) != 0) {
residualRecSize = opMappingCount % EXECUTION_BATCH_SIZE;
iterationCount++;
}
archivalDAO.moveOperations(operations);
commitTransactions();
if (log.isDebugEnabled()) {
log.debug("End of Iteration : " + i);
failAttempts = 0;
for (int iter = 0; iter < iterationCount; iter++) {
try {
if (iter == (iterationCount - 1)) {
archivalDAO.transferEnrollmentOpMappings(residualRecSize, currentTime);
archivalDAO.removeEnrollmentOPMappings(residualRecSize, currentTime);
} else {
archivalDAO.transferEnrollmentOpMappings(EXECUTION_BATCH_SIZE, currentTime);
archivalDAO.removeEnrollmentOPMappings(EXECUTION_BATCH_SIZE, currentTime);
}
commitTransactions();
failAttempts = 0;
} catch (ArchivalDAOException e) {
rollbackTransactions();
if (++failAttempts > 3) {
String msg = "Error occurred while trying to archive Operation Enrollment Mappings. Abort archiving.";
log.error(msg, e);
throw new ArchivalException(msg, e);
}
String msg = "Error occurred while trying to archive Operation Enrollment Mappings. " +
"Failed attempts: " + failAttempts + " Error: " + e.getMessage();
log.warn(msg);
iter--;
}
Thread.sleep(ARCHIVAL_LOCK_INTERVAL);
}
} catch (ArchivalDAOException e) {
rollbackTransactions();
String msg = "Error occurred while trying to archive data to the six tables";
log.error(msg, e);
throw new ArchivalException(msg, e);
} finally {
ArchivalSourceDAOFactory.closeConnection();
ArchivalDestinationDAOFactory.closeConnection();
}
}
}
//Finally, purge the operations table, DM_OPERATION
if (log.isDebugEnabled()) {
log.debug("## Archiving operations");
}
private void prepareTempTable(List<Integer> subList) throws ArchivalDAOException {
//Clean up the DM_ARCHIVED_OPERATIONS table
if (log.isDebugEnabled()) {
log.debug("## Truncating the temporary table");
}
archivalDAO.truncateOperationIDsForArchival();
if (log.isDebugEnabled()) {
log.debug("## Inserting into the temporary table");
archivalDAO.transferOperations();
archivalDAO.removeOperations();
commitTransactions();
} catch (ArchivalDAOException e) {
rollbackTransactions();
String msg = "Error occurred while trying to archive data to the six tables";
log.error(msg, e);
throw new ArchivalException(msg, e);
} catch (InterruptedException e) {
rollbackTransactions();
String msg = "Error while halting archival thread to free up table locks.";
log.error(msg, e);
throw new ArchivalException(msg, e);
} finally {
ArchivalSourceDAOFactory.closeConnection();
ArchivalDestinationDAOFactory.closeConnection();
}
archivalDAO.copyOperationIDsForArchival(subList);
}
private void beginTransactions() throws ArchivalException {
@ -247,28 +220,6 @@ public class ArchivalServiceImpl implements ArchivalService {
}
}
private void openConnection() throws ArchivalException {
try {
ArchivalSourceDAOFactory.openConnection();
} catch (SQLException e) {
String msg = "An error occurred during opening connection";
log.error(msg, e);
throw new ArchivalException(msg, e);
}
}
private void closeConnection() throws ArchivalException {
try {
ArchivalSourceDAOFactory.closeConnection();
} catch (Exception e) {
String msg = "An error occurred during opening connection";
log.error(msg, e);
throw new ArchivalException(msg, e);
}
}
private void commitTransactions() {
ArchivalSourceDAOFactory.commitTransaction();
ArchivalDestinationDAOFactory.commitTransaction();
@ -279,22 +230,16 @@ public class ArchivalServiceImpl implements ArchivalService {
ArchivalDestinationDAOFactory.rollbackTransaction();
}
private int calculateNumberOfBatches(int total) {
int batches = 0;
int batchSize = EXECUTION_BATCH_SIZE;
if ((total % batchSize) > 0) {
batches = (total / batchSize) + 1;
} else {
batches = total / batchSize;
}
return batches;
}
@Override
public void deleteArchivedRecords() throws ArchivalException {
try {
ArchivalDestinationDAOFactory.openConnection();
if (log.isDebugEnabled()) {
log.debug("## Deleting Large operation responses");
}
dataDeletionDAO.deleteLargeOperationResponses();
if (log.isDebugEnabled()) {
log.debug("## Deleting operation responses");
}
@ -305,16 +250,6 @@ public class ArchivalServiceImpl implements ArchivalService {
}
dataDeletionDAO.deleteNotifications();
if (log.isDebugEnabled()) {
log.debug("## Deleting command operations");
}
dataDeletionDAO.deleteCommandOperations();
if (log.isDebugEnabled()) {
log.debug("## Deleting profile operations ");
}
dataDeletionDAO.deleteProfileOperations();
if (log.isDebugEnabled()) {
log.debug("## Deleting enrolment mappings ");
}
@ -332,4 +267,4 @@ public class ArchivalServiceImpl implements ArchivalService {
ArchivalDestinationDAOFactory.closeConnection();
}
}
}
}

@ -1,44 +0,0 @@
/*
* Copyright (c) 2018, 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.archival.beans;
public class ArchiveCommandOperation {
private int operationId;
private int enabled;
public int getOperationId() {
return operationId;
}
public void setOperationId(int operationId) {
this.operationId = operationId;
}
public int getEnabled() {
return enabled;
}
public void setEnabled(int enabled) {
this.enabled = enabled;
}
}

@ -1,80 +0,0 @@
/*
* Copyright (c) 2018, 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.archival.beans;
public class ArchiveEnrolmentOperationMap {
private int id;
private int enrolmentId;
private int operationId;
private String status;
private int createdTimestamp;
private int updatedTimestamp;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getEnrolmentId() {
return enrolmentId;
}
public void setEnrolmentId(int enrolmentId) {
this.enrolmentId = enrolmentId;
}
public int getOperationId() {
return operationId;
}
public void setOperationId(int operationId) {
this.operationId = operationId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getCreatedTimestamp() {
return createdTimestamp;
}
public void setCreatedTimestamp(int createdTimestamp) {
this.createdTimestamp = createdTimestamp;
}
public int getUpdatedTimestamp() {
return updatedTimestamp;
}
public void setUpdatedTimestamp(int updatedTimestamp) {
this.updatedTimestamp = updatedTimestamp;
}
}

@ -1,80 +0,0 @@
/*
* Copyright (c) 2018, 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.archival.beans;
public class ArchiveNotification {
private int notificationId;
private int deviceId;
private int operationId;
private int tenantId;
private String status;
private String description;
public int getNotificationId() {
return notificationId;
}
public void setNotificationId(int notificationId) {
this.notificationId = notificationId;
}
public int getDeviceId() {
return deviceId;
}
public void setDeviceId(int deviceId) {
this.deviceId = deviceId;
}
public int getOperationId() {
return operationId;
}
public void setOperationId(int operationId) {
this.operationId = operationId;
}
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

@ -1,100 +0,0 @@
/*
* Copyright (c) 2018, 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.archival.beans;
import java.sql.Timestamp;
public class ArchiveOperation {
private int id;
private String type;
private Timestamp createdTimeStamp;
private Timestamp recievedTimeStamp;
private String operationCode;
private Object operationDetails;
private String initiatedBy;
private boolean enabled;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Timestamp getCreatedTimeStamp() {
return createdTimeStamp;
}
public void setCreatedTimeStamp(Timestamp createdTimeStamp) {
this.createdTimeStamp = createdTimeStamp;
}
public Timestamp getRecievedTimeStamp() {
return recievedTimeStamp;
}
public void setRecievedTimeStamp(Timestamp recievedTimeStamp) {
this.recievedTimeStamp = recievedTimeStamp;
}
public String getOperationCode() {
return operationCode;
}
public void setOperationCode(String operationCode) {
this.operationCode = operationCode;
}
public Object getOperationDetails() {
return operationDetails;
}
public void setOperationDetails(Object operationDetails) {
this.operationDetails = operationDetails;
}
public String getInitiatedBy() {
return initiatedBy;
}
public void setInitiatedBy(String initiatedBy) {
this.initiatedBy = initiatedBy;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}

@ -1,83 +0,0 @@
/*
* Copyright (c) 2018, 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.archival.beans;
import java.sql.Timestamp;
public class ArchiveOperationResponse {
private int id;
private int enrolmentId;
private int operationId;
private int enOpMapId;
private Object operationResponse;
private Timestamp receivedTimeStamp;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getEnrolmentId() {
return enrolmentId;
}
public void setEnrolmentId(int enrolmentId) {
this.enrolmentId = enrolmentId;
}
public int getOperationId() {
return operationId;
}
public void setOperationId(int operationId) {
this.operationId = operationId;
}
public int getEnOpMapId() {
return enOpMapId;
}
public void setEnOpMapId(int enOpMapId) {
this.enOpMapId = enOpMapId;
}
public Object getOperationResponse() {
return operationResponse;
}
public void setOperationResponse(Object operationResponse) {
this.operationResponse = operationResponse;
}
public Timestamp getReceivedTimeStamp() {
return receivedTimeStamp;
}
public void setReceivedTimeStamp(Timestamp receivedTimeStamp) {
this.receivedTimeStamp = receivedTimeStamp;
}
}

@ -1,53 +0,0 @@
/*
* Copyright (c) 2018, 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.archival.beans;
public class ArchiveProfileOperation {
private int operationId;
private int enabled;
private Object operationDetails;
public int getOperationId() {
return operationId;
}
public void setOperationId(int operationId) {
this.operationId = operationId;
}
public int getEnabled() {
return enabled;
}
public void setEnabled(int enabled) {
this.enabled = enabled;
}
public Object getOperationDetails() {
return operationDetails;
}
public void setOperationDetails(Object operationDetails) {
this.operationDetails = operationDetails;
}
}

@ -18,9 +18,7 @@
package org.wso2.carbon.device.mgt.core.archival.dao;
import org.wso2.carbon.device.mgt.core.archival.beans.*;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.List;
/**
@ -28,34 +26,30 @@ import java.util.List;
*/
public interface ArchivalDAO {
int DEFAULT_BATCH_SIZE = 1000;
List<Integer> getAllOperations() throws ArchivalDAOException;
List<Integer> getPendingAndInProgressOperations() throws ArchivalDAOException;
List<Integer> getNonRemovableOperationMappingIDs(Timestamp time) throws ArchivalDAOException;
void copyOperationIDsForArchival(List<Integer> operationIds) throws ArchivalDAOException;
int getLargeOperationResponseCount(Timestamp time, List<Integer> nonRemovableMappings) throws ArchivalDAOException;
List<ArchiveOperationResponse> selectOperationResponses() throws ArchivalDAOException;
int getOpMappingsCount(Timestamp time) throws ArchivalDAOException;
void moveOperationResponses(List<ArchiveOperationResponse> rs) throws ArchivalDAOException;
int getOperationResponseCount(Timestamp time, List<Integer> nonRemovableMappings) throws ArchivalDAOException;
List<ArchiveNotification> selectNotifications() throws ArchivalDAOException;
void transferOperationResponses(int batchSize, Timestamp time, List<Integer> nonRemovableMappings) throws ArchivalDAOException;
void moveNotifications(List<ArchiveNotification> rs) throws ArchivalDAOException;
void transferLargeOperationResponses(int batchSize, Timestamp time, List<Integer> nonRemovableMappings) throws ArchivalDAOException;
List<ArchiveCommandOperation> selectCommandOperations() throws ArchivalDAOException;
void removeLargeOperationResponses(int batchSize, Timestamp time, List<Integer> nonRemovableMappings) throws ArchivalDAOException;
List<ArchiveProfileOperation> selectProfileOperations() throws ArchivalDAOException;
void removeOperationResponses(int batchSize, Timestamp time, List<Integer> nonRemovableMappings) throws ArchivalDAOException;
List<ArchiveEnrolmentOperationMap> selectEnrolmentMappings() throws ArchivalDAOException;
void moveNotifications(Timestamp time) throws ArchivalDAOException;
void moveEnrolmentMappings(List<ArchiveEnrolmentOperationMap> rs) throws ArchivalDAOException;
void transferEnrollmentOpMappings(int batchSize, Timestamp time) throws ArchivalDAOException;
List<ArchiveOperation> selectOperations() throws ArchivalDAOException;
void removeEnrollmentOPMappings(int batchSize, Timestamp time) throws ArchivalDAOException;
void moveOperations(List<ArchiveOperation> rs) throws ArchivalDAOException;
void transferOperations() throws ArchivalDAOException;
void truncateOperationIDsForArchival() throws ArchivalDAOException;
void removeOperations() throws ArchivalDAOException;
}

@ -57,14 +57,4 @@ public class ArchivalDAOUtil {
}
}
public static void cleanupResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing the result set", e);
}
}
}
}

@ -39,8 +39,7 @@ public class ArchivalDestinationDAOFactory {
private static final Log log = LogFactory.getLog(OperationManagementDAOFactory.class);
private static DataSource dataSource;
private static String databaseEngine;
private static int retentionPeriod;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
public static DataDeletionDAO getDataDeletionDAO() {
return new DataDeletionDAOImpl(DeviceConfigurationManager.getInstance().getDeviceManagementConfig()
@ -77,6 +76,16 @@ public class ArchivalDestinationDAOFactory {
}
}
public static void beginTransaction(Connection conn) throws TransactionManagementException {
try {
conn.setAutoCommit(false);
// currentConnection.set(conn);
} catch (SQLException e) {
throw new TransactionManagementException(
"Error occurred while retrieving config.datasource connection", e);
}
}
public static void openConnection() throws SQLException {
currentConnection.set(dataSource.getConnection());
}
@ -102,6 +111,16 @@ public class ArchivalDestinationDAOFactory {
}
}
public static void closeConnection(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.error("Error occurred while close the connection");
}
}
}
public static void commitTransaction() {
try {
Connection conn = currentConnection.get();
@ -118,6 +137,21 @@ public class ArchivalDestinationDAOFactory {
}
}
public static void commitTransaction(Connection conn) {
try {
if (conn != null) {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit " +
"has not been attempted");
}
}
} catch (SQLException e) {
log.error("Error occurred while committing the transaction", e);
}
}
public static void rollbackTransaction() {
try {
Connection conn = currentConnection.get();
@ -153,7 +187,7 @@ public class ArchivalDestinationDAOFactory {
}
List<JNDILookupDefinition.JNDIProperty> jndiPropertyList = jndiConfig.getJndiProperties();
if (jndiPropertyList != null) {
Hashtable<Object, Object> jndiProperties = new Hashtable<Object, Object>();
Hashtable<Object, Object> jndiProperties = new Hashtable<>();
for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) {
jndiProperties.put(prop.getName(), prop.getValue());
}

@ -18,7 +18,6 @@
package org.wso2.carbon.device.mgt.core.archival.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.exceptions.IllegalTransactionStateException;

@ -23,16 +23,12 @@ package org.wso2.carbon.device.mgt.core.archival.dao;
*/
public interface DataDeletionDAO {
int DEFAULT_RETENTION_PERIOD = 364;
void deleteLargeOperationResponses() throws ArchivalDAOException;
void deleteOperationResponses() throws ArchivalDAOException;
void deleteNotifications() throws ArchivalDAOException;
void deleteCommandOperations() throws ArchivalDAOException;
void deleteProfileOperations() throws ArchivalDAOException;
void deleteEnrolmentMappings() throws ArchivalDAOException;
void deleteOperations() throws ArchivalDAOException;

@ -18,14 +18,13 @@
package org.wso2.carbon.device.mgt.core.archival.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.core.archival.dao.DataDeletionDAO;
import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDAOException;
import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDAOUtil;
import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDestinationDAOFactory;
import org.wso2.carbon.device.mgt.core.task.impl.ArchivedDataDeletionTask;
import org.wso2.carbon.device.mgt.core.archival.dao.DataDeletionDAO;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
@ -34,7 +33,11 @@ import java.sql.SQLException;
public class DataDeletionDAOImpl implements DataDeletionDAO {
private static Log log = LogFactory.getLog(DataDeletionDAOImpl.class);
private int retentionPeriod = DataDeletionDAO.DEFAULT_RETENTION_PERIOD;
private int retentionPeriod;
private static final String DESTINATION_DB =
DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getArchivalConfiguration()
.getArchivalTaskConfiguration().getDbConfig().getDestinationDB();
public DataDeletionDAOImpl(int retentionPeriod) {
this.retentionPeriod = retentionPeriod;
@ -49,7 +52,7 @@ public class DataDeletionDAOImpl implements DataDeletionDAO {
try {
Connection conn = ArchivalDestinationDAOFactory.getConnection();
conn.setAutoCommit(false);
String sql = "DELETE FROM DM_DEVICE_OPERATION_RESPONSE_ARCH " +
String sql = "DELETE FROM "+ DESTINATION_DB +".DM_DEVICE_OPERATION_RESPONSE_ARCH " +
"WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, this.retentionPeriod);
@ -63,57 +66,38 @@ public class DataDeletionDAOImpl implements DataDeletionDAO {
}
@Override
public void deleteNotifications() throws ArchivalDAOException {
PreparedStatement stmt = null;
try {
Connection conn = ArchivalDestinationDAOFactory.getConnection();
conn.setAutoCommit(false);
String sql = "DELETE FROM DM_NOTIFICATION_ARCH" +
" WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, this.retentionPeriod);
stmt.executeUpdate();
conn.commit();
} catch (SQLException e) {
throw new ArchivalDAOException("Error occurred while deleting notifications", e);
} finally {
ArchivalDAOUtil.cleanupResources(stmt);
}
}
@Override
public void deleteCommandOperations() throws ArchivalDAOException {
public void deleteLargeOperationResponses() throws ArchivalDAOException {
PreparedStatement stmt = null;
try {
Connection conn = ArchivalDestinationDAOFactory.getConnection();
conn.setAutoCommit(false);
String sql = "DELETE FROM DM_COMMAND_OPERATION_ARCH" +
" WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)";
String sql = "DELETE FROM "+ DESTINATION_DB +".DM_DEVICE_OPERATION_RESPONSE_LARGE_ARCH " +
"WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, this.retentionPeriod);
stmt.executeUpdate();
conn.commit();
} catch (SQLException e) {
throw new ArchivalDAOException("Error occurred while deleting command operations", e);
throw new ArchivalDAOException("Error occurred while deleting operation responses", e);
} finally {
ArchivalDAOUtil.cleanupResources(stmt);
}
}
@Override
public void deleteProfileOperations() throws ArchivalDAOException {
public void deleteNotifications() throws ArchivalDAOException {
PreparedStatement stmt = null;
try {
Connection conn = ArchivalDestinationDAOFactory.getConnection();
conn.setAutoCommit(false);
String sql = "DELETE FROM DM_PROFILE_OPERATION_ARCH" +
String sql = "DELETE FROM "+ DESTINATION_DB +".DM_NOTIFICATION_ARCH" +
" WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, this.retentionPeriod);
stmt.executeUpdate();
conn.commit();
} catch (SQLException e) {
throw new ArchivalDAOException("Error occurred while deleting profile operations", e);
throw new ArchivalDAOException("Error occurred while deleting notifications", e);
} finally {
ArchivalDAOUtil.cleanupResources(stmt);
}
@ -125,7 +109,7 @@ public class DataDeletionDAOImpl implements DataDeletionDAO {
try {
Connection conn = ArchivalDestinationDAOFactory.getConnection();
conn.setAutoCommit(false);
String sql = "DELETE FROM DM_ENROLMENT_OP_MAPPING_ARCH WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)";
String sql = "DELETE FROM "+ DESTINATION_DB + ".DM_ENROLMENT_OP_MAPPING_ARCH WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, this.retentionPeriod);
stmt.executeUpdate();
@ -143,7 +127,7 @@ public class DataDeletionDAOImpl implements DataDeletionDAO {
try {
Connection conn = ArchivalDestinationDAOFactory.getConnection();
conn.setAutoCommit(false);
String sql = "DELETE FROM DM_OPERATION_ARCH WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)";
String sql = "DELETE FROM "+ DESTINATION_DB +".DM_OPERATION_ARCH WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, this.retentionPeriod);
stmt.executeUpdate();

@ -269,16 +269,4 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori
permission.setPath(PermissionUtils.getAbsolutePermissionPath(CDM_ADMIN_PERMISSION));
return PermissionUtils.putPermission(permission);
}
public static final class PermissionMethod {
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";
private PermissionMethod() {
throw new AssertionError();
}
}
}

@ -28,8 +28,28 @@ public class ArchivalTaskConfiguration {
private String taskClazz;
private int retentionPeriod;
private int batchSize;
private int archivalLockInterval;
private PurgingTaskConfiguration purgingTaskConfiguration;
private boolean archivePendingOperations;
private DBConfig dbConfig;
@XmlElement(name = "ArchivalLockInterval", required = true)
public int getArchivalLockInterval() {
return archivalLockInterval;
}
public void setArchivalLockInterval(int archivalLockInterval) {
this.archivalLockInterval = archivalLockInterval;
}
@XmlElement(name = "DBConfig", required = true)
public DBConfig getDbConfig() {
return dbConfig;
}
public void setDbConfig(DBConfig dbConfig) {
this.dbConfig = dbConfig;
}
@XmlElement(name = "Enabled", required = true)
public boolean isEnabled() {

@ -0,0 +1,51 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.config.archival;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* This class represents the information related to data archival configurations.
*/
@XmlRootElement(name = "DBConfig")
public class DBConfig {
private String destinationDB;
private String sourceDB;
@XmlElement(name = "DestinationDB", required = true)
public String getDestinationDB() {
return destinationDB;
}
public void setDestinationDB(String destinationDB) {
this.destinationDB = destinationDB;
}
@XmlElement(name = "SourceDB", required = true)
public String getSourceDB() {
return sourceDB;
}
public void setSourceDB(String sourceDB) {
this.sourceDB = sourceDB;
}
}

@ -15,23 +15,6 @@
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
@ -409,13 +392,13 @@ public interface DeviceDAO {
*/
int getDeviceCount(PaginationRequest request, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve the available device types of a given tenant.
*
* @return returns list of device types.
* @throws DeviceManagementDAOException
*/
List<DeviceType> getDeviceTypes() throws DeviceManagementDAOException;
/**
* This method is used to retrieve the available device types of a given tenant.
*
* @return returns list of device types.
* @throws DeviceManagementDAOException
*/
List<DeviceType> getDeviceTypes() throws DeviceManagementDAOException;
/**
* This method is used to retrieve devices of a given device name.
@ -426,7 +409,7 @@ public interface DeviceDAO {
* @throws DeviceManagementDAOException
*/
List<Device> getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit)
throws DeviceManagementDAOException;
throws DeviceManagementDAOException;
/**
* This method is used to retrieve devices of a given device name as a paginated result.

@ -28,18 +28,12 @@ public interface EnrollmentDAO {
EnrolmentInfo 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 updateEnrollment(EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementDAOException;
boolean updateEnrollmentStatus(List<EnrolmentInfo> enrolmentInfos) throws DeviceManagementDAOException;
int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException;
boolean setStatus(int enrolmentId, String currentOwner, Status status,
int tenantId) throws DeviceManagementDAOException;
boolean setStatus(String currentOwner, Status status, int tenantId) throws DeviceManagementDAOException;
boolean setStatus(int enrolmentId, Status status, int tenantId) throws DeviceManagementDAOException;
@ -48,6 +42,8 @@ public interface EnrollmentDAO {
EnrolmentInfo getEnrollment(int deviceId, String currentUser, int tenantId) throws DeviceManagementDAOException;
EnrolmentInfo getEnrollment(int deviceId, int tenantId) throws DeviceManagementDAOException;
List<EnrolmentInfo> getEnrollmentsOfUser(int deviceId, String user, int tenantId) throws
DeviceManagementDAOException;

@ -16,23 +16,6 @@
* under the License.
*
*/
/*
* Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
@ -170,6 +153,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
+ "e.OWNER, "
+ "e.OWNERSHIP, "
+ "e.STATUS, "
+ "e.IS_TRANSFERRED, "
+ "e.DATE_OF_LAST_UPDATE, "
+ "e.DATE_OF_ENROLMENT, "
+ "e.ID AS ENROLMENT_ID "
@ -247,7 +231,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
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, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, 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 t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " +
@ -286,20 +270,20 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
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.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 " +
"WHERE " +
"d1.ID = e.DEVICE_ID " +
"AND TENANT_ID = ? " +
"ORDER BY e.DATE_OF_LAST_UPDATE DESC, e.STATUS ASC";
"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.IS_TRANSFERRED, 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.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 " +
"WHERE " +
"d1.ID = e.DEVICE_ID " +
"AND TENANT_ID = ? " +
"ORDER BY e.DATE_OF_LAST_UPDATE DESC, e.STATUS ASC";
// Status adeed as an orderby clause to fix a bug : when an existing device is
// re-enrolled, earlier enrollment is marked as removed and a new enrollment is added.
// However, both enrollments share the same time stamp. When retrieving the device
@ -334,7 +318,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
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, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, 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 t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " +
@ -368,7 +352,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
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, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, 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, DM_DEVICE_DETAIL dt " +
"WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " +
@ -394,7 +378,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
}
@Override
public List<Device> getDeviceBasedOnDeviceProperties(Map<String,String> deviceProps, int tenantId)
public List<Device> getDeviceBasedOnDeviceProperties(Map<String, String> deviceProps, int tenantId)
throws DeviceManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
@ -407,8 +391,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
for (Map.Entry<String, String> entry : deviceProps.entrySet()) {
stmt = conn.prepareStatement("SELECT DEVICE_IDENTIFICATION FROM DM_DEVICE_PROPERTIES " +
"WHERE (PROPERTY_NAME , PROPERTY_VALUE) IN " +
"((? , ?)) AND TENANT_ID = ?");
"WHERE (PROPERTY_NAME , PROPERTY_VALUE) IN " +
"((? , ?)) AND TENANT_ID = ?");
stmt.setString(1, entry.getKey());
stmt.setString(2, entry.getValue());
stmt.setInt(3, tenantId);
@ -421,7 +405,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
outputLists.add(deviceList);
}
List<String> deviceIds = findIntersection(outputLists);
for(String deviceId : deviceIds){
for (String deviceId : deviceIds) {
devices.add(getDeviceProps(deviceId, tenantId));
}
} catch (SQLException e) {
@ -445,15 +429,15 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
conn = this.getConnection();
List<List<DevicePropertyInfo>> outputLists = new ArrayList<>();
String sql = "SELECT " +
"p.DEVICE_IDENTIFICATION, " +
"p.DEVICE_TYPE_NAME, " +
"p.TENANT_ID FROM " +
"DM_DEVICE_PROPERTIES p ";
"p.DEVICE_IDENTIFICATION, " +
"p.DEVICE_TYPE_NAME, " +
"p.TENANT_ID FROM " +
"DM_DEVICE_PROPERTIES p ";
String groupByClause = "GROUP BY " +
"p.DEVICE_IDENTIFICATION, " +
"p.DEVICE_TYPE_NAME, " +
"p.TENANT_ID";
"p.DEVICE_IDENTIFICATION, " +
"p.DEVICE_TYPE_NAME, " +
"p.TENANT_ID";
int iterationCount = 0;
StringBuilder propertyQuery = new StringBuilder(" ");
@ -558,22 +542,22 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
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," +
" DM_DEVICE_DETAIL dt " +
"WHERE " +
"t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND" +
" dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?) d1 " +
"WHERE" +
" d1.ID = e.DEVICE_ID AND TENANT_ID = ? " +
"ORDER BY " +
"e.DATE_OF_LAST_UPDATE DESC";
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, 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," +
" DM_DEVICE_DETAIL dt " +
"WHERE " +
"t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND" +
" dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?) d1 " +
"WHERE" +
" d1.ID = e.DEVICE_ID AND TENANT_ID = ? " +
"ORDER BY " +
"e.DATE_OF_LAST_UPDATE DESC";
stmt = conn.prepareStatement(sql);
int paramIdx = 1;
stmt.setString(paramIdx++, deviceIdentifier);
@ -603,7 +587,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
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, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, 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, DM_DEVICE_DETAIL dt " +
"WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " +
@ -638,7 +622,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
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, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, 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 t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " +
@ -668,30 +652,31 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try {
Connection conn = this.getConnection();
String sql = "SELECT d1.ID AS DEVICE_ID, " +
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"e.TENANT_ID, " +
"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 t.ID = d.DEVICE_TYPE_ID " +
"AND d.DEVICE_IDENTIFICATION = ?) d1 " +
"WHERE d1.ID = e.DEVICE_ID " +
"ORDER BY e.DATE_OF_LAST_UPDATE DESC";
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"e.TENANT_ID, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"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 t.ID = d.DEVICE_TYPE_ID " +
"AND d.DEVICE_IDENTIFICATION = ?) d1 " +
"WHERE d1.ID = e.DEVICE_ID " +
"ORDER BY e.DATE_OF_LAST_UPDATE DESC";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, deviceIdentifier.getType());
@ -711,7 +696,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
} catch (SQLException e) {
String msg = "Error occurred while listing devices (with tenant id) for type " +
deviceIdentifier.getType();
deviceIdentifier.getType();
log.error(msg);
throw new DeviceManagementDAOException(msg, e);
}
@ -726,7 +711,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
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, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, 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 " +
"d.ID = ? AND t.ID = d.DEVICE_TYPE_ID AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " +
@ -753,11 +738,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> devices = null;
List<Device> devices;
try {
conn = this.getConnection();
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " +
@ -789,7 +774,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
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, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, 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, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " +
@ -823,10 +808,10 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
List<Device> devices = new ArrayList<>();
try {
conn = this.getConnection();
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," +
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.IS_TRANSFERRED, e1.DATE_OF_LAST_UPDATE," +
" e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " +
"AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " +
"e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " +
"e.DEVICE_ID, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " +
"e.TENANT_ID = ? AND LOWER(e.OWNER) = LOWER(?)) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " +
"AND t.ID = d.DEVICE_TYPE_ID ORDER BY e1.DATE_OF_LAST_UPDATE DESC";
stmt = conn.prepareStatement(sql);
@ -856,10 +841,10 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
List<Device> devices = new ArrayList<>();
try {
conn = this.getConnection();
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," +
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.IS_TRANSFERRED, e1.DATE_OF_LAST_UPDATE," +
" e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " +
"AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " +
"e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " +
"e.DEVICE_ID, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " +
"e.TENANT_ID = ? AND LOWER(e.OWNER) = LOWER(?) ORDER BY e.DATE_OF_LAST_UPDATE DESC) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " +
"AND t.ID = d.DEVICE_TYPE_ID AND t.NAME= ?";
stmt = conn.prepareStatement(sql);
@ -1189,15 +1174,15 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try {
Connection conn = getConnection();
String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT " +
"FROM DM_ENROLMENT e, " +
"(SELECT " +
"d.ID, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"DM_DEVICE d, " +
"DM_DEVICE_TYPE t";
"FROM DM_ENROLMENT e, " +
"(SELECT " +
"d.ID, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"DM_DEVICE d, " +
"DM_DEVICE_TYPE t";
//Add query for last updated timestamp
if (since != null) {
sql = sql + " , DM_DEVICE_DETAIL dt";
@ -1270,7 +1255,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving information of all " +
"registered devices", e);
"registered devices", e);
}
}
@ -1449,16 +1434,17 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
int enrolmentId = -1;
try {
conn = this.getConnection();
String sql = "INSERT INTO DM_ENROLMENT(DEVICE_ID, OWNER, OWNERSHIP, STATUS,DATE_OF_ENROLMENT, " +
"DATE_OF_LAST_UPDATE, TENANT_ID) VALUES(?, ?, ?, ?, ?, ?, ?)";
String sql = "INSERT INTO DM_ENROLMENT(DEVICE_ID, OWNER, OWNERSHIP, STATUS, IS_TRANSFERRED, " +
"DATE_OF_ENROLMENT, DATE_OF_LAST_UPDATE, TENANT_ID) VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, new String[]{"id"});
stmt.setInt(1, device.getId());
stmt.setString(2, device.getEnrolmentInfo().getOwner());
stmt.setString(3, device.getEnrolmentInfo().getOwnership().toString());
stmt.setString(4, device.getEnrolmentInfo().getStatus().toString());
stmt.setTimestamp(5, new Timestamp(new Date().getTime()));
stmt.setBoolean(5, device.getEnrolmentInfo().isTransferred());
stmt.setTimestamp(6, new Timestamp(new Date().getTime()));
stmt.setInt(7, tenantId);
stmt.setTimestamp(7, new Timestamp(new Date().getTime()));
stmt.setInt(8, tenantId);
stmt.execute();
rs = stmt.getGeneratedKeys();
@ -1542,6 +1528,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
+ "OWNER, "
+ "OWNERSHIP, "
+ "STATUS, "
+ "IS_TRANSFERRED, "
+ "DATE_OF_ENROLMENT, "
+ "DATE_OF_LAST_UPDATE, "
+ "TENANT_ID "
@ -1589,7 +1576,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
EnrolmentInfo enrolmentInfo = null;
try {
conn = this.getConnection();
String sql = "SELECT ID AS ENROLMENT_ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " +
String sql = "SELECT ID AS ENROLMENT_ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, IS_TRANSFERRED, DATE_OF_ENROLMENT, " +
"DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID " +
"FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " +
"AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " +
@ -1622,9 +1609,9 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try {
conn = this.getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e" +
".OWNERSHIP, e.STATUS, e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS " +
".OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS " +
"ENROLMENT_ID FROM DM_ENROLMENT e WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
@ -1687,7 +1674,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try {
conn = this.getConnection();
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE, d.LAST_UPDATED_TIMESTAMP FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? AND d.LAST_UPDATED_TIMESTAMP < CURRENT_TIMESTAMP) d1 " +
@ -1805,8 +1792,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
StringJoiner joiner = new StringJoiner(",",
"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 "
+ "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, "
+ "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 "
@ -1854,11 +1841,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
String sql =
"SELECT DEVICE_ID, TENANT_ID, DEVICE_ID_NAME, DEVICE_TYPE_NAME, LATITUDE, LONGITUDE, SPEED, " +
"HEADING, TIMESTAMP, GEO_HASH, DEVICE_OWNER, DEVICE_ALTITUDE, DISTANCE " +
"FROM DM_DEVICE_HISTORY_LAST_SEVEN_DAYS " +
"WHERE DEVICE_ID_NAME = ? " +
"AND DEVICE_TYPE_NAME = ? " +
"AND TIMESTAMP >= ? " +
"AND TIMESTAMP <= ?";
"FROM DM_DEVICE_HISTORY_LAST_SEVEN_DAYS " +
"WHERE DEVICE_ID_NAME = ? " +
"AND DEVICE_TYPE_NAME = ? " +
"AND TIMESTAMP >= ? " +
"AND TIMESTAMP <= ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceIdentifier.getId());
@ -1962,24 +1949,25 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
boolean isVersionProvided = false;
String sql = "SELECT " +
"d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_DEVICE AS d " +
"INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " +
"INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " +
"WHERE " +
"t.NAME = ? AND e.TENANT_ID = ? AND d.ID " +
"NOT IN " +
"(SELECT a.DEVICE_ID FROM DM_APPLICATION AS a WHERE a.APP_IDENTIFIER = ?";
"d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_DEVICE AS d " +
"INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " +
"INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " +
"WHERE " +
"t.NAME = ? AND e.TENANT_ID = ? AND d.ID " +
"NOT IN " +
"(SELECT a.DEVICE_ID FROM DM_APPLICATION AS a WHERE a.APP_IDENTIFIER = ?";
if (!StringUtils.isBlank(version)) {
sql = sql + " AND a.VERSION = ? ";
@ -2026,14 +2014,14 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
boolean isVersionProvided = false;
String sql = "SELECT " +
"COUNT(d.ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE AS d " +
"INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " +
"INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " +
"WHERE " +
"t.NAME = ? AND e.TENANT_ID = ? AND d.ID " +
"NOT IN " +
"(SELECT a.DEVICE_ID FROM DM_APPLICATION AS a WHERE a.APP_IDENTIFIER = ?";
"COUNT(d.ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE AS d " +
"INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " +
"INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " +
"WHERE " +
"t.NAME = ? AND e.TENANT_ID = ? AND d.ID " +
"NOT IN " +
"(SELECT a.DEVICE_ID FROM DM_APPLICATION AS a WHERE a.APP_IDENTIFIER = ?";
if (!StringUtils.isBlank(version)) {
sql = sql + " AND a.VERSION = ? ";

@ -57,7 +57,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql;
if(deviceGroup.getStatus() == null || deviceGroup.getStatus().isEmpty()){
if (deviceGroup.getStatus() == null || deviceGroup.getStatus().isEmpty()) {
sql = "INSERT INTO DM_GROUP(DESCRIPTION, GROUP_NAME, OWNER, TENANT_ID) VALUES (?, ?, ?, ?)";
} else {
sql = "INSERT INTO DM_GROUP(DESCRIPTION, GROUP_NAME, OWNER, TENANT_ID, STATUS) VALUES (?, ?, ?, ?, ?)";
@ -68,7 +68,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
stmt.setString(2, deviceGroup.getName());
stmt.setString(3, deviceGroup.getOwner());
stmt.setInt(4, tenantId);
if(hasStatus) {
if (hasStatus) {
stmt.setString(5, deviceGroup.getStatus());
}
@ -94,7 +94,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
Connection conn = GroupManagementDAOFactory.getConnection();
stmt = conn.prepareStatement(
"INSERT INTO GROUP_PROPERTIES(GROUP_ID, PROPERTY_NAME, " +
"PROPERTY_VALUE, TENANT_ID) VALUES (?, ?, ?, ?)");
"PROPERTY_VALUE, TENANT_ID) VALUES (?, ?, ?, ?)");
for (Map.Entry<String, String> entry : deviceGroup.getGroupProperties().entrySet()) {
stmt.setInt(1, groupId);
stmt.setString(2, entry.getKey());
@ -106,7 +106,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
status = true;
} catch (SQLException e) {
String msg = "Error occurred while adding properties for group '" +
deviceGroup.getName() + "' values : " + deviceGroup.getGroupProperties();
deviceGroup.getName() + "' values : " + deviceGroup.getGroupProperties();
throw new GroupManagementDAOException(msg, e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, null);
@ -122,7 +122,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
Connection conn = GroupManagementDAOFactory.getConnection();
stmt = conn.prepareStatement(
"UPDATE GROUP_PROPERTIES SET PROPERTY_VALUE = ? WHERE GROUP_ID = ? AND " +
"TENANT_ID = ? AND PROPERTY_NAME = ?");
"TENANT_ID = ? AND PROPERTY_NAME = ?");
for (Map.Entry<String, String> entry : deviceGroup.getGroupProperties().entrySet()) {
stmt.setString(1, entry.getValue());
stmt.setInt(2, groupId);
@ -134,7 +134,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
status = true;
} catch (SQLException e) {
String msg = "Error occurred while adding properties for group '" +
deviceGroup.getName() + "' values : " + deviceGroup.getGroupProperties();
deviceGroup.getName() + "' values : " + deviceGroup.getGroupProperties();
throw new GroupManagementDAOException(msg, e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, null);
@ -152,7 +152,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
String sql =
"UPDATE DM_GROUP SET DESCRIPTION = ?, GROUP_NAME = ?, OWNER = ? WHERE ID = ? AND TENANT_ID = ?";
if(deviceGroup.getStatus() != null && !deviceGroup.getStatus().isEmpty()){
if (deviceGroup.getStatus() != null && !deviceGroup.getStatus().isEmpty()) {
sql = "UPDATE DM_GROUP SET DESCRIPTION = ?, GROUP_NAME = ?, OWNER = ?, STATUS = ? WHERE ID = ? AND TENANT_ID = ?";
hasStatus = true;
}
@ -161,7 +161,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
stmt.setString(paramIndex++, deviceGroup.getDescription());
stmt.setString(paramIndex++, deviceGroup.getName());
stmt.setString(paramIndex++, deviceGroup.getOwner());
if(hasStatus) {
if (hasStatus) {
stmt.setString(paramIndex++, deviceGroup.getStatus());
}
stmt.setInt(paramIndex++, groupId);
@ -234,11 +234,11 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
}
}
public Map<String,String> getAllGroupProperties(int groupId, int tenantId)
public Map<String, String> getAllGroupProperties(int groupId, int tenantId)
throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
Map<String,String> properties = new HashMap<String, String>();
Map<String, String> properties = new HashMap<String, String>();
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT PROPERTY_NAME, PROPERTY_VALUE FROM GROUP_PROPERTIES WHERE GROUP_ID = ? AND TENANT_ID = ?";
@ -248,7 +248,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
resultSet = stmt.executeQuery();
while (resultSet.next()) {
properties.put(resultSet.getString("PROPERTY_NAME"),
resultSet.getString("PROPERTY_VALUE"));
resultSet.getString("PROPERTY_VALUE"));
}
} catch (SQLException e) {
String msg = "Error occurred while deleting group ID : " + groupId;
@ -339,13 +339,13 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT COUNT(ID) AS GROUP_COUNT FROM DM_GROUP WHERE TENANT_ID = ?";
if(!StringUtils.isEmpty(status)){
if (!StringUtils.isEmpty(status)) {
sql += " AND STATUS = ?";
statusAvailable = true;
}
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
if(statusAvailable){
if (statusAvailable) {
stmt.setString(2, status);
}
resultSet = stmt.executeQuery();
@ -384,7 +384,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
sql += " AND OWNER LIKE ?";
hasOwner = true;
}
if(!StringUtils.isEmpty(request.getStatus())){
if (!StringUtils.isEmpty(request.getStatus())) {
sql += " AND STATUS = ?";
hasStatus = true;
}
@ -781,6 +781,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
+ "e.OWNER, "
+ "e.OWNERSHIP, "
+ "e.STATUS, "
+ "e.IS_TRANSFERRED, "
+ "e.DATE_OF_LAST_UPDATE, "
+ "e.DATE_OF_ENROLMENT, "
+ "e.ID AS ENROLMENT_ID "
@ -797,11 +798,11 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
+ "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 "
+ "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)){
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, groupName);
stmt.setInt(2, tenantId);
stmt.setInt(3, tenantId);
try (ResultSet rs = stmt.executeQuery() ){
try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>();
while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs);
@ -824,26 +825,26 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
try {
Connection connection = GroupManagementDAOFactory.getConnection();
StringJoiner sql = new StringJoiner(",",
"SELECT DEVICE.ID AS DEVICE_ID, " +
"DEVICE.NAME AS DEVICE_NAME, " +
"DEVICE_TYPE.NAME AS DEVICE_TYPE, " +
"DEVICE.DESCRIPTION, " +
"DEVICE.DEVICE_IDENTIFICATION, " +
"ENROLMENT.ID AS ENROLMENT_ID, " +
"ENROLMENT.OWNER, " +
"ENROLMENT.OWNERSHIP, " +
"ENROLMENT.DATE_OF_ENROLMENT, " +
"ENROLMENT.DATE_OF_LAST_UPDATE, " +
"ENROLMENT.STATUS " +
"FROM DM_DEVICE AS DEVICE, DM_DEVICE_TYPE AS DEVICE_TYPE, DM_ENROLMENT " +
"AS ENROLMENT " +
"WHERE DEVICE_TYPE.NAME = ? AND DEVICE" +
".ID " +
"NOT IN " +
"(SELECT DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP " +
"WHERE GROUP_ID IN (SELECT ID FROM DM_GROUP WHERE GROUP_NAME NOT IN (",
")) GROUP BY DEVICE_ID)");
"SELECT DEVICE.ID AS DEVICE_ID, " +
"DEVICE.NAME AS DEVICE_NAME, " +
"DEVICE_TYPE.NAME AS DEVICE_TYPE, " +
"DEVICE.DESCRIPTION, " +
"DEVICE.DEVICE_IDENTIFICATION, " +
"ENROLMENT.ID AS ENROLMENT_ID, " +
"ENROLMENT.OWNER, " +
"ENROLMENT.OWNERSHIP, " +
"ENROLMENT.DATE_OF_ENROLMENT, " +
"ENROLMENT.DATE_OF_LAST_UPDATE, " +
"ENROLMENT.STATUS, " +
"ENROLMENT.IS_TRANSFERRED " +
"FROM DM_DEVICE AS DEVICE, DM_DEVICE_TYPE AS DEVICE_TYPE, DM_ENROLMENT " +
"AS ENROLMENT " +
"WHERE DEVICE_TYPE.NAME = ? AND DEVICE.ID " +
"NOT IN " +
"(SELECT DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP " +
"WHERE GROUP_ID IN (SELECT ID FROM DM_GROUP WHERE GROUP_NAME NOT IN (",
")) GROUP BY DEVICE_ID)");
groupNames.stream().map(e -> "?").forEach(sql::add);
try (PreparedStatement stmt = connection.prepareStatement(String.valueOf(sql))) {
@ -862,7 +863,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of group unassigned devices";
log.error(msg, e);
throw new GroupManagementDAOException(msg,e);
throw new GroupManagementDAOException(msg, e);
}
return groupUnassignedDeviceList;
}

@ -75,47 +75,21 @@ public class EnrollmentDAOImpl implements EnrollmentDAO {
}
@Override
public int updateEnrollment(int deviceId, EnrolmentInfo enrolmentInfo,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, DATE_OF_LAST_UPDATE = ? WHERE DEVICE_ID = ?" +
" AND OWNER = ? AND TENANT_ID = ? AND ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, enrolmentInfo.getOwnership().toString());
stmt.setString(2, enrolmentInfo.getStatus().toString());
stmt.setTimestamp(3, new Timestamp(new Date().getTime()));
stmt.setInt(4, deviceId);
stmt.setString(5, enrolmentInfo.getOwner());
stmt.setInt(6, tenantId);
stmt.setInt(7, enrolmentInfo.getId());
int status = stmt.executeUpdate();
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 {
public int updateEnrollment(EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, DATE_OF_LAST_UPDATE = ? WHERE ID = ?";
String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, DATE_OF_LAST_UPDATE = ? " +
"WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, enrolmentInfo.getOwnership().toString());
stmt.setString(2, enrolmentInfo.getStatus().toString());
stmt.setTimestamp(3, new Timestamp(new Date().getTime()));
stmt.setInt(4, enrolmentInfo.getId());
int status = stmt.executeUpdate();
return status;
stmt.setInt(5, tenantId);
return stmt.executeUpdate();
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e);
} finally {
@ -188,28 +162,6 @@ public class EnrollmentDAOImpl implements EnrollmentDAO {
}
}
@Override
public boolean setStatus(int enrolmentID, String currentOwner, EnrolmentInfo.Status status,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE ID = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, status.toString());
stmt.setInt(2, enrolmentID);
stmt.setString(3, currentOwner);
stmt.setInt(4, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return true;
}
private int getCountOfDevicesOfOwner(String owner, int tenantID) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
@ -314,7 +266,7 @@ public class EnrollmentDAOImpl implements EnrollmentDAO {
EnrolmentInfo enrolmentInfo = null;
try {
conn = this.getConnection();
String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " +
String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, IS_TRANSFERRED, 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);
@ -333,6 +285,33 @@ public class EnrollmentDAOImpl implements EnrollmentDAO {
}
}
@Override
public EnrolmentInfo getEnrollment(int deviceId, int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
EnrolmentInfo enrolmentInfo = null;
try {
conn = this.getConnection();
String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, IS_TRANSFERRED, DATE_OF_ENROLMENT, " +
"DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND TENANT_ID = ? " +
"ORDER BY DATE_OF_LAST_UPDATE DESC";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
enrolmentInfo = this.loadEnrolment(rs);
}
return enrolmentInfo;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " +
"information of device '" + deviceId + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public List<EnrolmentInfo> getEnrollmentsOfUser(int deviceId, String user, int tenantId)
throws DeviceManagementDAOException {
@ -343,7 +322,7 @@ public class EnrollmentDAOImpl implements EnrollmentDAO {
EnrolmentInfo enrolmentInfo = null;
try {
conn = this.getConnection();
String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " +
String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, IS_TRANSFERRED, 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);
@ -369,20 +348,21 @@ public class EnrollmentDAOImpl implements EnrollmentDAO {
try {
Connection conn = this.getConnection();
boolean updateStatus = true;
String sql = "UPDATE "
+ "DM_ENROLMENT "
+ "SET OWNER = ? "
+ "WHERE ID = ? AND "
+ "TENANT_ID = ?";
String sql = "UPDATE DM_ENROLMENT "
+ "SET OWNER = ?, IS_TRANSFERRED = ?, DATE_OF_LAST_UPDATE = ? "
+ "WHERE ID = ? AND TENANT_ID = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
if (conn.getMetaData().supportsBatchUpdates()) {
for (Device device : devices) {
ps.setString(1, owner);
ps.setInt(2, device.getId());
ps.setInt(3, tenantId);
ps.setBoolean(2, device.getEnrolmentInfo().isTransferred());
ps.setTimestamp(3, new Timestamp(new Date().getTime()));
ps.setInt(4, device.getEnrolmentInfo().getId());
ps.setInt(5, tenantId);
ps.addBatch();
}
for (int i : ps.executeBatch()) {
int[] batchResult = ps.executeBatch();
for (int i : batchResult) {
if (i == 0 || i == Statement.SUCCESS_NO_INFO || i == Statement.EXECUTE_FAILED) {
updateStatus = false;
break;
@ -391,8 +371,9 @@ public class EnrollmentDAOImpl implements EnrollmentDAO {
} else {
for (Device device : devices) {
ps.setString(1, owner);
ps.setInt(2, device.getId());
ps.setInt(3, tenantId);
ps.setBoolean(2, device.getEnrolmentInfo().isTransferred());
ps.setInt(3, device.getId());
ps.setInt(4, tenantId);
if (ps.executeUpdate() == 0) {
updateStatus = false;
break;
@ -415,6 +396,7 @@ public class EnrollmentDAOImpl implements EnrollmentDAO {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setOwner(rs.getString("OWNER"));
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP")));
enrolmentInfo.setTransferred(rs.getBoolean("IS_TRANSFERRED"));
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")));

@ -70,24 +70,24 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
Connection conn = 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, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t ";
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"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, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, DM_DEVICE_TYPE t ";
//Add the query to filter active devices on timestamp
if (since != null) {
sql = sql + ", DM_DEVICE_DETAIL dt";
@ -168,7 +168,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices";
"registered devices";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -197,34 +197,35 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
Connection conn = getConnection();
String sql = "SELECT d1.DEVICE_ID, " +
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, " +
"gd.DESCRIPTION, " +
"gd.NAME, " +
"gd.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"d.DEVICE_TYPE_ID " +
"FROM DM_DEVICE d, " +
"(SELECT dgm.DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP dgm " +
"WHERE dgm.GROUP_ID = ?) dgm1 " +
"WHERE d.ID = dgm1.DEVICE_ID " +
"AND d.TENANT_ID = ?";
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, " +
"gd.DESCRIPTION, " +
"gd.NAME, " +
"gd.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"d.DEVICE_TYPE_ID " +
"FROM DM_DEVICE d, " +
"(SELECT dgm.DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP dgm " +
"WHERE dgm.GROUP_ID = ?) dgm1 " +
"WHERE d.ID = dgm1.DEVICE_ID " +
"AND d.TENANT_ID = ?";
//Add the query for device-name
if (deviceName != null && !deviceName.isEmpty()) {
sql = sql + " AND d.NAME LIKE ?";
@ -306,7 +307,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of" +
" devices belonging to group : " + groupId;
" devices belonging to group : " + groupId;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -320,12 +321,12 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
List<Device> devices = new ArrayList<>();
try {
conn = this.getConnection();
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," +
" e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " +
"AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " +
"e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " +
"e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " +
"AND t.ID = d.DEVICE_TYPE_ID LIMIT ?,?";
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.IS_TRANSFERRED, e1.DATE_OF_LAST_UPDATE," +
" e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " +
"AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " +
"e.DEVICE_ID, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " +
"e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " +
"AND t.ID = d.DEVICE_TYPE_ID LIMIT ?,?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, request.getOwner());
@ -339,7 +340,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" +
request.getOwner() + "'", e);
request.getOwner() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
@ -355,11 +356,11 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
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.NAME, " +
"d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " +
"WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?,?";
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " +
"d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " +
"WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?,?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, request.getDeviceName() + "%");
stmt.setInt(2, tenantId);
@ -374,7 +375,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " +
"'" + request.getDeviceName() + "'", e);
"'" + request.getDeviceName() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
@ -390,11 +391,11 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = this.getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " +
"e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ?,?";
"d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, " +
"e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ?,?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, request.getOwnership());
@ -409,7 +410,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " +
"'" + request.getOwnership() + "'", e);
"'" + request.getOwnership() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
@ -425,41 +426,43 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
Connection conn = getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM " +
"(SELECT e.ID, " +
"e.DEVICE_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ?";
"d.DESCRIPTION, " +
"d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM " +
"(SELECT e.ID, " +
"e.DEVICE_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ?";
if (statusList == null || statusList.isEmpty()) {
String msg = "Error occurred while fetching the list of devices. Status List can't " +
"be null or empty";
"be null or empty";
log.error(msg);
throw new DeviceManagementDAOException(msg);
}
sql += buildStatusQuery(statusList);
sql += ") e, " +
"DM_DEVICE d, " +
"DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID " +
"AND d.DEVICE_TYPE_ID = t.ID " +
"AND d.TENANT_ID = ? " +
"LIMIT ?,?";
"DM_DEVICE d, " +
"DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID " +
"AND d.DEVICE_TYPE_ID = t.ID " +
"AND d.TENANT_ID = ? " +
"LIMIT ?,?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
@ -481,7 +484,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while fetching the list of devices that matches to status " +
request.getStatusList().toString();
request.getStatusList().toString();
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -497,21 +500,22 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isStatusProvided = false;
String sql = "SELECT " +
"d.ID AS DEVICE_ID, " +
"d.DESCRIPTION,d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE," +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " +
"WHERE d.ID = e.DEVICE_ID AND " +
"d.DEVICE_TYPE_ID = t.ID AND " +
"e.TENANT_ID = ? AND " +
"e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
"d.ID AS DEVICE_ID, " +
"d.DESCRIPTION,d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE," +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " +
"WHERE d.ID = e.DEVICE_ID AND " +
"d.DEVICE_TYPE_ID = t.ID AND " +
"e.TENANT_ID = ? AND " +
"e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
if (statusList != null && !statusList.isEmpty()) {
sql += buildStatusQuery(statusList);
isStatusProvided = true;
@ -548,7 +552,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices under tenant id " + tenantId;
"registered devices under tenant id " + tenantId;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -562,14 +566,14 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isStatusProvided = false;
String sql = "SELECT " +
"COUNT(d.ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE AS d , " +
"DM_ENROLMENT AS e , " +
"DM_DEVICE_TYPE AS t " +
"WHERE d.ID = e.DEVICE_ID " +
"AND d.DEVICE_TYPE_ID = t.ID " +
"AND e.TENANT_ID = ? " +
"AND e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
"COUNT(d.ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE AS d , " +
"DM_ENROLMENT AS e , " +
"DM_DEVICE_TYPE AS t " +
"WHERE d.ID = e.DEVICE_ID " +
"AND d.DEVICE_TYPE_ID = t.ID " +
"AND e.TENANT_ID = ? " +
"AND e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
if (statusList != null && !statusList.isEmpty()) {
sql += buildStatusQuery(statusList);
isStatusProvided = true;
@ -601,7 +605,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices under tenant id " + tenantId;
"registered devices under tenant id " + tenantId;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -609,7 +613,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
@Override
public List<Count> getCountOfDevicesByDuration(PaginationRequest request, List<String> statusList, int tenantId,
String fromDate, String toDate)
String fromDate, String toDate)
throws DeviceManagementDAOException {
List<Count> countList = new ArrayList<>();
String ownership = request.getOwnership();
@ -617,14 +621,14 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
String sql =
"SELECT " +
"SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10) AS ENROLMENT_DATE, " +
"COUNT(SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10)) AS ENROLMENT_COUNT " +
"FROM DM_DEVICE AS d " +
"INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " +
"INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " +
"AND e.TENANT_ID = ? " +
"AND e.DATE_OF_ENROLMENT " +
"BETWEEN ? AND ? ";
"SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10) AS ENROLMENT_DATE, " +
"COUNT(SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10)) AS ENROLMENT_COUNT " +
"FROM DM_DEVICE AS d " +
"INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " +
"INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " +
"AND e.TENANT_ID = ? " +
"AND e.DATE_OF_ENROLMENT " +
"BETWEEN ? AND ? ";
//Add the query for status
if (statusList != null && !statusList.isEmpty()) {
@ -703,7 +707,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
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, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " +
"d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString +
@ -733,7 +737,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while fetching the list of devices corresponding" +
"to the mentioned filtering criteria";
"to the mentioned filtering criteria";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
} finally {
@ -766,6 +770,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
+ "DM_ENROLMENT.DATE_OF_ENROLMENT, "
+ "DM_ENROLMENT.DATE_OF_LAST_UPDATE, "
+ "DM_ENROLMENT.STATUS, "
+ "DM_ENROLMENT.IS_TRANSFERRED, "
+ "device_types.NAME AS DEVICE_TYPE "
+ "FROM DM_DEVICE "
+ "INNER JOIN DM_ENROLMENT ON "
@ -809,7 +814,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all registered devices " +
"according to device ids and the limit area.";
"according to device ids and the limit area.";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -823,8 +828,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
int index = 1;
StringJoiner joiner = new StringJoiner(",",
"SELECT " +
"COUNT(e.DEVICE_ID) AS DEVICE_ID "+
"FROM DM_ENROLMENT AS e, DM_DEVICE AS f "+
"COUNT(e.DEVICE_ID) AS DEVICE_ID " +
"FROM DM_ENROLMENT AS e, DM_DEVICE AS f " +
"WHERE " +
"e.DEVICE_ID=f.ID AND " +
"e.DEVICE_ID IN (", ") AND e.TENANT_ID = ?");
@ -870,37 +875,38 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
/* following variable is used to identify the datasource type.This is due to a
convert function performed in the query which will depend on the datasource */
String dataSourceType = conn.getMetaData().getDatabaseProductName();
String sql="SELECT " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_ID, " +
"d1.DEVICE_NAME, " +
"d1.DESCRIPTION, " +
"d1.DEVICE_IDENTIFICATION, " +
"ddd.OS_VERSION, " +
"e.ID AS ENROLMENT_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT " +
"FROM DM_DEVICE_INFO ddi," +
"DM_DEVICE_DETAIL ddd, " +
"DM_ENROLMENT e, " +
"(SELECT dt.NAME AS DEVICE_TYPE, " +
"d.ID AS DEVICE_ID, " +
"d.NAME AS DEVICE_NAME, " +
"DESCRIPTION, " +
"DEVICE_IDENTIFICATION " +
"FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID " +
"AND d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND d1.DEVICE_ID = ddd.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? ";
String sql = "SELECT " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_ID, " +
"d1.DEVICE_NAME, " +
"d1.DESCRIPTION, " +
"d1.DEVICE_IDENTIFICATION, " +
"ddd.OS_VERSION, " +
"e.ID AS ENROLMENT_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT " +
"FROM DM_DEVICE_INFO ddi," +
"DM_DEVICE_DETAIL ddd, " +
"DM_ENROLMENT e, " +
"(SELECT dt.NAME AS DEVICE_TYPE, " +
"d.ID AS DEVICE_ID, " +
"d.NAME AS DEVICE_NAME, " +
"DESCRIPTION, " +
"DEVICE_IDENTIFICATION " +
"FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID " +
"AND d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND d1.DEVICE_ID = ddd.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? ";
if (dataSourceType.contains(DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2)) {
sql += "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? ";
} else if (dataSourceType.contains(DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL)) {
@ -930,7 +936,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while building or executing queries to retrieve information " +
"of devices with an older OS build date";
"of devices with an older OS build date";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -945,17 +951,17 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
convert function performed in the query which will depend on the datasource */
String dataSourceType = conn.getMetaData().getDatabaseProductName();
String sql = "SELECT " +
"COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE_INFO ddi, " +
"(SELECT d.ID AS DEVICE_ID " +
"FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? ";
"COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE_INFO ddi, " +
"(SELECT d.ID AS DEVICE_ID " +
"FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? ";
if (dataSourceType.contains(DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2)) {
sql += "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? ";
} else if (dataSourceType.contains(DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL)) {
@ -977,7 +983,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while building or executing queries to retrieve the count " +
"of devices with an older OS build date";
"of devices with an older OS build date";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}

@ -71,24 +71,25 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = 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, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t ";
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"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, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t ";
//Add the query to filter active devices on timestamp
if (since != null) {
sql = sql + ", DM_DEVICE_DETAIL dt";
@ -169,7 +170,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices";
"registered devices";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -199,35 +200,36 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = getConnection();
String sql = "SELECT d1.DEVICE_ID, " +
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, " +
"gd.DESCRIPTION, " +
"gd.NAME, " +
"gd.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"d.DEVICE_TYPE_ID " +
"FROM DM_DEVICE d, " +
"(SELECT dgm.DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP dgm " +
"WHERE dgm.GROUP_ID = ?) dgm1 " +
"WHERE " +
"d.ID = dgm1.DEVICE_ID " +
"AND d.TENANT_ID = ?";
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, " +
"gd.DESCRIPTION, " +
"gd.NAME, " +
"gd.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"d.DEVICE_TYPE_ID " +
"FROM DM_DEVICE d, " +
"(SELECT dgm.DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP dgm " +
"WHERE dgm.GROUP_ID = ?) dgm1 " +
"WHERE " +
"d.ID = dgm1.DEVICE_ID " +
"AND d.TENANT_ID = ?";
//Add the query for device-name
if (deviceName != null && !deviceName.isEmpty()) {
sql = sql + " AND d.NAME LIKE ?";
@ -309,7 +311,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of" +
" devices belonging to group : " + groupId;
" devices belonging to group : " + groupId;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -323,12 +325,12 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
List<Device> devices = new ArrayList<>();
try {
conn = this.getConnection();
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE,"
+ " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME "
+ "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, "
+ "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE "
+ "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID "
+ "AND t.ID = d.DEVICE_TYPE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.IS_TRANSFERRED, e1.DATE_OF_LAST_UPDATE,"
+ " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME "
+ "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, "
+ "e.DEVICE_ID, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE "
+ "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID "
+ "AND t.ID = d.DEVICE_TYPE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, request.getOwner());
@ -342,7 +344,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" +
request.getOwner() + "'", e);
request.getOwner() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
@ -358,7 +360,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
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, "
+ "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, "
+ "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, "
+ "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, "
+ "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 "
@ -378,7 +380,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " +
"'" + request.getDeviceName() + "'", e);
"'" + request.getDeviceName() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
@ -394,8 +396,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = this.getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, "
+ "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, "
+ "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, "
+ "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, "
+ "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, "
+ "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e "
+ "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t "
+ "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID "
@ -414,7 +416,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " +
"'" + request.getOwnership() + "'", e);
"'" + request.getOwnership() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
@ -431,41 +433,43 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM (SELECT e.ID, " +
"e.DEVICE_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ?";
"d.DESCRIPTION, " +
"d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM (SELECT e.ID, " +
"e.DEVICE_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ?";
if (statusList == null || statusList.isEmpty()) {
String msg = "Error occurred while fetching the list of devices. Status List can't " +
"be null or empty";
"be null or empty";
log.error(msg);
throw new DeviceManagementDAOException(msg);
}
sql += buildStatusQuery(statusList);
sql += ") e," +
"DM_DEVICE d," +
"DM_DEVICE_TYPE t" +
"WHERE DEVICE_ID = e.DEVICE_ID" +
"AND d.DEVICE_TYPE_ID = t.ID" +
"AND d.TENANT_ID = ?" +
"LIMIT ?,?";
"DM_DEVICE d," +
"DM_DEVICE_TYPE t" +
"WHERE DEVICE_ID = e.DEVICE_ID" +
"AND d.DEVICE_TYPE_ID = t.ID" +
"AND d.TENANT_ID = ?" +
"LIMIT ?,?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
@ -486,7 +490,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while fetching the list of devices that matches to status " +
request.getStatusList().toString();
request.getStatusList().toString();
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -502,21 +506,22 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
String ownership = request.getOwnership();
String sql = "SELECT " +
"d.ID AS DEVICE_ID, " +
"d.DESCRIPTION,d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE," +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " +
"WHERE d.ID = e.DEVICE_ID AND " +
"d.DEVICE_TYPE_ID = t.ID AND " +
"e.TENANT_ID = ? AND " +
"e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
"d.ID AS DEVICE_ID, " +
"d.DESCRIPTION,d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE," +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " +
"WHERE d.ID = e.DEVICE_ID AND " +
"d.DEVICE_TYPE_ID = t.ID AND " +
"e.TENANT_ID = ? AND " +
"e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
if (statusList != null && !statusList.isEmpty()) {
sql += buildStatusQuery(statusList);
isStatusProvided = true;
@ -553,7 +558,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices under tenant id " + tenantId;
"registered devices under tenant id " + tenantId;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -566,7 +571,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
@Override
public List<Count> getCountOfDevicesByDuration(PaginationRequest request, List<String> statusList, int tenantId,
String fromDate, String toDate)
String fromDate, String toDate)
throws DeviceManagementDAOException {
List<Count> countList = new ArrayList<>();
String ownership = request.getOwnership();
@ -576,7 +581,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
"SELECT " +
"SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10) AS ENROLMENT_DATE, " +
"COUNT(SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10)) AS ENROLMENT_COUNT " +
"FROM DM_DEVICE AS d " +
"FROM DM_DEVICE AS d " +
"INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " +
"INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " +
"AND e.TENANT_ID = ? " +
@ -640,7 +645,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
sqlBuilder.append(")");
return true;
}else {
} else {
return false;
}
}
@ -673,7 +678,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
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, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " +
"d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString +
@ -702,7 +707,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while fetching the list of devices corresponding" +
"to the mentioned filtering criteria";
"to the mentioned filtering criteria";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
} finally {
@ -735,6 +740,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
+ "DM_ENROLMENT.DATE_OF_ENROLMENT, "
+ "DM_ENROLMENT.DATE_OF_LAST_UPDATE, "
+ "DM_ENROLMENT.STATUS, "
+ "DM_ENROLMENT.IS_TRANSFERRED, "
+ "device_types.NAME AS DEVICE_TYPE "
+ "FROM DM_DEVICE "
+ "INNER JOIN DM_ENROLMENT ON "
@ -778,7 +784,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all registered devices " +
"according to device ids and the limit area.";
"according to device ids and the limit area.";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -792,8 +798,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
int index = 1;
StringJoiner joiner = new StringJoiner(",",
"SELECT " +
"COUNT(e.DEVICE_ID) AS DEVICE_ID "+
"FROM DM_ENROLMENT AS e, DM_DEVICE AS f "+
"COUNT(e.DEVICE_ID) AS DEVICE_ID " +
"FROM DM_ENROLMENT AS e, DM_DEVICE AS f " +
"WHERE " +
"e.DEVICE_ID=f.ID AND " +
"e.DEVICE_ID IN (", ") AND e.TENANT_ID = ?");
@ -836,41 +842,42 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
Long osValue = (Long) request.getProperty(Constants.OS_VALUE);
Connection conn = getConnection();
String sql="SELECT " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_ID, " +
"d1.DEVICE_NAME, " +
"d1.DESCRIPTION, " +
"d1.DEVICE_IDENTIFICATION, " +
"ddd.OS_VERSION, " +
"e.ID AS ENROLMENT_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT " +
"FROM DM_DEVICE_INFO ddi, " +
"DM_DEVICE_DETAIL ddd, " +
"DM_ENROLMENT e, " +
"(SELECT dt.NAME AS DEVICE_TYPE, " +
"d.ID AS DEVICE_ID, " +
"d.NAME AS DEVICE_NAME, " +
"DESCRIPTION, " +
"DEVICE_IDENTIFICATION " +
" FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID " +
"AND d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND d1.DEVICE_ID = ddd.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? " +
"AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? " +
"ORDER BY ENROLMENT_ID " +
"OFFSET ? ROWS " +
"FETCH NEXT ? ROWS ONLY";
String sql = "SELECT " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_ID, " +
"d1.DEVICE_NAME, " +
"d1.DESCRIPTION, " +
"d1.DEVICE_IDENTIFICATION, " +
"ddd.OS_VERSION, " +
"e.ID AS ENROLMENT_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT " +
"FROM DM_DEVICE_INFO ddi, " +
"DM_DEVICE_DETAIL ddd, " +
"DM_ENROLMENT e, " +
"(SELECT dt.NAME AS DEVICE_TYPE, " +
"d.ID AS DEVICE_ID, " +
"d.NAME AS DEVICE_NAME, " +
"DESCRIPTION, " +
"DEVICE_IDENTIFICATION " +
" FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID " +
"AND d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND d1.DEVICE_ID = ddd.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? " +
"AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? " +
"ORDER BY ENROLMENT_ID " +
"OFFSET ? ROWS " +
"FETCH NEXT ? ROWS ONLY";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, request.getDeviceType());
@ -894,7 +901,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while building or executing queries to retrieve information " +
"of devices with an older OS build date";
"of devices with an older OS build date";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -906,18 +913,18 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
Connection conn = getConnection();
String sql = "SELECT " +
"COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE_INFO ddi, " +
"(SELECT d.ID AS DEVICE_ID " +
"FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? " +
"AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ?";
"COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE_INFO ddi, " +
"(SELECT d.ID AS DEVICE_ID " +
"FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? " +
"AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, deviceType);
@ -934,7 +941,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while building or executing queries to retrieve the count " +
"of devices with an older OS build date";
"of devices with an older OS build date";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}

@ -70,26 +70,27 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = 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, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t " +
"WHERE DEVICE_TYPE_ID = t.ID " +
"AND d.TENANT_ID = ?";
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"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, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t " +
"WHERE DEVICE_TYPE_ID = t.ID " +
"AND d.TENANT_ID = ?";
//Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?";
@ -157,7 +158,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices";
"registered devices";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -187,34 +188,35 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = getConnection();
String sql = "SELECT d1.DEVICE_ID, " +
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, " +
"gd.DESCRIPTION, " +
"gd.NAME, " +
"gd.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"d.DEVICE_TYPE_ID " +
"FROM DM_DEVICE d, " +
"(SELECT dgm.DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP dgm " +
"WHERE dgm.GROUP_ID = ?) dgm1 " +
"WHERE d.ID = dgm1.DEVICE_ID " +
"AND d.TENANT_ID = ?";
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, " +
"gd.DESCRIPTION, " +
"gd.NAME, " +
"gd.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"d.DEVICE_TYPE_ID " +
"FROM DM_DEVICE d, " +
"(SELECT dgm.DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP dgm " +
"WHERE dgm.GROUP_ID = ?) dgm1 " +
"WHERE d.ID = dgm1.DEVICE_ID " +
"AND d.TENANT_ID = ?";
//Add the query for device-name
if (deviceName != null && !deviceName.isEmpty()) {
sql = sql + " AND d.NAME LIKE ?";
@ -296,7 +298,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of" +
" devices belonging to group : " + groupId;
" devices belonging to group : " + groupId;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -310,12 +312,12 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
List<Device> devices = new ArrayList<>();
try {
conn = this.getConnection();
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," +
" e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " +
"AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " +
"e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " +
"e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " +
"AND t.ID = d.DEVICE_TYPE_ID LIMIT ? OFFSET ?";
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.IS_TRANSFERRED, e1.DATE_OF_LAST_UPDATE," +
" e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " +
"AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " +
"e.DEVICE_ID, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " +
"e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " +
"AND t.ID = d.DEVICE_TYPE_ID LIMIT ? OFFSET ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, request.getOwner());
@ -329,7 +331,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" +
request.getOwner() + "'", e);
request.getOwner() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
@ -345,11 +347,11 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
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.NAME, " +
"d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " +
"WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?";
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " +
"d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " +
"WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, request.getDeviceName() + "%");
stmt.setInt(2, tenantId);
@ -364,7 +366,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " +
"'" + request.getDeviceName() + "'", e);
"'" + request.getDeviceName() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
@ -380,11 +382,11 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = this.getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " +
"e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ? OFFSET ?";
"d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, " +
"e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ? OFFSET ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, request.getOwnership());
@ -399,7 +401,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " +
"'" + request.getOwnership() + "'", e);
"'" + request.getOwnership() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
@ -416,39 +418,41 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM " +
"(SELECT e.ID, " +
"e.DEVICE_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ?";
"d.DESCRIPTION, " +
"d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM " +
"(SELECT e.ID, " +
"e.DEVICE_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ?";
if (statusList == null || statusList.isEmpty()) {
String msg = "Error occurred while fetching the list of devices. Status List can't " +
"be null or empty";
"be null or empty";
log.error(msg);
throw new DeviceManagementDAOException(msg);
}
sql += buildStatusQuery(statusList);
sql += ") e, " +
"DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID " +
"AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? " +
"LIMIT ? OFFSET ?";
"DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID " +
"AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? " +
"LIMIT ? OFFSET ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
@ -470,7 +474,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while fetching the list of devices that matches to status " +
request.getStatusList().toString();
request.getStatusList().toString();
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -486,21 +490,22 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
String ownership = request.getOwnership();
String sql = "SELECT " +
"d.ID AS DEVICE_ID, " +
"d.DESCRIPTION,d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE," +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " +
"WHERE d.ID = e.DEVICE_ID AND " +
"d.DEVICE_TYPE_ID = t.ID AND " +
"e.TENANT_ID = ? AND " +
"e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
"d.ID AS DEVICE_ID, " +
"d.DESCRIPTION,d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE," +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " +
"WHERE d.ID = e.DEVICE_ID AND " +
"d.DEVICE_TYPE_ID = t.ID AND " +
"e.TENANT_ID = ? AND " +
"e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
if (statusList != null && !statusList.isEmpty()) {
sql += buildStatusQuery(statusList);
isStatusProvided = true;
@ -537,7 +542,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices under tenant id " + tenantId;
"registered devices under tenant id " + tenantId;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -550,7 +555,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
@Override
public List<Count> getCountOfDevicesByDuration(PaginationRequest request, List<String> statusList, int tenantId,
String fromDate, String toDate)
String fromDate, String toDate)
throws DeviceManagementDAOException {
List<Count> countList = new ArrayList<>();
String ownership = request.getOwnership();
@ -560,7 +565,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
"SELECT " +
"SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10) AS ENROLMENT_DATE, " +
"COUNT(SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10)) AS ENROLMENT_COUNT " +
"FROM DM_DEVICE AS d " +
"FROM DM_DEVICE AS d " +
"INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " +
"INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " +
"AND e.TENANT_ID = ? " +
@ -624,7 +629,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
sqlBuilder.append(")");
return true;
}else {
} else {
return false;
}
}
@ -658,11 +663,11 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
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, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " +
"d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString +
") d1 WHERE d1.ID = e.DEVICE_ID OFFSET ? LIMIT ?";
"d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString +
") d1 WHERE d1.ID = e.DEVICE_ID OFFSET ? LIMIT ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
@ -688,7 +693,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while fetching the list of devices corresponding" +
"to the mentioned filtering criteria";
"to the mentioned filtering criteria";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
} finally {
@ -721,6 +726,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
+ "DM_ENROLMENT.DATE_OF_ENROLMENT, "
+ "DM_ENROLMENT.DATE_OF_LAST_UPDATE, "
+ "DM_ENROLMENT.STATUS, "
+ "DM_ENROLMENT.IS_TRANSFERRED, "
+ "device_types.NAME AS DEVICE_TYPE "
+ "FROM DM_DEVICE "
+ "INNER JOIN DM_ENROLMENT ON "
@ -764,7 +770,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all registered devices " +
"according to device ids and the limit area.";
"according to device ids and the limit area.";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -778,8 +784,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
int index = 1;
StringJoiner joiner = new StringJoiner(",",
"SELECT " +
"COUNT(e.DEVICE_ID) AS DEVICE_ID "+
"FROM DM_ENROLMENT AS e, DM_DEVICE AS f "+
"COUNT(e.DEVICE_ID) AS DEVICE_ID " +
"FROM DM_ENROLMENT AS e, DM_DEVICE AS f " +
"WHERE " +
"e.DEVICE_ID=f.ID AND " +
"e.DEVICE_ID IN (", ") AND e.TENANT_ID = ?");
@ -822,39 +828,40 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
Long osValue = (Long) request.getProperty(Constants.OS_VALUE);
Connection conn = getConnection();
String sql="SELECT " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_ID, " +
"d1.DEVICE_NAME, " +
"d1.DESCRIPTION, " +
"d1.DEVICE_IDENTIFICATION, " +
"ddd.OS_VERSION, " +
"e.ID AS ENROLMENT_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT " +
"FROM DM_DEVICE_INFO ddi, " +
"DM_DEVICE_DETAIL ddd, " +
"DM_ENROLMENT e, " +
"(SELECT dt.NAME AS DEVICE_TYPE, " +
"d.ID AS DEVICE_ID, " +
"d.NAME AS DEVICE_NAME, " +
"DESCRIPTION, " +
"DEVICE_IDENTIFICATION " +
" FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID " +
"AND d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND d1.DEVICE_ID = ddd.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? " +
"AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? " +
"LIMIT ? OFFSET ?";
String sql = "SELECT " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_ID, " +
"d1.DEVICE_NAME, " +
"d1.DESCRIPTION, " +
"d1.DEVICE_IDENTIFICATION, " +
"ddd.OS_VERSION, " +
"e.ID AS ENROLMENT_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT " +
"FROM DM_DEVICE_INFO ddi, " +
"DM_DEVICE_DETAIL ddd, " +
"DM_ENROLMENT e, " +
"(SELECT dt.NAME AS DEVICE_TYPE, " +
"d.ID AS DEVICE_ID, " +
"d.NAME AS DEVICE_NAME, " +
"DESCRIPTION, " +
"DEVICE_IDENTIFICATION " +
" FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID " +
"AND d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND d1.DEVICE_ID = ddd.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? " +
"AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? " +
"LIMIT ? OFFSET ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, request.getDeviceType());
@ -878,7 +885,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while building or executing queries to retrieve information " +
"of devices with an older OS build date";
"of devices with an older OS build date";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -890,18 +897,18 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
Connection conn = getConnection();
String sql = "SELECT " +
"COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE_INFO ddi, " +
"(SELECT d.ID AS DEVICE_ID " +
"FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? " +
"AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ?";
"COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE_INFO ddi, " +
"(SELECT d.ID AS DEVICE_ID " +
"FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? " +
"AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, deviceType);
@ -918,7 +925,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while building or executing queries to retrieve the count " +
"of devices with an older OS build date";
"of devices with an older OS build date";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}

@ -72,23 +72,24 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = 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, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, DM_DEVICE_TYPE t ";
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"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, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, DM_DEVICE_TYPE t ";
//Add the query to filter active devices on timestamp
if (since != null) {
sql = sql + ", DM_DEVICE_DETAIL dt";
@ -169,7 +170,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices";
"registered devices";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -199,34 +200,35 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = getConnection();
String sql = "SELECT d1.DEVICE_ID, " +
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, " +
"gd.DESCRIPTION, " +
"gd.NAME, " +
"gd.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"d.DEVICE_TYPE_ID " +
"FROM DM_DEVICE d, " +
"(SELECT dgm.DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP dgm " +
"WHERE dgm.GROUP_ID = ?) dgm1 " +
"WHERE d.ID = dgm1.DEVICE_ID " +
"AND d.TENANT_ID = ?";
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, " +
"gd.DESCRIPTION, " +
"gd.NAME, " +
"gd.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"d.DEVICE_TYPE_ID " +
"FROM DM_DEVICE d, " +
"(SELECT dgm.DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP dgm " +
"WHERE dgm.GROUP_ID = ?) dgm1 " +
"WHERE d.ID = dgm1.DEVICE_ID " +
"AND d.TENANT_ID = ?";
//Add the query for device-name
if (deviceName != null && !deviceName.isEmpty()) {
sql = sql + " AND d.NAME LIKE ?";
@ -308,7 +310,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of" +
" devices belonging to group : " + groupId;
" devices belonging to group : " + groupId;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -322,12 +324,12 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
List<Device> devices = new ArrayList<>();
try {
conn = this.getConnection();
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," +
" e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " +
"AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " +
"e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " +
"e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " +
"AND t.ID = d.DEVICE_TYPE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.IS_TRANSFERRED, e1.DATE_OF_LAST_UPDATE," +
" e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " +
"AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " +
"e.DEVICE_ID, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " +
"e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " +
"AND t.ID = d.DEVICE_TYPE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, request.getOwner());
@ -341,7 +343,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" +
request.getOwner() + "'", e);
request.getOwner() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
@ -357,12 +359,12 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
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.NAME, " +
"d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " +
"WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY ENROLMENT_ID " +
"OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " +
"d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " +
"WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY ENROLMENT_ID " +
"OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(sql);
stmt.setString(1, request.getDeviceName() + "%");
stmt.setInt(2, tenantId);
@ -377,7 +379,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " +
"'" + request.getDeviceName() + "'", e);
"'" + request.getDeviceName() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
@ -393,12 +395,12 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = this.getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " +
"e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " +
"OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
"d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, " +
"e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " +
"OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, request.getOwnership());
@ -413,7 +415,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " +
"'" + request.getOwnership() + "'", e);
"'" + request.getOwnership() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
@ -430,41 +432,43 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM " +
"(SELECT e.ID, " +
"e.DEVICE_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ?";
"d.DESCRIPTION, " +
"d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM " +
"(SELECT e.ID, " +
"e.DEVICE_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ?";
if (statusList == null || statusList.isEmpty()) {
String msg = "Error occurred while fetching the list of devices. Status List can't " +
"be null or empty";
"be null or empty";
log.error(msg);
throw new DeviceManagementDAOException(msg);
}
sql += buildStatusQuery(statusList);
sql += ") e, " +
"DM_DEVICE d, " +
"DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID " +
"AND d.DEVICE_TYPE_ID = t.ID " +
"AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " +
"OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
"DM_DEVICE d, " +
"DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID " +
"AND d.DEVICE_TYPE_ID = t.ID " +
"AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " +
"OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
@ -486,7 +490,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while fetching the list of devices that matches to status " +
request.getStatusList().toString();
request.getStatusList().toString();
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -520,11 +524,11 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
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, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " +
"d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString +
") d1 WHERE d1.ID = e.DEVICE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
"d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString +
") d1 WHERE d1.ID = e.DEVICE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
@ -550,7 +554,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while fetching the list of devices corresponding" +
"to the mentioned filtering criteria";
"to the mentioned filtering criteria";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
} finally {
@ -583,6 +587,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
+ "DM_ENROLMENT.DATE_OF_ENROLMENT, "
+ "DM_ENROLMENT.DATE_OF_LAST_UPDATE, "
+ "DM_ENROLMENT.STATUS, "
+ "DM_ENROLMENT.IS_TRANSFERRED, "
+ "device_types.NAME AS DEVICE_TYPE "
+ "FROM DM_DEVICE "
+ "INNER JOIN DM_ENROLMENT ON "
@ -626,7 +631,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all registered devices " +
"according to device ids and the limit area.";
"according to device ids and the limit area.";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -638,39 +643,40 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
Long osValue = (Long) request.getProperty(Constants.OS_VALUE);
Connection conn = getConnection();
String sql="SELECT " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_ID, " +
"d1.DEVICE_NAME, " +
"d1.DESCRIPTION, " +
"d1.DEVICE_IDENTIFICATION, " +
"ddd.OS_VERSION, " +
"e.ID AS ENROLMENT_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT " +
"FROM DM_DEVICE_INFO ddi, " +
"DM_DEVICE_DETAIL ddd, " +
"DM_ENROLMENT e, " +
"(SELECT dt.NAME AS DEVICE_TYPE, " +
"d.ID AS DEVICE_ID, " +
"d.NAME AS DEVICE_NAME, " +
"DESCRIPTION, " +
"DEVICE_IDENTIFICATION " +
" FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID " +
"AND d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND d1.DEVICE_ID = ddd.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? " +
"AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? " +
"LIMIT ? OFFSET ?";
String sql = "SELECT " +
"d1.DEVICE_TYPE, " +
"d1.DEVICE_ID, " +
"d1.DEVICE_NAME, " +
"d1.DESCRIPTION, " +
"d1.DEVICE_IDENTIFICATION, " +
"ddd.OS_VERSION, " +
"e.ID AS ENROLMENT_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT " +
"FROM DM_DEVICE_INFO ddi, " +
"DM_DEVICE_DETAIL ddd, " +
"DM_ENROLMENT e, " +
"(SELECT dt.NAME AS DEVICE_TYPE, " +
"d.ID AS DEVICE_ID, " +
"d.NAME AS DEVICE_NAME, " +
"DESCRIPTION, " +
"DEVICE_IDENTIFICATION " +
" FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID " +
"AND d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND d1.DEVICE_ID = ddd.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? " +
"AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? " +
"LIMIT ? OFFSET ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, request.getDeviceType());
@ -694,7 +700,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while building or executing queries to retrieve information " +
"of devices with an older OS build date";
"of devices with an older OS build date";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -706,18 +712,18 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
Connection conn = getConnection();
String sql = "SELECT " +
"COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE_INFO ddi, " +
"(SELECT d.ID AS DEVICE_ID " +
"FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? " +
"AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ?";
"COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE_INFO ddi, " +
"(SELECT d.ID AS DEVICE_ID " +
"FROM DM_DEVICE_TYPE dt, " +
"DM_DEVICE d " +
"WHERE dt.NAME = ? " +
"AND PROVIDER_TENANT_ID = ? " +
"AND dt.ID = d.DEVICE_TYPE_ID " +
") d1 " +
"WHERE d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? " +
"AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, deviceType);
@ -734,7 +740,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while building or executing queries to retrieve the count " +
"of devices with an older OS build date";
"of devices with an older OS build date";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -754,21 +760,22 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
String ownership = request.getOwnership();
String sql = "SELECT " +
"d.ID AS DEVICE_ID, " +
"d.DESCRIPTION,d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE," +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " +
"WHERE d.ID = e.DEVICE_ID AND " +
"d.DEVICE_TYPE_ID = t.ID AND " +
"e.TENANT_ID = ? AND " +
"e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
"d.ID AS DEVICE_ID, " +
"d.DESCRIPTION,d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE," +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " +
"WHERE d.ID = e.DEVICE_ID AND " +
"d.DEVICE_TYPE_ID = t.ID AND " +
"e.TENANT_ID = ? AND " +
"e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
if (statusList != null && !statusList.isEmpty()) {
sql += buildStatusQuery(statusList);
isStatusProvided = true;
@ -805,7 +812,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices under tenant id " + tenantId;
"registered devices under tenant id " + tenantId;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
@ -818,7 +825,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
@Override
public List<Count> getCountOfDevicesByDuration(PaginationRequest request, List<String> statusList, int tenantId,
String fromDate, String toDate)
String fromDate, String toDate)
throws DeviceManagementDAOException {
List<Count> countList = new ArrayList<>();
String ownership = request.getOwnership();
@ -828,7 +835,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
"SELECT " +
"SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10) AS ENROLMENT_DATE, " +
"COUNT(SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10)) AS ENROLMENT_COUNT " +
"FROM DM_DEVICE AS d " +
"FROM DM_DEVICE AS d " +
"INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " +
"INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " +
"AND e.TENANT_ID = ? " +
@ -892,7 +899,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
sqlBuilder.append(")");
return true;
}else {
} else {
return false;
}
}
@ -905,8 +912,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
int index = 1;
StringJoiner joiner = new StringJoiner(",",
"SELECT " +
"COUNT(e.DEVICE_ID) AS DEVICE_ID "+
"FROM DM_ENROLMENT AS e, DM_DEVICE AS f "+
"COUNT(e.DEVICE_ID) AS DEVICE_ID " +
"FROM DM_ENROLMENT AS e, DM_DEVICE AS f " +
"WHERE " +
"e.DEVICE_ID=f.ID AND " +
"e.DEVICE_ID IN (", ") AND e.TENANT_ID = ?");
@ -945,7 +952,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
@Override
public List<GeoCluster> findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast,
int geohashLength, int tenantId) throws DeviceManagementDAOException {
int geohashLength, int tenantId) throws DeviceManagementDAOException {
List<GeoCluster> geoClusters = new ArrayList<>();
try {
Connection conn = this.getConnection();
@ -978,14 +985,14 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
+ southWest.getLongitude()
+ " AND "
+ northEast.getLongitude()
+" AND "
+ "DEVICE.TENANT_ID = " + tenantId +" AND "
+ " AND "
+ "DEVICE.TENANT_ID = " + tenantId + " AND "
+ "DEVICE.ID = DEVICE_LOCATION.DEVICE_ID AND "
+ "DEVICE.DEVICE_TYPE_ID = DEVICE_TYPE.ID ";
if (deviceType != null && !deviceType.isEmpty()) {
sql += "AND DEVICE_TYPE.NAME = " + deviceType;
}
sql += "GROUP BY SUBSTRING(DEVICE_LOCATION.GEO_HASH,1,"+ geohashLength + ")";
sql += "GROUP BY SUBSTRING(DEVICE_LOCATION.GEO_HASH,1," + geohashLength + ")";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
try (ResultSet rs = stmt.executeQuery()) {

@ -177,7 +177,7 @@ public class GenericGroupDAOImpl extends AbstractGroupDAOImpl {
try {
conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " +
"FROM " +

@ -178,7 +178,7 @@ public class OracleGroupDAOImpl extends AbstractGroupDAOImpl {
try {
conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " +
"FROM " +

@ -218,7 +218,7 @@ public class PostgreSQLGroupDAOImpl extends AbstractGroupDAOImpl {
try {
conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " +
"FROM " +

@ -178,7 +178,7 @@ public class SQLServerGroupDAOImpl extends AbstractGroupDAOImpl {
try {
conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " +
"FROM " +

@ -144,6 +144,7 @@ public final class DeviceManagementDAOUtil {
enrolmentInfo.setId(rs.getInt("ENROLMENT_ID"));
enrolmentInfo.setOwner(rs.getString("OWNER"));
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP")));
enrolmentInfo.setTransferred(rs.getBoolean("IS_TRANSFERRED"));
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")));
@ -198,7 +199,6 @@ public final class DeviceManagementDAOUtil {
//This method will retrieve most appropriate device information when there are multiple device enrollments for
//a single device. Here we'll consider only active status.
public static Device loadActiveDevice(ResultSet rs, boolean deviceInfoIncluded) throws SQLException {
Map<EnrolmentInfo.Status, Device> deviceMap = new HashMap<>();
Device device = loadDevice(rs);
if (deviceInfoIncluded) {
device.setDeviceInfo(loadDeviceInfo(rs));
@ -209,7 +209,6 @@ public final class DeviceManagementDAOUtil {
//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, boolean deviceInfoIncluded) throws SQLException {
Map<EnrolmentInfo.Status, Device> deviceMap = new HashMap<>();
Device device = loadDevice(rs);
if (deviceInfoIncluded) {
device.setDeviceInfo(loadDeviceInfo(rs));

@ -60,6 +60,8 @@ public interface DeviceInformationManager {
*/
DeviceInfo getDeviceInfo(DeviceIdentifier deviceIdentifier) throws DeviceDetailsMgtException;
DeviceInfo getDeviceInfo(Device device) throws DeviceDetailsMgtException;
/**
* This method will return device information for the supplied devices list.
* @param deviceIdentifiers

@ -273,8 +273,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO {
conn = this.getConnection();
stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_LOCATION (DEVICE_ID, LATITUDE, LONGITUDE, STREET1, " +
"STREET2, CITY, ZIP, STATE, COUNTRY, GEO_HASH, UPDATE_TIMESTAMP, ENROLMENT_ID, ALTITUDE, SPEED, BEARING, " +
"DISTANCE) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
"DISTANCE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setInt(1, deviceLocation.getDeviceId());
stmt.setDouble(2, deviceLocation.getLatitude());
stmt.setDouble(3, deviceLocation.getLongitude());

@ -64,7 +64,7 @@ import java.util.Map;
public class DeviceInformationManagerImpl implements DeviceInformationManager {
private DeviceDetailsDAO deviceDetailsDAO;
private final DeviceDetailsDAO deviceDetailsDAO;
private DeviceDAO deviceDAO;
private static final Log log = LogFactory.getLog(DeviceInformationManagerImpl.class);
private static final String LOCATION_EVENT_STREAM_DEFINITION = "org.wso2.iot.LocationStream";
@ -117,7 +117,10 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
addOSVersionValue(device, newDeviceInfo);
for (String key : newDeviceInfo.getDeviceDetailsMap().keySet()) {
if (previousDeviceProperties.containsKey(key)) {
updatableProps.put(key, newDeviceInfo.getDeviceDetailsMap().get(key));
String val = previousDeviceProperties.get(key);
if (val != null &&!val.equals(newDeviceInfo.getDeviceDetailsMap().get(key))) {
updatableProps.put(key, newDeviceInfo.getDeviceDetailsMap().get(key));
}
} else {
injectableProps.put(key, newDeviceInfo.getDeviceDetailsMap().get(key));
}
@ -160,20 +163,17 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
);
}
} catch (TransactionManagementException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceDetailsMgtException("Transactional error occurred while adding the device information.", e);
} catch (DeviceDetailsMgtDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceDetailsMgtException("Error occurred while adding the device information.", e);
} catch (DeviceManagementException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceDetailsMgtException("Error occurred while retrieving the device information.", e);
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceDetailsMgtException("Error occurred while updating the last update timestamp of the " +
"device", e);
} catch (DataPublisherConfigurationException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
@ -226,17 +226,30 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
if (device == null) {
return null;
}
return getDeviceInfo(device);
}
@Override
public DeviceInfo getDeviceInfo(Device device) throws DeviceDetailsMgtException {
try {
DeviceManagementDAOFactory.openConnection();
DeviceInfo deviceInfo = deviceDetailsDAO.getDeviceInformation(device.getId(),
device.getEnrolmentInfo().getId());
if (deviceInfo == null) {
deviceInfo = new DeviceInfo();
}
deviceInfo.setDeviceDetailsMap(deviceDetailsDAO.getDeviceProperties(device.getId(),
device.getEnrolmentInfo().getId()));
DeviceLocation location = deviceDetailsDAO.getDeviceLocation(device.getId(),
device.getEnrolmentInfo().getId());
if (location != null) {
//There are some cases where the device-info is not updated properly. Hence returning a null value.
deviceInfo.setLocation(location);
}
return deviceInfo;
} catch (SQLException e) {
throw new DeviceDetailsMgtException("SQL error occurred while retrieving device " + deviceId.toString()
+ "'s info from database.", e);
throw new DeviceDetailsMgtException("SQL error occurred while retrieving device " +
device.getDeviceIdentifier() + "'s info from database.", e);
} catch (DeviceDetailsMgtDAOException e) {
throw new DeviceDetailsMgtException("Exception occurred while retrieving device details.", e);
} finally {
@ -263,11 +276,21 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
}
}
DeviceManagementDAOFactory.openConnection();
DeviceInfo deviceInfo;
for (Device device : deviceIds) {
DeviceInfo deviceInfo = deviceDetailsDAO.getDeviceInformation(device.getId(),
deviceInfo = deviceDetailsDAO.getDeviceInformation(device.getId(),
device.getEnrolmentInfo().getId());
if (deviceInfo == null) {
deviceInfo = new DeviceInfo();
}
deviceInfo.setDeviceDetailsMap(deviceDetailsDAO.getDeviceProperties(device.getId(),
device.getEnrolmentInfo().getId()));
DeviceLocation location = deviceDetailsDAO.getDeviceLocation(device.getId(),
device.getEnrolmentInfo().getId());
if (location != null) {
//There are some cases where the device-info is not updated properly. Hence returning a null value.
deviceInfo.setLocation(location);
}
deviceInfos.add(deviceInfo);
}
} catch (SQLException e) {
@ -367,7 +390,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
if (device == null) {
if (log.isDebugEnabled()) {
log.debug("No device is found upon the device identifier '" + deviceId.getId() +
"' and type '" + deviceId.getType() + "'. Therefore returning null");
"' and type '" + deviceId.getType() + "'. Therefore returning null");
}
return null;
}
@ -401,7 +424,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
throw new DeviceDetailsMgtException("SQL error occurred while retrieving device from database.", e);
} catch (DeviceDetailsMgtDAOException e) {
throw new DeviceDetailsMgtException("Exception occurred while retrieving device locations.", e);
} finally{
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}

@ -0,0 +1,69 @@
/*
* Copyright (c) 2020, 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.dto.operation.mgt;
import java.sql.Timestamp;
public class OperationResponseMeta {
private int id;
private int enrolmentId;
private int operationMappingId;
private boolean isLargeResponse;
private Timestamp receivedTimestamp;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getEnrolmentId() {
return enrolmentId;
}
public void setEnrolmentId(int enrolmentId) {
this.enrolmentId = enrolmentId;
}
public int getOperationMappingId() {
return operationMappingId;
}
public void setOperationMappingId(int operationMappingId) {
this.operationMappingId = operationMappingId;
}
public boolean isLargeResponse() {
return isLargeResponse;
}
public void setLargeResponse(boolean largeResponse) {
isLargeResponse = largeResponse;
}
public Timestamp getReceivedTimestamp() {
return receivedTimestamp;
}
public void setReceivedTimestamp(Timestamp receivedTimestamp) {
this.receivedTimestamp = receivedTimestamp;
}
}

@ -28,6 +28,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
@ -45,11 +46,13 @@ import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationExecu
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationProvider;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
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.dao.EnrollmentDAO;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.OperationResponseMeta;
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;
@ -66,12 +69,14 @@ import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* This class implements all the functionality exposed as part of the OperationManager. Any transaction initiated
@ -84,19 +89,21 @@ public class OperationManagerImpl implements OperationManager {
private static final int CACHE_VALIDITY_PERIOD = 5 * 60 * 1000;
private static final String NOTIFIER_TYPE_LOCAL = "LOCAL";
private static final String SYSTEM = "system";
private OperationDAO commandOperationDAO;
private OperationDAO configOperationDAO;
private OperationDAO profileOperationDAO;
private OperationDAO policyOperationDAO;
private OperationMappingDAO operationMappingDAO;
private OperationDAO operationDAO;
private DeviceDAO deviceDAO;
private EnrollmentDAO enrollmentDAO;
public static final int maxOperationCacheSize = 100;
private final OperationDAO commandOperationDAO;
private final OperationDAO configOperationDAO;
private final OperationDAO profileOperationDAO;
private final OperationDAO policyOperationDAO;
private final OperationMappingDAO operationMappingDAO;
private final OperationDAO operationDAO;
private final DeviceDAO deviceDAO;
private final EnrollmentDAO enrollmentDAO;
private String deviceType;
private DeviceManagementService deviceManagementService;
private Map<Integer, NotificationStrategy> notificationStrategies;
private Map<Integer, Long> lastUpdatedTimeStamps;
private final Map<Integer, NotificationStrategy> notificationStrategies;
private final Map<Integer, Long> lastUpdatedTimeStamps;
private final ConcurrentMap<Integer, String> operationsInitBy;
public OperationManagerImpl() {
commandOperationDAO = OperationManagementDAOFactory.getCommandOperationDAO();
@ -109,6 +116,7 @@ public class OperationManagerImpl implements OperationManager {
enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
notificationStrategies = new HashMap<>();
lastUpdatedTimeStamps = new HashMap<>();
operationsInitBy = new ConcurrentHashMap<>();
}
public OperationManagerImpl(String deviceType, DeviceManagementService deviceManagementService) {
@ -124,7 +132,7 @@ public class OperationManagerImpl implements OperationManager {
// type specific notification strategy.
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(false);
long lastUpdatedTimeStamp = 0;
if (lastUpdatedTimeStamps.containsKey(tenantId)){
if (lastUpdatedTimeStamps.containsKey(tenantId)) {
lastUpdatedTimeStamp = lastUpdatedTimeStamps.get(tenantId);
}
if (Calendar.getInstance().getTimeInMillis() - lastUpdatedTimeStamp > CACHE_VALIDITY_PERIOD) {
@ -134,11 +142,11 @@ public class OperationManagerImpl implements OperationManager {
.getPushNotificationProviderRepository().getProvider(pushNoteConfig.getType());
if (provider == null) {
log.error("No registered push notification provider found for the type '" +
pushNoteConfig.getType() + "' under tenant ID '" + tenantId + "'.");
pushNoteConfig.getType() + "' under tenant ID '" + tenantId + "'.");
return null;
}
notificationStrategies.put(tenantId, provider.getNotificationStrategy(pushNoteConfig));
} else if (notificationStrategies.containsKey(tenantId)){
} else if (notificationStrategies.containsKey(tenantId)) {
notificationStrategies.remove(tenantId);
}
lastUpdatedTimeStamps.put(tenantId, Calendar.getInstance().getTimeInMillis());
@ -159,140 +167,253 @@ public class OperationManagerImpl implements OperationManager {
try {
DeviceIDHolder deviceValidationResult = DeviceManagerUtil.validateDeviceIdentifiers(deviceIds);
List<DeviceIdentifier> validDeviceIds = deviceValidationResult.getValidDeviceIDList();
if (validDeviceIds.size() > 0) {
DeviceIDHolder deviceAuthorizationResult = this.authorizeDevices(operation, validDeviceIds);
List<DeviceIdentifier> authorizedDeviceIds = deviceAuthorizationResult.getValidDeviceIDList();
if (authorizedDeviceIds.size() <= 0) {
log.warn("User : " + getUser() + " is not authorized to perform operations on given device-list.");
Activity activity = new Activity();
//Send the operation statuses only for admin triggered operations
activity.setActivityStatus(this.getActivityStatus(deviceValidationResult,
deviceAuthorizationResult));
return activity;
}
if (validDeviceIds.isEmpty()) {
String msg = "Invalid device Identifiers found.";
log.error(msg);
throw new InvalidDeviceException(msg);
}
if (log.isDebugEnabled() && deviceIds.get(0).getType() != null) {
log.debug("Adding operation for Device type : " + deviceIds.get(0).getType() + ", tenant ID:"
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId() + ", domain:"
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain() + ", device count:"
+ deviceIds.size() + " operation type:" + operation.getCode());
}
DeviceIDHolder deviceAuthorizationResult = this.authorizeDevices(operation, validDeviceIds);
List<DeviceIdentifier> authorizedDeviceIds = deviceAuthorizationResult.getValidDeviceIDList();
if (authorizedDeviceIds.isEmpty()) {
log.warn("User : " + getUser() + " is not authorized to perform operations on given device-list.");
Activity activity = new Activity();
//Send the operation statuses only for admin triggered operations
activity.setActivityStatus(
this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult));
return activity;
}
boolean isScheduledOperation = this.isTaskScheduledOperation(operation);
String initiatedBy = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (initiatedBy == null && isScheduledOperation) {
if (log.isDebugEnabled()) {
log.debug("initiatedBy : " + SYSTEM);
}
operation.setInitiatedBy(SYSTEM);
} else {
if (log.isDebugEnabled()) {
log.debug("initiatedBy : " + initiatedBy);
}
operation.setInitiatedBy(initiatedBy);
}
boolean isScheduledOperation = this.isTaskScheduledOperation(operation);
String initiatedBy = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (initiatedBy == null && isScheduledOperation) {
if (log.isDebugEnabled()) {
log.debug("initiatedBy : " + SYSTEM);
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto =
OperationDAOUtil.convertOperation(operation);
String operationCode = operationDto.getCode();
Map<Integer, Device> enrolments = new HashMap<>();
Device device;
for (DeviceIdentifier deviceId : authorizedDeviceIds) {
device = getDevice(deviceId);
enrolments.put(device.getEnrolmentInfo().getId(), device);
}
operation.setInitiatedBy(SYSTEM);
} else {
if (log.isDebugEnabled()) {
log.debug("initiatedBy : " + initiatedBy);
OperationManagementDAOFactory.beginTransaction();
if (operationDto.getControl() ==
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT) {
Map<Integer, Integer> pendingOperationIDs = operationDAO
.getExistingOperationIDs(enrolments.keySet().toArray(new Integer[0]), operationCode);
for (Integer enrolmentId : pendingOperationIDs.keySet()) {
operation.setId(pendingOperationIDs.get(enrolmentId));
device = enrolments.get(enrolmentId);
this.sendNotification(operation, device);
//No need to keep this enrollment as it has a pending operation
enrolments.remove(enrolmentId);
}
if (enrolments.size() == 0) {
//No operations to be add. All are repeated.
if (log.isDebugEnabled()) {
log.debug("All the devices contain a pending operation for the Operation Code: "
+ operationCode);
}
Activity activity = new Activity();
//Send the operation statuses only for admin triggered operations
String deviceType = validDeviceIds.get(0).getType();
activity.setActivityStatus(this.getActivityStatus(deviceValidationResult,
deviceAuthorizationResult));
return activity;
}
}
operation.setInitiatedBy(initiatedBy);
}
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto = OperationDAOUtil
.convertOperation(operation);
int enrolmentId;
String operationCode = operationDto.getCode();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
int operationId = this.lookupOperationDAO(operation).addOperation(operationDto);
operationDto.setId(operationId);
List<Device> authorizedDevices = new ArrayList<>();
List<Device> ignoredDevices = new ArrayList<>();
for (DeviceIdentifier deviceId : authorizedDeviceIds) {
Device device = getDevice(deviceId);
authorizedDevices.add(device);
}
boolean isScheduled = false;
NotificationStrategy notificationStrategy = getNotificationStrategy();
OperationManagementDAOFactory.beginTransaction();
if (operationDto.getControl()
== org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT) {
int existingOperationID;
for (Device device : authorizedDevices) {
enrolmentId = device.getEnrolmentInfo().getId();
existingOperationID = operationDAO.getExistingOperationID(enrolmentId, operationCode);
if (existingOperationID > 0) {
ignoredDevices.add(device);
operation.setId(existingOperationID);
this.sendNotification(operation, device);
// check whether device list is greater than batch size notification strategy has enable to send push
// notification using scheduler task
if (DeviceConfigurationManager.getInstance().getDeviceManagementConfig().
getPushNotificationConfiguration().getSchedulerBatchSize() <= authorizedDeviceIds.size() &&
notificationStrategy != null) {
isScheduled = notificationStrategy.getConfig().isScheduled();
}
int failAttempts = 0;
while (true) {
try {
operationMappingDAO.addOperationMapping(operationDto,
new ArrayList<>(enrolments.values()), isScheduled, tenantId);
OperationManagementDAOFactory.commitTransaction();
break;
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
if (++failAttempts > 3) {
String msg = "Error occurred while updating operation mapping. Operation ID: " +
operationId;
log.error(msg, e);
throw new OperationManagementException(msg, e);
}
log.warn("Unable to update operation status. Operation ID: " + operationId +
", Attempt: " + failAttempts + ", Error: " + e.getMessage());
try {
Thread.sleep(2000);
} catch (InterruptedException ignore) {
break;
}
}
}
}
if (!ignoredDevices.isEmpty()) {
if (authorizedDevices.size() == ignoredDevices.size()) {
if (log.isDebugEnabled()) {
log.debug(
"All the devices contain a pending operation for the Operation Code: " + operationCode);
if (!isScheduled && notificationStrategy != null) {
for (Device d : enrolments.values()) {
this.sendNotification(operation, d);
}
Activity activity = new Activity();
//Send the operation statuses only for admin triggered operations
activity.setActivityStatus(
this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult));
return activity;
} else {
authorizedDevices.removeAll(ignoredDevices);
}
Activity activity = new Activity();
activity.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + operationId);
activity.setCode(operationCode);
activity.setCreatedTimeStamp(new Date().toString());
activity.setType(Activity.Type.valueOf(operationDto.getType().toString()));
//For now set the operation statuses only for admin triggered operations
if (!isScheduledOperation) {
//Get the device-type from 1st valid DeviceIdentifier. We know the 1st element is definitely there.
String deviceType = validDeviceIds.get(0).getType();
activity.setActivityStatus(this.getActivityStatus(deviceValidationResult,
deviceAuthorizationResult));
}
return activity;
} else {
throw new InvalidDeviceException("Invalid device Identifiers found.");
}
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
throw new OperationManagementException("Error occurred while adding operation", e);
} catch (TransactionManagementException e) {
throw new OperationManagementException("Error occurred while initiating the transaction", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
}
int operationId = this.lookupOperationDAO(operation).addOperation(operationDto);
operation.setId(operationId);
@Override
public void addTaskOperation(String deviceType, Operation operation) throws OperationManagementException {
List<String> validStatuses = Arrays.asList(EnrolmentInfo.Status.ACTIVE.toString(),
EnrolmentInfo.Status.INACTIVE.toString(),
EnrolmentInfo.Status.UNREACHABLE.toString());
int batchSize = 2000;
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
PaginationRequest paginationRequest;
boolean hasRecords;
int start = 0;
OperationManagementDAOFactory.beginTransaction();
DeviceManagementDAOFactory.beginTransaction();
do {
paginationRequest = new PaginationRequest(start, batchSize);
paginationRequest.setStatusList(validStatuses);
paginationRequest.setDeviceType(deviceType);
List<Device> devices = deviceDAO.getDevices(paginationRequest, tenantId);
if (devices.size() == batchSize) {
hasRecords = true;
start += batchSize;
} else if (devices.size() == 0) {
break;
} else {
hasRecords = false;
}
operation.setInitiatedBy(SYSTEM);
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto =
OperationDAOUtil.convertOperation(operation);
String operationCode = operationDto.getCode();
Map<Integer, Device> enrolments = new HashMap<>();
for (Device device : devices) {
enrolments.put(device.getEnrolmentInfo().getId(), device);
}
if (operationDto.getControl() ==
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT) {
Map<Integer, Integer> pendingOperationIDs = operationDAO
.getExistingOperationIDs(enrolments.keySet().toArray(new Integer[0]), operationCode);
Device device;
for (Integer enrolmentId : pendingOperationIDs.keySet()) {
operation.setId(pendingOperationIDs.get(enrolmentId));
device = enrolments.get(enrolmentId);
this.sendNotification(operation, device);
//No need to keep this enrollment as it has a pending operation
enrolments.remove(enrolmentId);
}
if (enrolments.size() == 0) {
//No operations to be add. All are repeated.
break;
}
}
boolean isScheduled = false;
NotificationStrategy notificationStrategy = getNotificationStrategy();
int operationId = this.lookupOperationDAO(operation).addOperation(operationDto);
operationDto.setId(operationId);
// check whether device list is greater than batch size notification strategy has enable to send push
// notification using scheduler task
if (DeviceConfigurationManager.getInstance().getDeviceManagementConfig().
getPushNotificationConfiguration().getSchedulerBatchSize() <= authorizedDeviceIds.size()
&& notificationStrategy != null) {
isScheduled = notificationStrategy.getConfig().isScheduled();
}
boolean isScheduled = false;
NotificationStrategy notificationStrategy = getNotificationStrategy();
List<Integer> enrolmentIds = new ArrayList<>();
for (Device device : authorizedDevices) {
enrolmentId = device.getEnrolmentInfo().getId();
enrolmentIds.add(enrolmentId);
}
operationMappingDAO.addOperationMapping(operationId, enrolmentIds, isScheduled);
OperationManagementDAOFactory.commitTransaction();
if (!isScheduled && notificationStrategy != null) {
for (Device device : authorizedDevices) {
this.sendNotification(operation, device);
// check whether device list is greater than batch size notification strategy has enable to send push
// notification using scheduler task
if (DeviceConfigurationManager.getInstance().getDeviceManagementConfig().
getPushNotificationConfiguration().getSchedulerBatchSize() <= enrolments.size() &&
notificationStrategy != null) {
isScheduled = notificationStrategy.getConfig().isScheduled();
}
}
Activity activity = new Activity();
activity.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + operationId);
activity.setCode(operationCode);
activity.setCreatedTimeStamp(new Date().toString());
activity.setType(Activity.Type.valueOf(operationDto.getType().toString()));
//For now set the operation statuses only for admin triggered operations
if (!isScheduledOperation) {
activity.setActivityStatus(
this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult));
}
return activity;
int failAttempts = 0;
while (true) {
try {
operationMappingDAO.addOperationMapping(operationDto,
new ArrayList<>(enrolments.values()), isScheduled, tenantId);
OperationManagementDAOFactory.commitTransaction();
break;
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
if (++failAttempts > 3) {
String msg = "Error occurred while updating operation mapping. Operation ID: " +
operationId;
log.error(msg, e);
throw new OperationManagementException(msg, e);
}
log.warn("Unable to update operation status. Operation ID: " + operationId +
", Attempt: " + failAttempts + ", Error: " + e.getMessage());
try {
Thread.sleep(2000);
} catch (InterruptedException ignore) {
break;
}
}
}
if (!isScheduled && notificationStrategy != null) {
for (Device device : enrolments.values()) {
this.sendNotification(operation, device);
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException ignore) {
break;
}
} while (hasRecords);
} catch (DeviceManagementDAOException e) {
throw new OperationManagementException("Error occurred while getting devices to add operations", e);
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
throw new OperationManagementException("Error occurred while adding operation", e);
} catch (TransactionManagementException e) {
throw new OperationManagementException("Error occurred while initiating the transaction", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
OperationManagementDAOFactory.closeConnection();
}
}
private void sendNotification(Operation operation, Device device) {
if (log.isDebugEnabled()) {
log.debug("Sending notification for device id: " + device.getDeviceIdentifier() + ", type:" + device
.getType() + ", tenant:" + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()
+ ", domain:" + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
}
NotificationStrategy notificationStrategy = getNotificationStrategy();
/*
* If notification strategy has not enable to send push notification using scheduler task we will send
@ -309,43 +430,61 @@ public class OperationManagerImpl implements OperationManager {
notificationStrategy.execute(new NotificationContext(deviceIdentifier, operation));
} catch (PushNotificationExecutionFailedException e) {
log.error("Error occurred while sending push notifications to " + device.getType() +
" device carrying id '" + device.getDeviceIdentifier() + "'", e);
" device carrying id '" + device.getDeviceIdentifier() + "'", e);
/*
* Reschedule if push notification failed. Doing db transactions in atomic way to prevent
* deadlocks.
*/
try {
operationMappingDAO.updateOperationMapping(operation.getId(), device.getEnrolmentInfo().getId(), org.wso2.carbon
.device.mgt.core.dto.operation.mgt.Operation.PushNotificationStatus.SCHEDULED);
OperationManagementDAOFactory.commitTransaction();
} catch (OperationManagementDAOException ex) {
// Not throwing this exception in order to keep scheduling remaining notifications if any.
log.error("Error occurred while setting push notification status to SCHEDULED.", ex);
OperationManagementDAOFactory.rollbackTransaction();
int failAttempts = 0;
while (true) {
try {
operationMappingDAO.updateOperationMapping(operation.getId(), device.getEnrolmentInfo().getId(),
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.PushNotificationStatus.SCHEDULED);
OperationManagementDAOFactory.commitTransaction();
break;
} catch (OperationManagementDAOException ex) {
OperationManagementDAOFactory.rollbackTransaction();
if (++failAttempts > 3) {
String msg = "Error occurred while setting push notification status to SCHEDULED. Operation ID: " +
operation.getId() + ", Enrollment ID: " + device.getEnrolmentInfo().getId() +
", Device ID:" + device.getDeviceIdentifier();
log.error(msg, e);
break;
}
log.warn("Unable to set push notification status to SCHEDULED. Operation ID: " +
operation.getId() + ", Enrollment ID: " + device.getEnrolmentInfo().getId() +
", Device ID:" + device.getDeviceIdentifier() + ", Attempt: " + failAttempts +
", Error: " + e.getMessage());
try {
Thread.sleep(2000);
} catch (InterruptedException ignore) {
break;
}
}
}
} catch (Exception e) {
log.error("Error occurred while sending notifications to " + device.getType() + " device carrying id '"
+ device.getDeviceIdentifier() + "'", e);
log.error("Error occurred while sending notifications to " + device.getType() +
" device carrying id '" + device.getDeviceIdentifier() + "'", e);
}
}
}
private List<ActivityStatus> getActivityStatus(DeviceIDHolder deviceIdValidationResult,
DeviceIDHolder deviceAuthResult) {
DeviceIDHolder deviceAuthResult) {
List<ActivityStatus> activityStatuses = new ArrayList<>();
ActivityStatus activityStatus;
//Add the invalid DeviceIds
for (DeviceIdentifier id : deviceIdValidationResult.getErrorDeviceIdList()) {
for (DeviceIdentifier deviceIdentifier : deviceIdValidationResult.getErrorDeviceIdList()) {
activityStatus = new ActivityStatus();
activityStatus.setDeviceIdentifier(id);
activityStatus.setDeviceIdentifier(deviceIdentifier);
activityStatus.setStatus(ActivityStatus.Status.INVALID);
activityStatuses.add(activityStatus);
}
//Add the unauthorized DeviceIds
for (DeviceIdentifier id : deviceAuthResult.getErrorDeviceIdList()) {
for (DeviceIdentifier deviceIdentifier : deviceAuthResult.getErrorDeviceIdList()) {
activityStatus = new ActivityStatus();
activityStatus.setDeviceIdentifier(id);
activityStatus.setDeviceIdentifier(deviceIdentifier);
activityStatus.setStatus(ActivityStatus.Status.UNAUTHORIZED);
activityStatuses.add(activityStatus);
}
@ -401,7 +540,7 @@ public class OperationManagerImpl implements OperationManager {
@Override
public List<? extends Operation> getOperations(DeviceIdentifier deviceId) throws OperationManagementException {
List<Operation> operations = null;
List<Operation> operations;
if (!isActionAuthorized(deviceId)) {
throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
@ -440,7 +579,7 @@ public class OperationManagerImpl implements OperationManager {
@Override
public PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request)
throws OperationManagementException {
PaginationResult paginationResult = null;
PaginationResult paginationResult;
List<Operation> operations = new ArrayList<>();
String owner = request.getOwner();
try {
@ -492,14 +631,36 @@ public class OperationManagerImpl implements OperationManager {
return paginationResult;
}
@Override
public List<? extends Operation> getOperations(DeviceIdentifier deviceId, Operation.Status status)
throws OperationManagementException {
if (log.isDebugEnabled()) {
log.debug("Device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType() + "]");
}
if (!isActionAuthorized(deviceId)) {
throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
deviceId.getType() + "' device, which carries the identifier '" +
deviceId.getId() + "'");
}
PaginationRequest request = new PaginationRequest(0, 0);
request.setOwner(getUser());
EnrolmentInfo enrolmentInfo = this.getEnrolmentInfo(deviceId, request);
if (enrolmentInfo == null) {
throw new OperationManagementException("Device not found for the given device Identifier:" +
deviceId.getId() + " and given type:" +
deviceId.getType());
}
int enrolmentId = enrolmentInfo.getId();
return getOperations(deviceId, status, enrolmentId);
}
@Override
public List<? extends Operation> getPendingOperations(DeviceIdentifier deviceId) throws
OperationManagementException {
if (log.isDebugEnabled()) {
log.debug("Device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType() + "]");
}
List<Operation> operations = new ArrayList<>();
List<org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> dtoOperationList = new ArrayList<>();
EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId);
if (enrolmentInfo == null) {
@ -513,36 +674,12 @@ public class OperationManagerImpl implements OperationManager {
case INACTIVE:
case UNREACHABLE:
this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE);
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
DeviceCacheManagerImpl.getInstance().removeDeviceFromCache(deviceId, tenantId);
break;
}
try {
OperationManagementDAOFactory.openConnection();
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 OperationIdComparator());
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
"pending operations assigned for '" + deviceId.getType() +
"' device '" + deviceId.getId() + "'", e);
} catch (SQLException e) {
throw new OperationManagementException(
"Error occurred while opening a connection to the data source", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
return operations;
return getOperations(deviceId, Operation.Status.PENDING, enrolmentId);
}
@Override
@ -553,17 +690,21 @@ public class OperationManagerImpl implements OperationManager {
device.getId() + " and given type:" +
device.getType());
}
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setType(device.getType());
deviceIdentifier.setId(device.getDeviceIdentifier());
int enrolmentId = enrolmentInfo.getId();
//Changing the enrollment status & attempt count if the device is marked as inactive or unreachable
switch (enrolmentInfo.getStatus()) {
case INACTIVE:
case UNREACHABLE:
this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setEnrolmentInfo(enrolmentInfo);
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
DeviceCacheManagerImpl.getInstance().addDeviceToCache(deviceIdentifier, device, tenantId);
break;
}
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setType(device.getType());
deviceIdentifier.setId(device.getDeviceIdentifier());
return getOperations(deviceIdentifier, Operation.Status.PENDING, enrolmentId);
}
@ -599,6 +740,8 @@ public class OperationManagerImpl implements OperationManager {
case INACTIVE:
case UNREACHABLE:
this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE);
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
DeviceCacheManagerImpl.getInstance().removeDeviceFromCache(deviceId, tenantId);
break;
}
@ -673,29 +816,136 @@ public class OperationManagerImpl implements OperationManager {
"Device not found for device id:" + deviceId.getId() + " " + "type:" +
deviceId.getType());
}
updateOperation(enrolmentInfo.getId(), operation);
updateOperation(enrolmentInfo.getId(), operation, deviceId);
}
@Override
public void updateOperation(int enrolmentId, Operation operation) throws OperationManagementException {
public void updateOperation(int enrolmentId, Operation operation, DeviceIdentifier deviceId)
throws OperationManagementException {
int operationId = operation.getId();
try {
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()));
int failAttempts = 0;
while (true) {
try {
operationDAO.updateOperationStatus(enrolmentId, operationId,
org.wso2.carbon.device.mgt.core.dto.operation.mgt.
Operation.Status.valueOf(operation.getStatus().
toString()));
OperationManagementDAOFactory.commitTransaction();
break;
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
if (++failAttempts > 3) {
String msg = "Error occurred while updating operation status. Operation ID: " +
operationId + ", Enrollment ID: " + enrolmentId + ", Device ID:" + deviceId;
log.error(msg, e);
throw new OperationManagementException(msg, e);
}
log.warn("Unable to update operation status. Operation ID: " + operationId +
", Enrollment ID: " + enrolmentId + ", Device ID:" + deviceId + ", Attempt: " + failAttempts +
", Error: " + e.getMessage());
try {
Thread.sleep(2000);
} catch (InterruptedException ignore) {
break;
}
}
}
}
if (operation.getOperationResponse() != null) {
operationDAO.addOperationResponse(enrolmentId, operationId, operation.getOperationResponse());
OperationMonitoringTaskConfig operationMonitoringTaskConfig = DeviceManagementDataHolder
.getInstance().getDeviceManagementProvider().getDeviceMonitoringConfig(deviceId.getType());
List<MonitoringOperation> monitoringOperations = operationMonitoringTaskConfig.getMonitoringOperation();
MonitoringOperation currentMonitoringOperation = null;
for (MonitoringOperation monitoringOperation : monitoringOperations) {
if (operation.getCode().equals(monitoringOperation.getTaskName())) {
currentMonitoringOperation = monitoringOperation;
break;
}
}
if (currentMonitoringOperation != null && !currentMonitoringOperation.hasResponsePersistence()) {
String initiatedBy = operationsInitBy.get(operationId);
if (initiatedBy == null) {
try {
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto =
operationDAO.getOperation(operationId);
operation.setInitiatedBy(operationDto.getInitiatedBy());
if (operationsInitBy.size() > maxOperationCacheSize) {
Integer obsoleteOperationId = (Integer) operationsInitBy.keySet().toArray()[0];
operationsInitBy.remove(obsoleteOperationId);
}
operationsInitBy.put(operationId, operation.getInitiatedBy());
} catch (OperationManagementDAOException e) {
log.warn("Unable to get operationDTO for Operation ID: " + operationId +
", Error: " + e.getErrorMessage());
}
} else {
operation.setInitiatedBy(initiatedBy);
}
if (SYSTEM.equals(operation.getInitiatedBy())) {
return;
}
}
}
OperationResponseMeta responseMeta = null;
if (operation.getOperationResponse() != null) {
int failAttempts = 0;
while (true) {
try {
responseMeta = operationDAO.addOperationResponse(enrolmentId, operation, deviceId.getId());
OperationManagementDAOFactory.commitTransaction();
break;
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
if (++failAttempts > 3) {
String msg = "Error occurred while updating operation response. Operation ID: " +
operationId + ", Enrollment ID: " + enrolmentId + ", Device ID:" + deviceId;
log.error(msg, e);
throw new OperationManagementException(msg, e);
}
log.warn("Unable to update operation response. Operation ID: " + operationId +
", Enrollment ID: " + enrolmentId + ", Device ID:" + deviceId + " Attempt: " + failAttempts +
", Error: " + e.getErrorMessage());
try {
Thread.sleep(2000);
} catch (InterruptedException ignore) {
break;
}
}
}
}
if (responseMeta != null && responseMeta.isLargeResponse() && responseMeta.getId() > 0) {
int failAttempts = 0;
while (true) {
try {
operationDAO.addOperationResponseLarge(responseMeta, operation, deviceId.getId());
OperationManagementDAOFactory.commitTransaction();
break;
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
if (++failAttempts > 3) {
String msg = "Error occurred while updating large operation response. " +
"Enrollment Mapping ID: " + responseMeta.getOperationMappingId() +
", Response ID: " + responseMeta.getId() + ", Operation ID: " + operationId +
", Enrollment ID: " + enrolmentId + ", Device ID:" + deviceId;
log.error(msg, e);
throw new OperationManagementException(msg, e);
}
log.warn("Unable to update large operation response. " +
"Enrollment Mapping ID: " + responseMeta.getOperationMappingId() +
", Response ID: " + responseMeta.getId() + ", Operation ID: " + operationId +
", Enrollment ID: " + enrolmentId + ", Device ID:" + deviceId +
", Attempt: " + failAttempts + ", Error: " + e.getMessage());
try {
Thread.sleep(2000);
} catch (InterruptedException ignore) {
break;
}
}
}
}
OperationManagementDAOFactory.commitTransaction();
} catch (OperationManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
throw new OperationManagementException(
"Error occurred while updating the operation: " + operationId + " status:" +
operation.getStatus(), e);
} catch (TransactionManagementException e) {
throw new OperationManagementException("Error occurred while initiating a transaction", e);
} finally {
@ -706,7 +956,7 @@ public class OperationManagerImpl implements OperationManager {
@Override
public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId)
throws OperationManagementException {
Operation operation = null;
Operation operation;
if (log.isDebugEnabled()) {
log.debug("Operation Id: " + operationId + " Device Type: " + deviceId.getType() + " Device Identifier: " +
deviceId.getId());
@ -913,7 +1163,8 @@ public class OperationManagerImpl implements OperationManager {
}
}
public Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) throws OperationManagementException {
public Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId)
throws OperationManagementException {
// This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer.
int operationId = Integer.parseInt(
activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, ""));
@ -957,7 +1208,7 @@ public class OperationManagerImpl implements OperationManager {
@Override
public List<Activity> getFilteredActivities(String operationCode, int limit, int offset) throws OperationManagementException{
public List<Activity> getFilteredActivities(String operationCode, int limit, int offset) throws OperationManagementException {
try {
OperationManagementDAOFactory.openConnection();
return operationDAO.getFilteredActivities(operationCode, limit, offset);
@ -972,7 +1223,7 @@ public class OperationManagerImpl implements OperationManager {
}
@Override
public int getTotalCountOfFilteredActivities(String operationCode) throws OperationManagementException{
public int getTotalCountOfFilteredActivities(String operationCode) throws OperationManagementException {
try {
OperationManagementDAOFactory.openConnection();
return operationDAO.getTotalCountOfFilteredActivities(operationCode);
@ -1142,23 +1393,38 @@ public class OperationManagerImpl implements OperationManager {
return enrolmentInfo;
}
private boolean setEnrolmentStatus(int enrolmentId, EnrolmentInfo.Status status) throws OperationManagementException {
boolean updateStatus;
private void setEnrolmentStatus(int enrolmentId, EnrolmentInfo.Status status) throws OperationManagementException {
try {
DeviceManagementDAOFactory.beginTransaction();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
updateStatus = enrollmentDAO.setStatus(enrolmentId, status, tenantId);
DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new OperationManagementException("Error occurred while updating enrollment status of device of " +
"enrolment-id '" + enrolmentId + "'", e);
int failAttempts = 0;
while (true) {
try {
enrollmentDAO.setStatus(enrolmentId, status, tenantId);
DeviceManagementDAOFactory.commitTransaction();
break;
} catch (DeviceManagementDAOException e) {
OperationManagementDAOFactory.rollbackTransaction();
if (++failAttempts > 3) {
String msg = "Error occurred while updating enrollment status of device of " +
"enrolment-id '" + enrolmentId + "'";
log.error(msg, e);
throw new OperationManagementException(msg, e);
}
log.warn("Unable to update enrollment status of device of enrolment-id '" +
enrolmentId + ", Attempt: " + failAttempts + ", Error: " + e.getMessage());
try {
Thread.sleep(2000);
} catch (InterruptedException ignore) {
break;
}
}
}
} catch (TransactionManagementException e) {
throw new OperationManagementException("Error occurred while initiating a transaction", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
return updateStatus;
}
private boolean isTaskScheduledOperation(Operation operation) {
@ -1173,6 +1439,10 @@ public class OperationManagerImpl implements OperationManager {
return false;
}
private boolean isSameUser(String user, String owner) {
return user.equalsIgnoreCase(owner);
}
private List<? extends Operation> getOperations(DeviceIdentifier deviceId, Operation.Status status, int enrolmentId)
throws OperationManagementException {
List<Operation> operations = new ArrayList<>();

@ -20,7 +20,9 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationResponse;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.OperationResponseMeta;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping;
import java.util.List;
@ -54,15 +56,24 @@ public interface OperationDAO {
void updateEnrollmentOperationsStatus(int enrolmentId, String operationCode, Operation.Status existingStatus,
Operation.Status newStatus) throws OperationManagementDAOException;
int getExistingOperationID(int enrolmentId, String operationCode) throws OperationManagementDAOException;
Map<Integer, Integer> getExistingOperationIDs(Integer[] enrolmentIds, String operationCode)
throws OperationManagementDAOException;
void addOperationResponse(int enrolmentId, int operationId, Object operationResponse)
OperationResponseMeta addOperationResponse(int enrolmentId, org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation, String deviceId)
throws OperationManagementDAOException;
Activity getActivity(int operationId) throws OperationManagementDAOException;
List<Activity> getActivityList(List<Integer> operationIds) throws OperationManagementDAOException;
void addOperationResponseLarge(OperationResponseMeta responseMeta,
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation,
String deviceId) throws OperationManagementDAOException;
Map<String, Map<String, List<OperationResponse>>> getLargeOperationResponsesInBulk(List<Integer> operationIds) throws OperationManagementDAOException;
void populateLargeOperationResponses(List<Activity> activities, List<Integer> largeResponseIDs) throws OperationManagementDAOException;
Activity getActivityByDevice(int operationId, int deviceId) throws OperationManagementDAOException;
List<Activity> getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementDAOException;

@ -37,14 +37,9 @@ public class OperationManagementDAOUtil {
log.warn("Error occurred while closing the result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing the statement", e);
}
}
cleanupResources(stmt);
}
public static void cleanupResources(Statement stmt) {
if (stmt != null) {
try {

@ -18,6 +18,8 @@
*/
package org.wso2.carbon.device.mgt.core.operation.mgt.dao;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping;
@ -27,10 +29,9 @@ import java.util.Map;
public interface OperationMappingDAO {
void addOperationMapping(int operationId, int enrollmentId, boolean isScheduled)
throws OperationManagementDAOException;
void addOperationMapping(Operation operation, Integer deviceId, boolean isScheduled, Device device, Integer tenantId) throws OperationManagementDAOException;
void addOperationMapping(int operationId, List<Integer> enrollmentIds, boolean isScheduled)
void addOperationMapping(Operation operation, List<Device> devices, boolean isScheduled, Integer tenantId)
throws OperationManagementDAOException;
void removeOperationMapping(int operationId, Integer deviceId) throws OperationManagementDAOException;

@ -26,6 +26,7 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.ActivityStatus;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationResponse;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.OperationResponseMeta;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationDAO;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException;
@ -33,10 +34,8 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOF
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
@ -44,7 +43,6 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
@ -81,7 +79,8 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
return id;
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while adding operation metadata", e);
throw new OperationManagementDAOException("Error occurred while adding operation metadata. " +
e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
@ -106,7 +105,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while update device mapping operation status " +
"metadata", e);
"metadata. " + e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt);
}
@ -151,70 +150,134 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
@Override
public int getExistingOperationID(int enrolmentId, String operationCode)
public Map<Integer, Integer> getExistingOperationIDs(Integer[] enrolmentIds, String operationCode)
throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
int result = -1;
Map<Integer, Integer> existingOperationIds = new HashMap<>();
try {
Connection connection = OperationManagementDAOFactory.getConnection();
String query = "SELECT DM.ID FROM DM_ENROLMENT_OP_MAPPING EOM INNER JOIN DM_OPERATION DM "
+ "ON DM.ID = EOM.OPERATION_ID WHERE EOM.ENROLMENT_ID = ? AND DM.OPERATION_CODE = ? AND "
+ "EOM.STATUS = ?";
stmt = connection.prepareStatement(query);
stmt.setInt(1, enrolmentId);
stmt.setString(2, operationCode);
stmt.setString(3, Operation.Status.PENDING.toString());
// This will return only one result always.
StringBuilder query = new StringBuilder("SELECT OPERATION_ID, ENROLMENT_ID FROM DM_ENROLMENT_OP_MAPPING " +
"WHERE OPERATION_CODE = ? AND STATUS = ? AND ENROLMENT_ID IN (");
for (int i = 0; i < enrolmentIds.length; i++) {
query.append(" ?,");
}
query.deleteCharAt(query.length() - 1);
query.append(")");
stmt = connection.prepareStatement(query.toString());
stmt.setString(1, operationCode);
stmt.setString(2, Operation.Status.PENDING.toString());
for (int i = 0; i < enrolmentIds.length; i++) {
stmt.setInt(i + 3, enrolmentIds[i]);
}
rs = stmt.executeQuery();
if (rs.next()) {
result = rs.getInt("ID");
int operationId;
int enrollmentId;
while (rs.next()) {
enrollmentId = rs.getInt("ENROLMENT_ID");
operationId = rs.getInt("OPERATION_ID");
existingOperationIds.put(enrollmentId, operationId);
}
} catch (SQLException e) {
throw new OperationManagementDAOException(
"Error occurred while update device mapping operation status " + "metadata", e);
throw new OperationManagementDAOException("Error occurred while update device mapping operation status " +
"metadata. " + e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
return result;
return existingOperationIds;
}
@Override
public void addOperationResponse(int enrolmentId, int operationId, Object operationResponse)
throws OperationManagementDAOException {
public OperationResponseMeta addOperationResponse(int enrolmentId,
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation,
String deviceId) throws OperationManagementDAOException {
PreparedStatement stmt = null;
ByteArrayOutputStream bao = null;
ObjectOutputStream oos = null;
ResultSet rs = null;
boolean isLargeResponse = false;
try {
Connection connection = OperationManagementDAOFactory.getConnection();
stmt = connection.prepareStatement("SELECT ID FROM DM_ENROLMENT_OP_MAPPING WHERE ENROLMENT_ID = ? " +
"AND OPERATION_ID = ?");
stmt.setInt(1, enrolmentId);
stmt.setInt(2, operationId);
stmt.setInt(2, operation.getId());
rs = stmt.executeQuery();
int enPrimaryId = 0;
if(rs.next()){
if (rs.next()) {
enPrimaryId = rs.getInt("ID");
}
stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID, ENROLMENT_ID, " +
"EN_OP_MAP_ID, OPERATION_RESPONSE, RECEIVED_TIMESTAMP) VALUES(?, ?, ?, ?, ?)");
bao = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bao);
oos.writeObject(operationResponse);
stmt.setInt(1, operationId);
"EN_OP_MAP_ID, OPERATION_RESPONSE, IS_LARGE_RESPONSE, RECEIVED_TIMESTAMP) VALUES(?, ?, ?, ?, ?, ?)",
new String[]{"ID"});
stmt.setInt(1, operation.getId());
stmt.setInt(2, enrolmentId);
stmt.setInt(3, enPrimaryId);
stmt.setBytes(4, bao.toByteArray());
stmt.setTimestamp(5, new Timestamp(new Date().getTime()));
if (operation.getOperationResponse() != null && operation.getOperationResponse().length() >= 1000) {
isLargeResponse = true;
stmt.setBytes(4, null);
} else {
stmt.setString(4, operation.getOperationResponse());
}
stmt.setBoolean(5, isLargeResponse);
Timestamp receivedTimestamp = new Timestamp(new Date().getTime());
stmt.setTimestamp(6, receivedTimestamp);
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
int opResID = -1;
if (rs.next()) {
opResID = rs.getInt(1);
}
OperationResponseMeta responseMeta = new OperationResponseMeta();
responseMeta.setId(opResID);
responseMeta.setEnrolmentId(enrolmentId);
responseMeta.setOperationMappingId(enPrimaryId);
responseMeta.setReceivedTimestamp(receivedTimestamp);
responseMeta.setLargeResponse(isLargeResponse);
return responseMeta;
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while inserting operation response. " +
e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public void addOperationResponseLarge(OperationResponseMeta responseMeta,
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation,
String deviceId) throws OperationManagementDAOException {
PreparedStatement stmt = null;
ByteArrayOutputStream bao = null;
ObjectOutputStream oos = null;
ResultSet rs = null;
try {
Connection connection = OperationManagementDAOFactory.getConnection();
stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE_LARGE " +
"(ID, OPERATION_RESPONSE, OPERATION_ID, EN_OP_MAP_ID, RECEIVED_TIMESTAMP, DEVICE_IDENTIFICATION) " +
"VALUES(?, ?, ?, ?, ?, ?)");
bao = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bao);
oos.writeObject(operation.getOperationResponse());
stmt.setInt(1, responseMeta.getId());
stmt.setBytes(2, bao.toByteArray());
stmt.setInt(3, operation.getId());
stmt.setInt(4, responseMeta.getOperationMappingId());
stmt.setTimestamp(5, responseMeta.getReceivedTimestamp());
stmt.setString(6, deviceId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while inserting operation response", e);
throw new OperationManagementDAOException("Error occurred while inserting operation response. " +
e.getMessage(), e);
} catch (IOException e) {
throw new OperationManagementDAOException("Error occurred while serializing policy operation object", e);
throw new OperationManagementDAOException("Error occurred while serializing operation response object. " +
e.getMessage(), e);
} finally {
if (bao != null) {
try {
@ -234,6 +297,93 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
}
@Override
public Map<String, Map<String, List<OperationResponse>>> getLargeOperationResponsesInBulk(List<Integer> operationResponseIds)
throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
Map<String, Map<String, List<OperationResponse>>> operationResponseMapping = new HashMap<>();
Map<String, List<OperationResponse>> operationDeviceMappings;
List<OperationResponse> responseList;
try {
Connection conn = OperationManagementDAOFactory.getConnection();
String sql1 = "SELECT * FROM DM_DEVICE_OPERATION_RESPONSE_LARGE WHERE ID IN (";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < operationResponseIds.size(); i++) {
builder.append("?,");
}
sql1 += builder.deleteCharAt(builder.length() - 1).toString() + ")";
stmt = conn.prepareStatement(sql1);
int i;
for (i = 0; i < operationResponseIds.size(); i++) {
stmt.setInt(i + 1, operationResponseIds.get(i));
}
rs = stmt.executeQuery();
while (rs.next()) {
String activityID = OperationDAOUtil.getActivityId(rs.getInt("OPERATION_ID"));
String deviceID = rs.getString("DEVICE_IDENTIFICATION");
if (operationResponseMapping.containsKey(activityID)) {
operationDeviceMappings = operationResponseMapping.get(activityID);
if (operationDeviceMappings.containsKey(deviceID)) {
responseList = operationDeviceMappings.get(deviceID);
} else {
responseList = new ArrayList<>();
operationDeviceMappings.put(deviceID, responseList);
}
} else {
responseList = new ArrayList<>();
operationDeviceMappings = new HashMap<>();
operationDeviceMappings.put(deviceID, responseList);
operationResponseMapping.put(activityID, operationDeviceMappings);
}
responseList.add(OperationDAOUtil.getLargeOperationResponse(rs));
}
} catch (SQLException e) {
throw new OperationManagementDAOException(
"Error occurred while getting the operation details from the database. " + e.getMessage(), e);
} catch (ClassNotFoundException e) {
throw new OperationManagementDAOException(
"Error occurred while converting the operation response to string.. " + e.getMessage(), e);
} catch (IOException e) {
throw new OperationManagementDAOException(
"IO exception occurred while converting the operations responses. " + e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
return operationResponseMapping;
}
@Override
public void populateLargeOperationResponses(List<Activity> activities,
List<Integer> largeResponseIDs)
throws OperationManagementDAOException {
if (!largeResponseIDs.isEmpty()) {
Map<String, Map<String, List<OperationResponse>>> largeOperationResponses = getLargeOperationResponsesInBulk(largeResponseIDs);
if (!largeOperationResponses.isEmpty()) {
for (Activity tempActivity : activities) {
if (largeOperationResponses.containsKey(tempActivity.getActivityId())) {
List<ActivityStatus> activityStatuses = tempActivity.getActivityStatus();
Map<String, List<OperationResponse>> deviceOpResponseMap = largeOperationResponses.get(tempActivity.getActivityId());
for (Map.Entry<String, List<OperationResponse>> deviceOpRes : deviceOpResponseMap.entrySet()) {
for (ActivityStatus status : activityStatuses) {
if (deviceOpRes.getKey().equalsIgnoreCase(status.getDeviceIdentifier().getId())) {
status.getResponses().addAll(deviceOpRes.getValue());
}
}
}
}
}
}
}
}
@Override
public Activity getActivity(int operationId) throws OperationManagementDAOException {
@ -243,18 +393,29 @@ public class GenericOperationDAOImpl implements OperationDAO {
List<ActivityStatus> activityStatusList = new ArrayList<>();
try {
Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "SELECT eom.ENROLMENT_ID, eom.OPERATION_ID, eom.ID AS EOM_MAPPING_ID, dor.ID AS OP_RES_ID,\n" +
"de.DEVICE_ID, d.DEVICE_IDENTIFICATION, \n" +
"d.DEVICE_TYPE_ID, dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, \n" +
"eom.UPDATED_TIMESTAMP, op.OPERATION_CODE, op.TYPE AS OPERATION_TYPE, dor.OPERATION_RESPONSE, \n" +
"dor.RECEIVED_TIMESTAMP, op.INITIATED_BY FROM DM_ENROLMENT_OP_MAPPING eom \n" +
"INNER JOIN DM_OPERATION op ON op.ID=eom.OPERATION_ID\n" +
"INNER JOIN DM_ENROLMENT de ON de.ID=eom.ENROLMENT_ID\n" +
"INNER JOIN DM_DEVICE d ON d.ID=de.DEVICE_ID \n" +
"INNER JOIN DM_DEVICE_TYPE dt ON dt.ID=d.DEVICE_TYPE_ID\n" +
"LEFT JOIN DM_DEVICE_OPERATION_RESPONSE dor ON dor.ENROLMENT_ID=de.id \n" +
"AND dor.OPERATION_ID = eom.OPERATION_ID\n" +
"WHERE eom.OPERATION_ID = ? AND de.TENANT_ID = ?";
String sql = "SELECT " +
" eom.ENROLMENT_ID," +
" eom.CREATED_TIMESTAMP," +
" eom.UPDATED_TIMESTAMP," +
" eom.OPERATION_ID," +
" eom.OPERATION_CODE," +
" eom.INITIATED_BY," +
" eom.TYPE AS OPERATION_TYPE," +
" eom.STATUS," +
" eom.DEVICE_ID," +
" eom.DEVICE_IDENTIFICATION," +
" eom.DEVICE_TYPE AS DEVICE_TYPE_NAME," +
" eom.ID AS EOM_MAPPING_ID," +
" opr.ID AS OP_RES_ID," +
" opr.RECEIVED_TIMESTAMP," +
" opr.OPERATION_RESPONSE," +
" opr.IS_LARGE_RESPONSE " +
"FROM " +
" DM_ENROLMENT_OP_MAPPING eom " +
" LEFT JOIN " +
" DM_DEVICE_OPERATION_RESPONSE opr ON opr.EN_OP_MAP_ID = eom.ID " +
"WHERE " +
" eom.OPERATION_ID = ? AND eom.TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, operationId);
@ -263,7 +424,8 @@ public class GenericOperationDAOImpl implements OperationDAO {
int enrolmentId = 0;
ActivityStatus activityStatus = null;
int responseId = 0;
List<Integer> largeResponseIDs = new ArrayList<>();
while (rs.next()) {
if (enrolmentId == 0) {
activity = new Activity();
@ -295,17 +457,40 @@ public class GenericOperationDAOImpl implements OperationDAO {
activity.setActivityStatus(activityStatusList);
} else {
if (rs.getInt("UPDATED_TIMESTAMP") != 0) {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
if (activityStatus == null) {
activityStatus = new ActivityStatus();
}
if (activityStatus.getResponses() == null) {
activityStatus.setResponses(new ArrayList<>());
}
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
}
}
}
}
if (!largeResponseIDs.isEmpty()) {
Map<String, Map<String, List<OperationResponse>>> largeOperationResponses = getLargeOperationResponsesInBulk(largeResponseIDs);
if (!largeOperationResponses.isEmpty()) {
List<ActivityStatus> activityStatuses = activity.getActivityStatus();
if (activityStatuses != null) {
Map<String, List<OperationResponse>> deviceOpResponseMap = largeOperationResponses.get(activity.getActivityId());
for (Map.Entry<String, List<OperationResponse>> deviceOpRes : deviceOpResponseMap.entrySet()) {
for (ActivityStatus status : activityStatuses) {
if (deviceOpRes.getKey().equalsIgnoreCase(status.getDeviceIdentifier().getId())) {
status.getResponses().addAll(deviceOpRes.getValue());
}
}
}
}
}
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while getting the operation details from " +
"the database.", e);
} catch (ClassNotFoundException e) {
throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e);
} catch (IOException e) {
throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e);
"the database. " + e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
@ -328,12 +513,12 @@ public class GenericOperationDAOImpl implements OperationDAO {
+ "dor.ID AS OP_RES_ID, de.DEVICE_ID, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID, "
+ "dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, "
+ "eom.UPDATED_TIMESTAMP, op.OPERATION_CODE, op.TYPE AS OPERATION_TYPE, "
+ "dor.OPERATION_RESPONSE, op.INITIATED_BY, dor.RECEIVED_TIMESTAMP FROM "
+ "dor.OPERATION_RESPONSE, op.INITIATED_BY, dor.RECEIVED_TIMESTAMP, dor.IS_LARGE_RESPONSE FROM "
+ "DM_ENROLMENT_OP_MAPPING eom INNER JOIN DM_OPERATION op "
+ "ON op.ID=eom.OPERATION_ID INNER JOIN DM_ENROLMENT de "
+ "ON de.ID=eom.ENROLMENT_ID INNER JOIN DM_DEVICE d ON d.ID=de.DEVICE_ID \n"
+ "INNER JOIN DM_DEVICE_TYPE dt ON dt.ID=d.DEVICE_TYPE_ID\n"
+ "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE dor ON dor.ENROLMENT_ID=de.id \n"
+ "ON de.ID=eom.ENROLMENT_ID INNER JOIN DM_DEVICE d ON d.ID=de.DEVICE_ID "
+ "INNER JOIN DM_DEVICE_TYPE dt ON dt.ID=d.DEVICE_TYPE_ID "
+ "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE dor ON dor.ENROLMENT_ID=de.id "
+ "AND dor.OPERATION_ID = eom.OPERATION_ID WHERE eom.OPERATION_ID "
+ "IN (SELECT * FROM TABLE(x INT = ?)) AND de.TENANT_ID = ?";
@ -347,6 +532,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
int enrolmentId = 0;
int responseId = 0;
ActivityStatus activityStatus = new ActivityStatus();
List<Integer> largeResponseIDs = new ArrayList<>();
while (rs.next()) {
activity = new Activity();
@ -379,8 +565,14 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getInt("UPDATED_TIMESTAMP") != 0) {
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
}
activityStatus.setResponses(operationResponses);
statusList.add(activityStatus);
@ -409,8 +601,12 @@ public class GenericOperationDAOImpl implements OperationDAO {
new java.util.Date(rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString());
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
activity.getActivityStatus().add(activityStatus);
@ -420,20 +616,21 @@ public class GenericOperationDAOImpl implements OperationDAO {
if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID") && rs.getTimestamp(
"RECEIVED_TIMESTAMP") != null) {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
}
}
}
if (!largeResponseIDs.isEmpty()) {
populateLargeOperationResponses(activities, largeResponseIDs);
}
} catch (SQLException e) {
throw new OperationManagementDAOException(
"Error occurred while getting the operation details from " + "the database.", e);
} catch (ClassNotFoundException e) {
throw new OperationManagementDAOException(
"Error occurred while converting the operation response to string.", e);
} catch (IOException e) {
throw new OperationManagementDAOException(
"IO exception occurred while converting the operations responses.", e);
"Error occurred while getting the operation details from the database. " + e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
@ -445,6 +642,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
PreparedStatement stmt = null;
ResultSet rs = null;
Activity activity = null;
int responseId = 0;
List<ActivityStatus> activityStatusList = new ArrayList<>();
try {
Connection conn = OperationManagementDAOFactory.getConnection();
@ -452,7 +650,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
"de.DEVICE_ID, d.DEVICE_IDENTIFICATION, \n" +
"d.DEVICE_TYPE_ID, dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, \n" +
"eom.UPDATED_TIMESTAMP, op.OPERATION_CODE, op.TYPE AS OPERATION_TYPE, dor.OPERATION_RESPONSE, \n" +
"dor.RECEIVED_TIMESTAMP, op.INITIATED_BY FROM DM_ENROLMENT_OP_MAPPING AS eom \n" +
"dor.RECEIVED_TIMESTAMP, dor.IS_LARGE_RESPONSE, op.INITIATED_BY FROM DM_ENROLMENT_OP_MAPPING AS eom \n" +
"INNER JOIN DM_OPERATION AS op ON op.ID=eom.OPERATION_ID\n" +
"INNER JOIN DM_ENROLMENT AS de ON de.ID=eom.ENROLMENT_ID\n" +
"INNER JOIN DM_DEVICE AS d ON d.ID=de.DEVICE_ID \n" +
@ -469,6 +667,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
int enrolmentId = 0;
ActivityStatus activityStatus = null;
List<Integer> largeResponseIDs = new ArrayList<>();
while (rs.next()) {
if (enrolmentId == 0) {
@ -501,17 +700,35 @@ public class GenericOperationDAOImpl implements OperationDAO {
activity.setActivityStatus(activityStatusList);
} else {
if (rs.getInt("UPDATED_TIMESTAMP") != 0) {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
}
}
}
}
if (!largeResponseIDs.isEmpty()) {
Map<String, Map<String, List<OperationResponse>>> largeOperationResponses = getLargeOperationResponsesInBulk(largeResponseIDs);
if (!largeOperationResponses.isEmpty()) {
List<ActivityStatus> activityStatuses = activity.getActivityStatus();
if (activityStatuses != null) {
Map<String, List<OperationResponse>> deviceOpResponseMap = largeOperationResponses.get(activity.getActivityId());
for (Map.Entry<String, List<OperationResponse>> deviceOpRes : deviceOpResponseMap.entrySet()) {
for (ActivityStatus status : activityStatuses) {
if (deviceOpRes.getKey().equalsIgnoreCase(status.getDeviceIdentifier().getId())) {
status.getResponses().addAll(deviceOpRes.getValue());
}
}
}
}
}
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while getting the operation details from " +
"the database.", e);
} catch (ClassNotFoundException e) {
throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e);
} catch (IOException e) {
throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e);
"the database. " + e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
@ -520,11 +737,11 @@ public class GenericOperationDAOImpl implements OperationDAO {
@Override
public List<Activity> getFilteredActivities(String operationCode, int limit, int offset)
throws OperationManagementDAOException{
throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<Activity> activities = new ArrayList<>();
try{
try {
Connection conn = OperationManagementDAOFactory.getConnection();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String sql = "SELECT " +
@ -539,8 +756,9 @@ public class GenericOperationDAOImpl implements OperationDAO {
" opr.DEVICE_IDENTIFICATION, " +
" opr.DEVICE_TYPE, " +
" ops.RECEIVED_TIMESTAMP, " +
" ops.ID OP_RES_ID, " +
" ops.ID AS OP_RES_ID, " +
" ops.OPERATION_RESPONSE, " +
" ops.IS_LARGE_RESPONSE, " +
" opr.INITIATED_BY " +
" FROM " +
" (SELECT " +
@ -551,11 +769,11 @@ public class GenericOperationDAOImpl implements OperationDAO {
" opm.OPERATION_ID, " +
" op.OPERATION_CODE, " +
" op.INITIATED_BY, " +
" op.TYPE OPERATION_TYPE, " +
" op.TYPE AS OPERATION_TYPE, " +
" opm.STATUS, " +
" en.DEVICE_ID, " +
" de.DEVICE_IDENTIFICATION, " +
" dt.NAME DEVICE_TYPE, " +
" dt.NAME AS DEVICE_TYPE, " +
" de.TENANT_ID " +
" FROM" +
" DM_ENROLMENT_OP_MAPPING opm " +
@ -588,6 +806,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
int responseId = 0;
Activity activity = null;
ActivityStatus activityStatus = null;
List<Integer> largeResponseIDs = new ArrayList<>();
while (rs.next()) {
if (operationId != rs.getInt("OPERATION_ID")) {
@ -618,8 +837,12 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
statusList.add(activityStatus);
@ -648,8 +871,12 @@ public class GenericOperationDAOImpl implements OperationDAO {
rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString());
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
activity.getActivityStatus().add(activityStatus);
@ -659,19 +886,22 @@ public class GenericOperationDAOImpl implements OperationDAO {
if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) {
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
}
}
}
}
if (!largeResponseIDs.isEmpty()) {
populateLargeOperationResponses(activities, largeResponseIDs);
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while getting the operation details from " +
"the database.", e);
} catch (ClassNotFoundException e) {
throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e);
} catch (IOException e) {
throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e);
"the database. " + e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
@ -680,7 +910,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
@Override
public int getTotalCountOfFilteredActivities(String operationCode)throws OperationManagementDAOException {
public int getTotalCountOfFilteredActivities(String operationCode) throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
try {
@ -699,7 +929,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
} catch (SQLException e) {
throw new OperationManagementDAOException(
"Error occurred while getting the activity count from " + "the database.", e);
"Error occurred while getting the activity count from the database. " + e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
@ -728,8 +958,9 @@ public class GenericOperationDAOImpl implements OperationDAO {
" opr.DEVICE_IDENTIFICATION, " +
" opr.DEVICE_TYPE, " +
" ops.RECEIVED_TIMESTAMP, " +
" ops.ID OP_RES_ID, " +
" ops.ID AS OP_RES_ID, " +
" ops.OPERATION_RESPONSE , " +
" ops.IS_LARGE_RESPONSE , " +
" opr.INITIATED_BY " +
" FROM " +
" (SELECT " +
@ -740,11 +971,11 @@ public class GenericOperationDAOImpl implements OperationDAO {
" opm.OPERATION_ID, " +
" op.OPERATION_CODE, " +
" op.INITIATED_BY, " +
" op.TYPE OPERATION_TYPE, " +
" op.TYPE AS OPERATION_TYPE, " +
" opm.STATUS, " +
" en.DEVICE_ID, " +
" de.DEVICE_IDENTIFICATION, " +
" dt.NAME DEVICE_TYPE, " +
" dt.NAME AS DEVICE_TYPE, " +
" de.TENANT_ID " +
" FROM" +
" DM_ENROLMENT_OP_MAPPING opm " +
@ -780,6 +1011,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
int responseId = 0;
Activity activity = null;
ActivityStatus activityStatus = null;
List<Integer> largeResponseIDs = new ArrayList<>();
while (rs.next()) {
if (operationId != rs.getInt("OPERATION_ID")) {
@ -810,8 +1042,12 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
statusList.add(activityStatus);
@ -840,8 +1076,12 @@ public class GenericOperationDAOImpl implements OperationDAO {
rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString());
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
activity.getActivityStatus().add(activityStatus);
@ -851,18 +1091,21 @@ public class GenericOperationDAOImpl implements OperationDAO {
if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) {
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
}
}
}
}
if (!largeResponseIDs.isEmpty()) {
populateLargeOperationResponses(activities, largeResponseIDs);
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while getting the operation details from " +
"the database.", e);
} catch (ClassNotFoundException e) {
throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e);
} catch (IOException e) {
throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e);
"the database. " + e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
@ -871,13 +1114,13 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
@Override
public List<Activity> getActivitiesUpdatedAfter(long timestamp, int limit,
int offset) throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<Activity> activities = new ArrayList<>();
List<Integer> largeResponseIDs = new ArrayList<>();
try {
Connection conn = OperationManagementDAOFactory.getConnection();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
@ -893,7 +1136,8 @@ public class GenericOperationDAOImpl implements OperationDAO {
" opr.DEVICE_IDENTIFICATION, " +
" opr.DEVICE_TYPE, " +
" ops.RECEIVED_TIMESTAMP, " +
" ops.ID OP_RES_ID, " +
" ops.IS_LARGE_RESPONSE, " +
" ops.ID AS OP_RES_ID, " +
" ops.OPERATION_RESPONSE " +
" FROM " +
" (SELECT " +
@ -903,11 +1147,11 @@ public class GenericOperationDAOImpl implements OperationDAO {
" opm.UPDATED_TIMESTAMP, " +
" opm.OPERATION_ID, " +
" op.OPERATION_CODE, " +
" op.TYPE OPERATION_TYPE, " +
" op.TYPE AS OPERATION_TYPE, " +
" opm.STATUS, " +
" en.DEVICE_ID, " +
" de.DEVICE_IDENTIFICATION, " +
" dt.NAME DEVICE_TYPE, " +
" dt.NAME AS DEVICE_TYPE, " +
" de.TENANT_ID " +
" FROM" +
" DM_ENROLMENT_OP_MAPPING opm " +
@ -970,8 +1214,12 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
statusList.add(activityStatus);
@ -1000,8 +1248,12 @@ public class GenericOperationDAOImpl implements OperationDAO {
rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString());
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
activity.getActivityStatus().add(activityStatus);
@ -1011,18 +1263,21 @@ public class GenericOperationDAOImpl implements OperationDAO {
if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) {
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
}
}
}
}
if (!largeResponseIDs.isEmpty()) {
populateLargeOperationResponses(activities, largeResponseIDs);
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while getting the operation details from " +
"the database.", e);
} catch (ClassNotFoundException e) {
throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e);
} catch (IOException e) {
throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e);
"the database. " + e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
@ -1035,9 +1290,8 @@ public class GenericOperationDAOImpl implements OperationDAO {
ResultSet rs = null;
try {
Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "SELECT COUNT(*) AS COUNT FROM DM_ENROLMENT_OP_MAPPING m \n"
+ "INNER JOIN DM_ENROLMENT d ON m.ENROLMENT_ID = d.ID \n"
+ "WHERE m.UPDATED_TIMESTAMP > ? AND d.TENANT_ID = ?";
String sql = "SELECT COUNT(*) AS COUNT FROM DM_ENROLMENT_OP_MAPPING WHERE " +
"UPDATED_TIMESTAMP > ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setLong(1, timestamp);
stmt.setInt(2, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
@ -1047,7 +1301,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
} catch (SQLException e) {
throw new OperationManagementDAOException(
"Error occurred while getting the activity count from " + "the database.", e);
"Error occurred while getting the activity count from the database. " + e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
@ -1060,17 +1314,13 @@ public class GenericOperationDAOImpl implements OperationDAO {
ResultSet rs = null;
try {
Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "SELECT \n" +
" COUNT(*) AS COUNT\n" +
"FROM\n" +
" DM_ENROLMENT_OP_MAPPING AS m\n" +
" INNER JOIN\n" +
" DM_ENROLMENT AS d ON m.ENROLMENT_ID = d.ID\n" +
" INNER JOIN \n" +
" DM_OPERATION dp ON dp.ID = m.OPERATION_ID \n" +
"WHERE\n" +
" m.UPDATED_TIMESTAMP > ? AND dp.INITIATED_BY = ?\n" +
" AND d.TENANT_ID = ?";
String sql = "SELECT COUNT(*) AS COUNT " +
"FROM DM_ENROLMENT_OP_MAPPING AS m " +
" INNER JOIN " +
" DM_OPERATION dp ON dp.ID = m.OPERATION_ID " +
"WHERE m.UPDATED_TIMESTAMP > ?" +
" AND dp.INITIATED_BY = ?" +
" AND m.TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setLong(1, timestamp);
stmt.setString(2, user);
@ -1081,7 +1331,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while getting the activity count from " +
"the database.", e);
"the database. " + e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
@ -1095,7 +1345,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
Operation operation = null;
try {
Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE FROM " +
String sql = "SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, INITIATED_BY FROM " +
"DM_OPERATION WHERE id = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);
@ -1112,6 +1362,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
}
operation.setCode(rs.getString("OPERATION_CODE"));
operation.setInitiatedBy(rs.getString("INITIATED_BY"));
}
} catch (SQLException e) {
@ -1270,8 +1521,8 @@ public class GenericOperationDAOImpl implements OperationDAO {
List<Operation> operations = new ArrayList<>();
try {
Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " +
"OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " +
String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " +
"o.OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " +
"INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " +
"WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID " +
"ORDER BY o.CREATED_TIMESTAMP DESC, o.ID DESC";
@ -1312,8 +1563,8 @@ public class GenericOperationDAOImpl implements OperationDAO {
List<Operation> operations = new ArrayList<Operation>();
try {
Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " +
"OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " +
String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " +
"o.OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " +
"INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " +
"WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID " +
"ORDER BY o.CREATED_TIMESTAMP DESC, o.ID DESC LIMIT ?,?";
@ -1364,7 +1615,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
operationCount = rs.getInt("OPERATION_COUNT");
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while getting the operations count for enrolment : "
throw new OperationManagementDAOException("Error occurred while getting the operations count for enrolment: "
+ enrolmentId, e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
@ -1378,8 +1629,8 @@ public class GenericOperationDAOImpl implements OperationDAO {
ResultSet rs = null;
try {
Connection connection = OperationManagementDAOFactory.getConnection();
stmt = connection.prepareStatement("SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " +
"OPERATION_CODE, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " +
stmt = connection.prepareStatement("SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " +
"o.OPERATION_CODE, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " +
"INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " +
"WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID " +
"ORDER BY om.UPDATED_TIMESTAMP ASC, om.ID ASC LIMIT 1");
@ -1406,19 +1657,19 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
return operation;
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while adding operation metadata", e);
throw new OperationManagementDAOException("Error occurred while getting operation metadata. " +
e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
}
public List<? extends Operation> getOperationsByDeviceStatusAndType(
int enrolmentId, Operation.Status status, Operation.Type type) throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
Operation operation;
List<Operation> operations = new ArrayList<Operation>();
List<Operation> operations = new ArrayList<>();
try {
Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, OPERATION_CODE, om.ID AS OM_MAPPING_ID, " +
@ -1499,7 +1750,8 @@ public class GenericOperationDAOImpl implements OperationDAO {
operationMappings.add(operationMapping);
}
} catch (SQLException e) {
throw new OperationManagementDAOException("SQL error while getting operation mappings from database. ", e);
throw new OperationManagementDAOException("SQL error while getting operation mappings from database. " +
e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}

@ -18,6 +18,7 @@
*/
package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping;
@ -39,17 +40,18 @@ import java.util.Map;
public class OperationMappingDAOImpl implements OperationMappingDAO {
@Override
public void addOperationMapping(int operationId, int enrollmentId, boolean isScheduled) throws
public void addOperationMapping(Operation operation, Integer deviceId, boolean isScheduled, Device device, Integer tenantId) throws
OperationManagementDAOException {
PreparedStatement stmt = null;
try {
long time = System.currentTimeMillis() / 1000;
Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID, OPERATION_ID, STATUS, " +
"PUSH_NOTIFICATION_STATUS, CREATED_TIMESTAMP, UPDATED_TIMESTAMP) VALUES (?, ?, ?, ?, ?, ?)";
"PUSH_NOTIFICATION_STATUS, CREATED_TIMESTAMP, UPDATED_TIMESTAMP, OPERATION_CODE, INITIATED_BY, " +
"TYPE, DEVICE_TYPE, DEVICE_ID, DEVICE_IDENTIFICATION, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, enrollmentId);
stmt.setInt(2, operationId);
stmt.setInt(1, deviceId);
stmt.setInt(2, operation.getId());
stmt.setString(3, Operation.Status.PENDING.toString());
if (isScheduled) {
stmt.setString(4, Operation.PushNotificationStatus.SCHEDULED.toString());
@ -58,27 +60,36 @@ public class OperationMappingDAOImpl implements OperationMappingDAO {
}
stmt.setLong(5, time);
stmt.setLong(6, time);
stmt.setString(7, operation.getCode());
stmt.setString(8, operation.getInitiatedBy());
stmt.setString(9, operation.getType().toString());
stmt.setString(10, device.getType());
stmt.setInt(11, device.getId());
stmt.setString(12, device.getDeviceIdentifier());
stmt.setInt(13, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while persisting device operation mappings", e);
throw new OperationManagementDAOException("Error occurred while persisting device operation mappings. " +
e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public void addOperationMapping(int operationId, List<Integer> enrollmentIds, boolean isScheduled) throws
public void addOperationMapping(Operation operation, List<Device> devices, boolean isScheduled, Integer tenantId) throws
OperationManagementDAOException {
PreparedStatement stmt = null;
try {
long time = System.currentTimeMillis() / 1000;
Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID, OPERATION_ID, STATUS, " +
"PUSH_NOTIFICATION_STATUS, CREATED_TIMESTAMP, UPDATED_TIMESTAMP) VALUES (?, ?, ?, ?, ?, ?)";
"PUSH_NOTIFICATION_STATUS, CREATED_TIMESTAMP, UPDATED_TIMESTAMP, OPERATION_CODE, INITIATED_BY, " +
"TYPE, DEVICE_TYPE, DEVICE_ID, DEVICE_IDENTIFICATION, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql);
for (int enrollmentId : enrollmentIds) {
stmt.setInt(1, enrollmentId);
stmt.setInt(2, operationId);
for (Device device : devices) {
stmt.setInt(1, device.getEnrolmentInfo().getId());
stmt.setInt(2, operation.getId());
stmt.setString(3, Operation.Status.PENDING.toString());
if (isScheduled) {
stmt.setString(4, Operation.PushNotificationStatus.SCHEDULED.toString());
@ -87,11 +98,19 @@ public class OperationMappingDAOImpl implements OperationMappingDAO {
}
stmt.setLong(5, time);
stmt.setLong(6, time);
stmt.setString(7, operation.getCode());
stmt.setString(8, operation.getInitiatedBy());
stmt.setString(9, operation.getType().toString());
stmt.setString(10, device.getType());
stmt.setInt(11, device.getId());
stmt.setString(12, device.getDeviceIdentifier());
stmt.setInt(13, tenantId);
stmt.addBatch();
}
stmt.executeBatch();
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while persisting device operation mappings", e);
throw new OperationManagementDAOException("Error occurred while persisting device operation mappings. " +
e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, null);
}
@ -109,14 +128,17 @@ public class OperationMappingDAOImpl implements OperationMappingDAO {
stmt.setInt(2, operationId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while persisting device operation mappings", e);
throw new OperationManagementDAOException("Error occurred while persisting device operation mappings. " +
e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public void updateOperationMapping(int operationId, Integer deviceId, Operation.PushNotificationStatus pushNotificationStatus) throws OperationManagementDAOException {
public void updateOperationMapping(int operationId, Integer deviceId,
Operation.PushNotificationStatus pushNotificationStatus)
throws OperationManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = OperationManagementDAOFactory.getConnection();
@ -128,7 +150,8 @@ public class OperationMappingDAOImpl implements OperationMappingDAO {
stmt.setInt(3, operationId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while updating device operation mappings", e);
throw new OperationManagementDAOException("Error occurred while updating device operation mappings. " +
e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, null);
}
@ -161,7 +184,7 @@ public class OperationMappingDAOImpl implements OperationMappingDAO {
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while updating device operation mappings as " +
"batch ", e);
"batch . " + e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, null);
}
@ -172,7 +195,7 @@ public class OperationMappingDAOImpl implements OperationMappingDAO {
long maxDuration, int deviceTypeId) throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<OperationEnrolmentMapping> enrolmentOperationMappingList = null;
List<OperationEnrolmentMapping> enrolmentOperationMappingList;
try {
Connection conn = OperationManagementDAOFactory.getConnection();
//We are specifically looking for operation mappings in 'Pending' & 'Repeated' states. Further we want

@ -61,7 +61,7 @@ public class PolicyOperationDAOImpl extends GenericOperationDAOImpl {
oos = new ObjectOutputStream(bao);
oos.writeObject(operation);
stmt.setObject(6, operation);
stmt.setBytes(6, bao.toByteArray());
stmt.setBoolean(7, operation.isEnabled());
stmt.executeUpdate();

@ -18,19 +18,19 @@
package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation;
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.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.ActivityStatus;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationResponse;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.GenericOperationDAOImpl;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@ -43,6 +43,8 @@ import java.util.List;
*/
public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
private static final Log log = LogFactory.getLog(MySQLOperationDAOImpl.class);
@Override
public List<Activity> getActivityList(List<Integer> activityIds) throws OperationManagementDAOException {
PreparedStatement stmt = null;
@ -53,23 +55,34 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
try {
Connection conn = OperationManagementDAOFactory.getConnection();
String sql1 = "SELECT eom.ENROLMENT_ID, eom.OPERATION_ID, eom.ID AS EOM_MAPPING_ID, "
+ "dor.ID AS OP_RES_ID, de.DEVICE_ID, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID, "
+ "dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, "
+ "eom.UPDATED_TIMESTAMP, op.OPERATION_CODE, op.TYPE AS OPERATION_TYPE, "
+ "dor.OPERATION_RESPONSE, dor.RECEIVED_TIMESTAMP, op.INITIATED_BY FROM "
+ "DM_ENROLMENT_OP_MAPPING eom INNER JOIN DM_OPERATION op "
+ "ON op.ID=eom.OPERATION_ID INNER JOIN DM_ENROLMENT de "
+ "ON de.ID=eom.ENROLMENT_ID INNER JOIN DM_DEVICE d ON d.ID=de.DEVICE_ID \n"
+ "INNER JOIN DM_DEVICE_TYPE dt ON dt.ID=d.DEVICE_TYPE_ID\n"
+ "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE dor ON dor.ENROLMENT_ID=de.id \n"
+ "AND dor.OPERATION_ID = eom.OPERATION_ID WHERE eom.OPERATION_ID " + "IN (";
String sql1 = "SELECT " +
" eom.ENROLMENT_ID," +
" eom.CREATED_TIMESTAMP," +
" eom.UPDATED_TIMESTAMP," +
" eom.OPERATION_ID," +
" eom.OPERATION_CODE," +
" eom.INITIATED_BY," +
" eom.TYPE," +
" eom.STATUS," +
" eom.DEVICE_ID," +
" eom.DEVICE_IDENTIFICATION," +
" eom.DEVICE_TYPE," +
" opr.ID AS OP_RES_ID," +
" opr.RECEIVED_TIMESTAMP," +
" opr.OPERATION_RESPONSE," +
" opr.IS_LARGE_RESPONSE " +
"FROM " +
" DM_ENROLMENT_OP_MAPPING eom " +
" LEFT JOIN " +
" DM_DEVICE_OPERATION_RESPONSE opr ON opr.EN_OP_MAP_ID = eom.ID " +
"WHERE " +
" eom.OPERATION_ID IN (";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < activityIds.size(); i++) {
builder.append("?,");
}
sql1 += builder.deleteCharAt(builder.length() - 1).toString() + ") AND de.TENANT_ID = ?";
sql1 += builder.deleteCharAt(builder.length() - 1).toString() + ") AND eom.TENANT_ID = ?";
stmt = conn.prepareStatement(sql1);
int i;
for (i = 0; i < activityIds.size(); i++) {
@ -83,6 +96,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
int enrolmentId = 0;
int responseId = 0;
ActivityStatus activityStatus = new ActivityStatus();
List<Integer> largeResponseIDs = new ArrayList<>();
while (rs.next()) {
activity = new Activity();
@ -94,7 +108,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
operationId = rs.getInt("OPERATION_ID");
enrolmentId = rs.getInt("ENROLMENT_ID");
activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE")));
activity.setType(Activity.Type.valueOf(rs.getString("TYPE")));
activity.setCreatedTimeStamp(
new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString());
activity.setCode(rs.getString("OPERATION_CODE"));
@ -102,7 +116,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION"));
deviceIdentifier.setType(rs.getString("DEVICE_TYPE_NAME"));
deviceIdentifier.setType(rs.getString("DEVICE_TYPE"));
activityStatus.setDeviceIdentifier(deviceIdentifier);
@ -115,8 +129,12 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
statusList.add(activityStatus);
@ -127,7 +145,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
if (operationId == rs.getInt("OPERATION_ID") && enrolmentId != rs.getInt("ENROLMENT_ID")) {
activityStatus = new ActivityStatus();
activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE")));
activity.setType(Activity.Type.valueOf(rs.getString("TYPE")));
activity.setCreatedTimeStamp(
new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString());
activity.setCode(rs.getString("OPERATION_CODE"));
@ -135,7 +153,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION"));
deviceIdentifier.setType(rs.getString("DEVICE_TYPE_NAME"));
deviceIdentifier.setType(rs.getString("DEVICE_TYPE"));
activityStatus.setDeviceIdentifier(deviceIdentifier);
activityStatus.setStatus(ActivityStatus.Status.valueOf(rs.getString("STATUS")));
@ -146,8 +164,12 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
new java.util.Date(rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString());
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
activity.getActivityStatus().add(activityStatus);
@ -157,31 +179,30 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID") && rs.getTimestamp(
"RECEIVED_TIMESTAMP") != null) {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
}
}
}
if(!largeResponseIDs.isEmpty()) {
populateLargeOperationResponses(activities, largeResponseIDs);
}
} catch (SQLException e) {
throw new OperationManagementDAOException(
"Error occurred while getting the operation details from " + "the database.", e);
} catch (ClassNotFoundException e) {
throw new OperationManagementDAOException(
"Error occurred while converting the operation response to string.", e);
} catch (IOException e) {
throw new OperationManagementDAOException(
"IO exception occurred while converting the operations responses.", e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
return activities;
}
@Override
public List<Activity> getActivitiesUpdatedAfter(long timestamp, int limit,
int offset) throws OperationManagementDAOException {
int offset)
throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<Activity> activities = new ArrayList<>();
@ -189,51 +210,32 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
Connection conn = OperationManagementDAOFactory.getConnection();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String sql = "SELECT " +
" opr.ENROLMENT_ID, " +
" opr.CREATED_TIMESTAMP, " +
" opr.UPDATED_TIMESTAMP, " +
" opr.OPERATION_ID, " +
" opr.OPERATION_CODE, " +
" opr.INITIATED_BY, " +
" opr.OPERATION_TYPE, " +
" opr.STATUS, " +
" opr.DEVICE_ID, " +
" opr.DEVICE_IDENTIFICATION, " +
" opr.DEVICE_TYPE, " +
" ops.RECEIVED_TIMESTAMP, " +
" ops.ID OP_RES_ID, " +
" ops.OPERATION_RESPONSE " +
" FROM " +
" (SELECT " +
" opm.ID MAPPING_ID, " +
" opm.ENROLMENT_ID, " +
" opm.CREATED_TIMESTAMP, " +
" opm.UPDATED_TIMESTAMP, " +
" opm.OPERATION_ID, " +
" op.OPERATION_CODE, " +
" op.INITIATED_BY, " +
" op.TYPE OPERATION_TYPE, " +
" opm.STATUS, " +
" en.DEVICE_ID, " +
" de.DEVICE_IDENTIFICATION, " +
" dt.NAME DEVICE_TYPE, " +
" de.TENANT_ID " +
" FROM" +
" DM_ENROLMENT_OP_MAPPING opm FORCE INDEX (IDX_ENROLMENT_OP_MAPPING) " +
" INNER JOIN DM_OPERATION op ON opm.OPERATION_ID = op.ID " +
" INNER JOIN DM_ENROLMENT en ON opm.ENROLMENT_ID = en.ID " +
" INNER JOIN DM_DEVICE de ON en.DEVICE_ID = de.ID " +
" INNER JOIN DM_DEVICE_TYPE dt ON dt.ID = de.DEVICE_TYPE_ID " +
" WHERE" +
" opm.UPDATED_TIMESTAMP > ? " +
" AND de.TENANT_ID = ? " +
" ORDER BY opm.UPDATED_TIMESTAMP " +
" LIMIT ? OFFSET ?) opr " +
" LEFT JOIN DM_DEVICE_OPERATION_RESPONSE ops ON opr.MAPPING_ID = ops.EN_OP_MAP_ID " +
" WHERE " +
" opr.UPDATED_TIMESTAMP > ? " +
" AND opr.TENANT_ID = ? ";
" eom.ENROLMENT_ID," +
" eom.CREATED_TIMESTAMP," +
" eom.UPDATED_TIMESTAMP," +
" eom.OPERATION_ID," +
" eom.OPERATION_CODE," +
" eom.INITIATED_BY," +
" eom.TYPE," +
" eom.STATUS," +
" eom.DEVICE_ID," +
" eom.DEVICE_IDENTIFICATION," +
" eom.DEVICE_TYPE," +
" opr.ID AS OP_RES_ID," +
" opr.RECEIVED_TIMESTAMP," +
" opr.OPERATION_RESPONSE," +
" opr.IS_LARGE_RESPONSE " +
"FROM " +
" DM_ENROLMENT_OP_MAPPING eom FORCE INDEX (IDX_ENROLMENT_OP_MAPPING) " +
" LEFT JOIN " +
" DM_DEVICE_OPERATION_RESPONSE opr ON opr.EN_OP_MAP_ID = eom.ID " +
"WHERE " +
" eom.UPDATED_TIMESTAMP > ? " +
" AND eom.TENANT_ID = ? " +
"ORDER BY eom.UPDATED_TIMESTAMP " +
"LIMIT ? OFFSET ?";
stmt = conn.prepareStatement(sql);
@ -241,8 +243,6 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
stmt.setInt(2, tenantId);
stmt.setInt(3, limit);
stmt.setInt(4, offset);
stmt.setLong(5, timestamp);
stmt.setInt(6, tenantId);
rs = stmt.executeQuery();
@ -251,6 +251,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
int responseId = 0;
Activity activity = null;
ActivityStatus activityStatus = null;
List<Integer> largeResponseIDs = new ArrayList<>();
while (rs.next()) {
if (operationId != rs.getInt("OPERATION_ID")) {
@ -262,7 +263,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
operationId = rs.getInt("OPERATION_ID");
enrolmentId = rs.getInt("ENROLMENT_ID");
activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE")));
activity.setType(Activity.Type.valueOf(rs.getString("TYPE")));
activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString());
activity.setCode(rs.getString("OPERATION_CODE"));
activity.setInitiatedBy(rs.getString("INITIATED_BY"));
@ -281,8 +282,12 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
statusList.add(activityStatus);
@ -294,7 +299,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
if (operationId == rs.getInt("OPERATION_ID") && enrolmentId != rs.getInt("ENROLMENT_ID")) {
activityStatus = new ActivityStatus();
activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE")));
activity.setType(Activity.Type.valueOf(rs.getString("TYPE")));
activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString());
activity.setCode(rs.getString("OPERATION_CODE"));
activity.setInitiatedBy(rs.getString("INITIATED_BY"));
@ -312,8 +317,12 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString());
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
activity.getActivityStatus().add(activityStatus);
@ -323,18 +332,21 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) {
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
}
}
}
}
if(!largeResponseIDs.isEmpty()) {
populateLargeOperationResponses(activities, largeResponseIDs);
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while getting the operation details from " +
"the database.", e);
} catch (ClassNotFoundException e) {
throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e);
} catch (IOException e) {
throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
@ -347,66 +359,55 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
PreparedStatement stmt = null;
ResultSet rs = null;
List<Activity> activities = new ArrayList<>();
List<Integer> largeResponseIDs = new ArrayList<>();
try {
Connection conn = OperationManagementDAOFactory.getConnection();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String sql = "SELECT " +
" opr.ENROLMENT_ID, " +
" opr.CREATED_TIMESTAMP, " +
" opr.UPDATED_TIMESTAMP, " +
" opr.OPERATION_ID, " +
" opr.OPERATION_CODE, " +
" opr.INITIATED_BY, " +
" opr.OPERATION_TYPE, " +
" opr.STATUS, " +
" opr.DEVICE_ID, " +
" opr.DEVICE_IDENTIFICATION, " +
" opr.DEVICE_TYPE, " +
" ops.RECEIVED_TIMESTAMP, " +
" ops.ID OP_RES_ID, " +
" ops.OPERATION_RESPONSE " +
" FROM " +
" (SELECT " +
" opm.ID MAPPING_ID, " +
" opm.ENROLMENT_ID, " +
" opm.CREATED_TIMESTAMP, " +
" opm.UPDATED_TIMESTAMP, " +
" opm.OPERATION_ID, " +
" op.OPERATION_CODE, " +
" op.INITIATED_BY, " +
" op.TYPE OPERATION_TYPE, " +
" opm.STATUS, " +
" en.DEVICE_ID, " +
" de.DEVICE_IDENTIFICATION, " +
" dt.NAME DEVICE_TYPE, " +
" de.TENANT_ID " +
" FROM" +
" DM_ENROLMENT_OP_MAPPING opm FORCE INDEX (IDX_ENROLMENT_OP_MAPPING) " +
" INNER JOIN DM_OPERATION op ON opm.OPERATION_ID = op.ID " +
" INNER JOIN DM_ENROLMENT en ON opm.ENROLMENT_ID = en.ID " +
" INNER JOIN DM_DEVICE de ON en.DEVICE_ID = de.ID " +
" INNER JOIN DM_DEVICE_TYPE dt ON dt.ID = de.DEVICE_TYPE_ID " +
" WHERE" +
" opm.UPDATED_TIMESTAMP > ? AND op.INITIATED_BY = ?" +
" AND de.TENANT_ID = ? " +
" ORDER BY opm.UPDATED_TIMESTAMP " +
" LIMIT ? OFFSET ?) opr " +
" LEFT JOIN DM_DEVICE_OPERATION_RESPONSE ops ON opr.MAPPING_ID = ops.EN_OP_MAP_ID " +
" WHERE " +
" opr.UPDATED_TIMESTAMP > ? AND opr.INITIATED_BY = ? " +
" AND opr.TENANT_ID = ? ";
" eom.ENROLMENT_ID," +
" eom.CREATED_TIMESTAMP," +
" eom.UPDATED_TIMESTAMP," +
" eom.OPERATION_ID," +
" eom.OPERATION_CODE," +
" eom.INITIATED_BY," +
" eom.TYPE," +
" eom.STATUS," +
" eom.DEVICE_ID," +
" eom.DEVICE_IDENTIFICATION," +
" eom.DEVICE_TYPE," +
" opr.ID AS OP_RES_ID," +
" opr.RECEIVED_TIMESTAMP," +
" opr.OPERATION_RESPONSE," +
" opr.IS_LARGE_RESPONSE " +
"FROM " +
" DM_ENROLMENT_OP_MAPPING eom FORCE INDEX (IDX_ENROLMENT_OP_MAPPING) " +
" LEFT JOIN " +
" DM_DEVICE_OPERATION_RESPONSE opr ON opr.EN_OP_MAP_ID = eom.ID " +
"WHERE " +
" eom.UPDATED_TIMESTAMP > ? " +
" AND eom.TENANT_ID = ? " +
" AND eom.INITIATED_BY = ? " +
"ORDER BY eom.UPDATED_TIMESTAMP " +
"LIMIT ? OFFSET ?";
stmt = conn.prepareStatement(sql);
stmt.setLong(1, timestamp);
stmt.setString(2, user);
stmt.setInt(3, tenantId);
stmt.setInt(2, tenantId);
stmt.setString(3, user);
stmt.setInt(4, limit);
stmt.setInt(5, offset);
stmt.setLong(6, timestamp);
stmt.setString(7, user);
stmt.setInt(8, tenantId);
// stmt.setLong(1, timestamp);
// stmt.setString(2, user);
// stmt.setInt(3, tenantId);
// stmt.setInt(4, limit);
// stmt.setInt(5, offset);
// stmt.setLong(6, timestamp);
// stmt.setString(7, user);
// stmt.setInt(8, tenantId);
rs = stmt.executeQuery();
@ -426,7 +427,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
operationId = rs.getInt("OPERATION_ID");
enrolmentId = rs.getInt("ENROLMENT_ID");
activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE")));
activity.setType(Activity.Type.valueOf(rs.getString("TYPE")));
activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString());
activity.setCode(rs.getString("OPERATION_CODE"));
activity.setInitiatedBy(rs.getString("INITIATED_BY"));
@ -445,8 +446,12 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
statusList.add(activityStatus);
@ -458,7 +463,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
if (operationId == rs.getInt("OPERATION_ID") && enrolmentId != rs.getInt("ENROLMENT_ID")) {
activityStatus = new ActivityStatus();
activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE")));
activity.setType(Activity.Type.valueOf(rs.getString("TYPE")));
activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString());
activity.setCode(rs.getString("OPERATION_CODE"));
activity.setInitiatedBy(rs.getString("INITIATED_BY"));
@ -476,8 +481,12 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString());
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
activity.getActivityStatus().add(activityStatus);
@ -487,31 +496,25 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl {
if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) {
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
}
}
}
}
if(!largeResponseIDs.isEmpty()) {
populateLargeOperationResponses(activities, largeResponseIDs);
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while getting the operation details from " +
"the database.", e);
} catch (ClassNotFoundException e) {
throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e);
} catch (IOException e) {
throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
return activities;
}
private Integer[] getIntArrayOfActivityIds(List<Integer> activityIds) {
Integer[] arr = new Integer[activityIds.size()];
int x = 0;
for (Integer activityId : activityIds) {
arr[x] = activityId;
x++;
}
return arr;
}
}

@ -188,6 +188,7 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl {
PreparedStatement stmt = null;
ResultSet rs = null;
List<Activity> activities = new ArrayList<>();
List<Integer> largeResponseIDs = new ArrayList<>();
try {
Connection conn = OperationManagementDAOFactory.getConnection();
/*String sql = "SELECT opm.ENROLMENT_ID, opm.CREATED_TIMESTAMP, opm.UPDATED_TIMESTAMP, opm.OPERATION_ID,\n"
@ -224,6 +225,7 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl {
" opr.DEVICE_TYPE, " +
" ops.RECEIVED_TIMESTAMP, " +
" ops.ID OP_RES_ID, " +
" ops.IS_LARGE_RESPONSE, " +
" ops.OPERATION_RESPONSE " +
" FROM " +
" (SELECT " +
@ -301,8 +303,12 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl {
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
statusList.add(activityStatus);
@ -332,8 +338,12 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl {
new java.util.Date(rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString());
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
activity.getActivityStatus().add(activityStatus);
@ -343,20 +353,21 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl {
if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) {
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
}
}
}
}
if(!largeResponseIDs.isEmpty()) {
populateLargeOperationResponses(activities, largeResponseIDs);
}
} catch (SQLException e) {
throw new OperationManagementDAOException(
"Error occurred while getting the operation details from " + "the database.", e);
} catch (ClassNotFoundException e) {
throw new OperationManagementDAOException(
"Error occurred while converting the operation response to string.", e);
} catch (IOException e) {
throw new OperationManagementDAOException(
"IO exception occurred while converting the operations responses.", e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}

@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.OperationResponseMeta;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil;
@ -30,7 +31,9 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
@ -126,4 +129,63 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl {
}
return operations;
}
@Override
public OperationResponseMeta addOperationResponse(int enrolmentId, org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation,
String deviceId) throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
boolean isLargeResponse = false;
try {
Connection connection = OperationManagementDAOFactory.getConnection();
stmt = connection.prepareStatement("SELECT ID FROM DM_ENROLMENT_OP_MAPPING WHERE ENROLMENT_ID = ? " +
"AND OPERATION_ID = ?");
stmt.setInt(1, enrolmentId);
stmt.setInt(2, operation.getId());
rs = stmt.executeQuery();
int enPrimaryId = 0;
if (rs.next()) {
enPrimaryId = rs.getInt("ID");
}
stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID, ENROLMENT_ID, " +
"EN_OP_MAP_ID, OPERATION_RESPONSE, IS_LARGE_RESPONSE, RECEIVED_TIMESTAMP) VALUES(?, ?, ?, ?, ?, ?)",
new String[]{"id"});
stmt.setInt(1, operation.getId());
stmt.setInt(2, enrolmentId);
stmt.setInt(3, enPrimaryId);
if (operation.getOperationResponse() != null && operation.getOperationResponse().length() >= 1000) {
isLargeResponse = true;
stmt.setBytes(4, null);
} else {
stmt.setString(4, operation.getOperationResponse());
}
stmt.setBoolean(5, isLargeResponse);
Timestamp receivedTimestamp = new Timestamp(new Date().getTime());
stmt.setTimestamp(6, receivedTimestamp);
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
int opResID = -1;
if (rs.next()) {
opResID = rs.getInt(1);
}
OperationResponseMeta responseMeta = new OperationResponseMeta();
responseMeta.setId(opResID);
responseMeta.setEnrolmentId(enrolmentId);
responseMeta.setOperationMappingId(enPrimaryId);
responseMeta.setReceivedTimestamp(receivedTimestamp);
responseMeta.setLargeResponse(isLargeResponse);
return responseMeta;
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while inserting operation response. " +
e.getMessage(), e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
}
}

@ -166,6 +166,7 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl {
PreparedStatement stmt = null;
ResultSet rs = null;
List<Activity> activities = new ArrayList<>();
List<Integer> largeResponseIDs = new ArrayList<>();
try {
Connection conn = OperationManagementDAOFactory.getConnection();
/*String sql = "SELECT opm.ENROLMENT_ID, opm.CREATED_TIMESTAMP, opm.UPDATED_TIMESTAMP, opm.OPERATION_ID,\n"
@ -201,6 +202,7 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl {
" opr.DEVICE_TYPE, " +
" ops.RECEIVED_TIMESTAMP, " +
" ops.ID OP_RES_ID, " +
" ops.IS_LARGE_RESPONSE, " +
" ops.OPERATION_RESPONSE " +
" FROM " +
" (SELECT " +
@ -277,8 +279,12 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl {
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
statusList.add(activityStatus);
@ -308,8 +314,12 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl {
new java.util.Date(rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString());
}
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
operationResponses.add(OperationDAOUtil.getOperationResponse(rs));
}
}
activityStatus.setResponses(operationResponses);
activity.getActivityStatus().add(activityStatus);
@ -319,20 +329,21 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl {
if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) {
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs));
}
}
}
}
if(!largeResponseIDs.isEmpty()) {
populateLargeOperationResponses(activities, largeResponseIDs);
}
} catch (SQLException e) {
throw new OperationManagementDAOException(
"Error occurred while getting the operation details from " + "the database.", e);
} catch (ClassNotFoundException e) {
throw new OperationManagementDAOException(
"Error occurred while converting the operation response to string.", e);
} catch (IOException e) {
throw new OperationManagementDAOException(
"IO exception occurred while converting the operations responses.", e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}

@ -123,8 +123,8 @@ public class OperationDAOUtil {
return operation;
}
public static OperationResponse getOperationResponse(ResultSet rs) throws
ClassNotFoundException, IOException, SQLException {
public static OperationResponse getLargeOperationResponse(ResultSet rs) throws
ClassNotFoundException, IOException, SQLException {
OperationResponse response = new OperationResponse();
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
response.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
@ -158,6 +158,18 @@ public class OperationDAOUtil {
return response;
}
public static OperationResponse getOperationResponse(ResultSet rs) throws SQLException {
OperationResponse response = new OperationResponse();
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
response.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
}
if (rs.getString("OPERATION_RESPONSE") != null) {
response.setResponse(rs.getString("OPERATION_RESPONSE"));
}
return response;
}
public static Operation.Type getType(String type) {
return Operation.Type.valueOf(type);
}

@ -89,6 +89,7 @@ import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion;
import org.wso2.carbon.device.mgt.core.geo.GeoCluster;
import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import java.sql.SQLException;
import java.util.Date;
@ -659,10 +660,7 @@ public interface DeviceManagementProviderService {
boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) throws DeviceManagementException;
boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException;
boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException;
boolean setStatus(Device device, EnrolmentInfo.Status status) throws DeviceManagementException;
boolean setStatus(String currentOwner, EnrolmentInfo.Status status) throws DeviceManagementException;
@ -672,11 +670,16 @@ public interface DeviceManagementProviderService {
Activity addOperation(String type, Operation operation,
List<DeviceIdentifier> devices) throws OperationManagementException, InvalidDeviceException;
void addTaskOperation(String deviceType, Operation operation) throws OperationManagementException;
List<? extends Operation> getOperations(DeviceIdentifier deviceId) throws OperationManagementException;
PaginationResult getOperations(DeviceIdentifier deviceId,
PaginationRequest request) throws OperationManagementException;
List<? extends Operation> getOperations(DeviceIdentifier deviceId, Operation.Status status)
throws OperationManagementException;
List<? extends Operation> getPendingOperations(
DeviceIdentifier deviceId) throws OperationManagementException;
@ -805,7 +808,7 @@ public interface DeviceManagementProviderService {
boolean bulkUpdateDeviceStatus(String deviceType, List<String> deviceList, String status) throws DeviceManagementException;
boolean updateEnrollment(String owner, List<String> deviceIdentifiers)
boolean updateEnrollment(String owner, boolean isTransfer, List<String> deviceIdentifiers)
throws DeviceManagementException, UserNotFoundException, InvalidDeviceException;
boolean addDeviceTypeVersion(DeviceTypeVersion deviceTypeVersion) throws DeviceManagementException;

@ -21,10 +21,12 @@ package org.wso2.carbon.device.mgt.core.status.task.impl;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl;
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.operation.mgt.OperationEnrolmentMapping;
@ -65,52 +67,57 @@ public class DeviceStatusMonitoringTask implements Task {
@Override
public void execute() {
List<OperationEnrolmentMapping> operationEnrolmentMappings = null;
List<OperationEnrolmentMapping> operationEnrolmentMappings;
List<EnrolmentInfo> enrolmentInfoTobeUpdated = new ArrayList<>();
List<DeviceIdentifier> identifiers = new ArrayList<>();
Map<Integer, Long> lastActivities = null;
EnrolmentInfo enrolmentInfo;
DeviceIdentifier deviceIdentifier;
Device device;
try {
operationEnrolmentMappings = this.getOperationEnrolmentMappings();
if (operationEnrolmentMappings != null && operationEnrolmentMappings.size() > 0) {
if (operationEnrolmentMappings.size() > 0) {
lastActivities = this.getLastDeviceActivities();
}
} catch (DeviceStatusTaskException e) {
log.error("Error occurred while fetching OperationEnrolment mappings of deviceType '" + deviceType + "'", e);
return;
}
for (OperationEnrolmentMapping mapping:operationEnrolmentMappings) {
for (OperationEnrolmentMapping mapping : operationEnrolmentMappings) {
long lastActivity = -1;
if (lastActivities != null && lastActivities.containsKey(mapping.getEnrolmentId())) {
lastActivity = lastActivities.get(mapping.getEnrolmentId());
}
EnrolmentInfo.Status newStatus = this.determineDeviceStatus(mapping, lastActivity);
if (newStatus != mapping.getDeviceStatus()) {
enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setId(mapping.getEnrolmentId());
enrolmentInfo.setStatus(newStatus);
enrolmentInfoTobeUpdated.add(enrolmentInfo);
deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(mapping.getDeviceId());
deviceIdentifier.setId(mapping.getDeviceType());
identifiers.add(deviceIdentifier);
device = DeviceCacheManagerImpl.getInstance().getDeviceFromCache(deviceIdentifier, mapping.getTenantId());
if (device == null) {
enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setId(mapping.getEnrolmentId());
enrolmentInfo.setStatus(newStatus);
} else {
enrolmentInfo = device.getEnrolmentInfo();
enrolmentInfo.setStatus(newStatus);
device.setEnrolmentInfo(enrolmentInfo);
DeviceCacheManagerImpl.getInstance().addDeviceToCache(deviceIdentifier, device, mapping.getTenantId());
}
enrolmentInfoTobeUpdated.add(enrolmentInfo);
}
}
if (enrolmentInfoTobeUpdated.size() > 0) {
try {
this.updateDeviceStatus(enrolmentInfoTobeUpdated);
//Remove updated entries from cache
//DeviceCacheManagerImpl.getInstance().removeDevicesFromCache(identifiers);
} catch (DeviceStatusTaskException e) {
log.error("Error occurred while updating non-responsive device-status of devices of type '" + deviceType + "'",e);
log.error("Error occurred while updating non-responsive device-status of devices of type '" + deviceType + "'", e);
}
}
}
private EnrolmentInfo.Status determineDeviceStatus(OperationEnrolmentMapping opMapping, long lastActivityTime) {
long lastPendingOpBefore = (System.currentTimeMillis()/1000) - opMapping.getCreatedTime();
long lastPendingOpBefore = (System.currentTimeMillis() / 1000) - opMapping.getCreatedTime();
EnrolmentInfo.Status newStatus = null;
if (lastPendingOpBefore >= this.deviceStatusTaskPluginConfig.getIdleTimeToMarkInactive()) {
newStatus = EnrolmentInfo.Status.INACTIVE;
@ -118,7 +125,7 @@ public class DeviceStatusMonitoringTask implements Task {
newStatus = EnrolmentInfo.Status.UNREACHABLE;
}
if (lastActivityTime != -1) {
long lastActivityBefore = (System.currentTimeMillis()/1000) - lastActivityTime;
long lastActivityBefore = (System.currentTimeMillis() / 1000) - lastActivityTime;
if (lastActivityBefore < lastPendingOpBefore) {
return opMapping.getDeviceStatus();
}
@ -127,12 +134,12 @@ public class DeviceStatusMonitoringTask implements Task {
}
private long getMinTimeWindow() {
return (System.currentTimeMillis()/1000) - this.deviceStatusTaskPluginConfig.getIdleTimeToMarkUnreachable();
return (System.currentTimeMillis() / 1000) - this.deviceStatusTaskPluginConfig.getIdleTimeToMarkUnreachable();
}
private long getMaxTimeWindow() {
//Need to consider the frequency of the task as well
return (System.currentTimeMillis()/1000) - this.deviceStatusTaskPluginConfig.getIdleTimeToMarkInactive() -
return (System.currentTimeMillis() / 1000) - this.deviceStatusTaskPluginConfig.getIdleTimeToMarkInactive() -
this.deviceStatusTaskPluginConfig.getFrequency();
}
@ -149,7 +156,7 @@ public class DeviceStatusMonitoringTask implements Task {
+ deviceType + "'", e);
} catch (TransactionManagementException e) {
throw new DeviceStatusTaskException("Error occurred while initiating a transaction for updating the device " +
"status of type '" + deviceType +"'", e);
"status of type '" + deviceType + "'", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@ -157,7 +164,7 @@ public class DeviceStatusMonitoringTask implements Task {
}
private List<OperationEnrolmentMapping> getOperationEnrolmentMappings() throws DeviceStatusTaskException {
List<OperationEnrolmentMapping> operationEnrolmentMappings = null;
List<OperationEnrolmentMapping> operationEnrolmentMappings;
try {
OperationManagementDAOFactory.openConnection();
operationEnrolmentMappings = OperationManagementDAOFactory.
@ -176,7 +183,7 @@ public class DeviceStatusMonitoringTask implements Task {
}
private Map<Integer, Long> getLastDeviceActivities() throws DeviceStatusTaskException {
Map<Integer, Long> lastActivities = null;
Map<Integer, Long> lastActivities;
try {
OperationManagementDAOFactory.openConnection();
lastActivities = OperationManagementDAOFactory.

@ -1,59 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.task;
import java.util.List;
/**
* This is the bean for the operations added by the task.
*/
public class TaskOperation {
private String taskName;
private int recurrentTimes;
private List<String> taskPlatforms;
public List<String> getTaskPlatforms() {
return taskPlatforms;
}
public void setTaskPlatforms(List<String> taskPlatforms) {
this.taskPlatforms = taskPlatforms;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public int getRecurrentTimes() {
return recurrentTimes;
}
public void setRecurrentTimes(int recurrentTimes) {
this.recurrentTimes = recurrentTimes;
}
}

@ -33,7 +33,6 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.core.task;
import org.wso2.carbon.context.PrivilegedCarbonContext;
@ -86,4 +85,3 @@ public class Utils {
}
}

@ -30,9 +30,9 @@ import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class ArchivalTask implements Task {
private static Log log = LogFactory.getLog(ArchivalTask.class);
private static final Log log = LogFactory.getLog(ArchivalTask.class);
private ArchivalService archivalService;
@ -72,16 +72,6 @@ public class ArchivalTask implements Task {
millis -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
StringBuilder sb = new StringBuilder(64);
sb.append(days);
sb.append(" Days ");
sb.append(hours);
sb.append(" Hours ");
sb.append(minutes);
sb.append(" Minutes ");
sb.append(seconds);
sb.append(" Seconds");
return (sb.toString());
return (days + " Days " + hours + " Hours " + minutes + " Minutes " + seconds + " Seconds");
}
}

@ -32,19 +32,16 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.core.task.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.StartupOperationConfig;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
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.core.internal.DeviceManagementDataHolder;
@ -54,16 +51,19 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException;
import org.wso2.carbon.device.mgt.core.task.DeviceTaskManager;
import org.wso2.carbon.device.mgt.core.task.Utils;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DeviceTaskManagerImpl implements DeviceTaskManager {
private static Log log = LogFactory.getLog(DeviceTaskManagerImpl.class);
private String deviceType;
private static final Log log = LogFactory.getLog(DeviceTaskManagerImpl.class);
private final String deviceType;
static volatile Map<Integer, Map<String, Map<String, Long>>> map = new HashMap<>();
private static volatile Map<Integer, List<String>> startupConfigMap = new HashMap<>();
private static final Map<Integer, List<String>> startupConfigMap = new HashMap<>();
private OperationMonitoringTaskConfig operationMonitoringTaskConfig;
private StartupOperationConfig startupOperationConfig;
@ -118,58 +118,25 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager {
public void addOperations() throws DeviceMgtTaskException {
DeviceManagementProviderService deviceManagementProviderService = DeviceManagementDataHolder.getInstance().
getDeviceManagementProvider();
try {
//list operations for device type
List<String> operations = this.getValidOperationNames();
if (operations.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("No operations are available.");
}
return;
//list operations for device type
List<String> operations = this.getValidOperationNames();
if (operations.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("No operations are available.");
}
List<DeviceIdentifier> validDeviceIdentifiers;
List<String> startupOperations;
//list devices of device type
List<Device> devices = deviceManagementProviderService.getAllDevices(deviceType, false);
return;
}
if (!devices.isEmpty()) {
if (log.isDebugEnabled() && deviceType != null) {
log.info("Devices exist to add operations and the total number of devices are " + devices.size());
}
validDeviceIdentifiers = DeviceManagerUtil.getValidDeviceIdentifiers(devices);
if (!validDeviceIdentifiers.isEmpty()) {
if (log.isDebugEnabled() && deviceType != null) {
log.debug("Number of valid device identifier size to add operations: " + validDeviceIdentifiers
.size());
}
for (String str : operations) {
CommandOperation operation = new CommandOperation();
operation.setEnabled(true);
operation.setType(Operation.Type.COMMAND);
operation.setCode(str);
deviceManagementProviderService.addOperation(deviceType, operation, validDeviceIdentifiers);
}
startupOperations = getStartupOperations();
if (startupOperations != null && !startupOperations.isEmpty()) {
addStartupOperations(startupOperations, validDeviceIdentifiers,
deviceManagementProviderService);
}
} else {
if (log.isDebugEnabled()) {
log.debug("No valid devices are available.");
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("No devices are available to perform the operations.");
}
for (String str : operations) {
CommandOperation operation = new CommandOperation();
operation.setEnabled(true);
operation.setType(Operation.Type.COMMAND);
operation.setCode(str);
try {
deviceManagementProviderService.addTaskOperation(deviceType, operation);
} catch (OperationManagementException e) {
throw new DeviceMgtTaskException("Error occurred while adding task operations to devices", e);
}
} catch (InvalidDeviceException e) {
throw new DeviceMgtTaskException("Invalid DeviceIdentifiers found.", e);
} catch (DeviceManagementException e) {
throw new DeviceMgtTaskException("Error occurred while retrieving the device list.", e);
} catch (OperationManagementException e) {
throw new DeviceMgtTaskException("Error occurred while adding the operations to devices", e);
}
}
@ -187,7 +154,7 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager {
mp.put(top.getTaskName(), milliseconds);
} else {
Long lastExecutedTime = mp.get(top.getTaskName());
Long evalTime = lastExecutedTime + (frequency * top.getRecurrentTimes());
long evalTime = lastExecutedTime + (frequency * top.getRecurrentTimes());
if (evalTime <= milliseconds) {
opNames.add(top.getTaskName());
mp.put(top.getTaskName(), milliseconds);
@ -230,9 +197,7 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager {
private List<MonitoringOperation> getOperationListforTask() throws DeviceMgtTaskException {
DeviceManagementProviderService deviceManagementProviderService = DeviceManagementDataHolder
.getInstance().
getDeviceManagementProvider();
.getInstance().getDeviceManagementProvider();
return deviceManagementProviderService.getMonitoringOperationList(
deviceType);//Get task list from each device type
}
@ -265,9 +230,7 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager {
} catch (DeviceMgtTaskException e) {
// ignoring the error, no need to throw, If error occurs, return value will be false.
}
return false;
}
}

@ -14,29 +14,12 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*
* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
@ -56,15 +39,15 @@ import org.wso2.carbon.device.mgt.common.ApplicationRegistration;
import org.wso2.carbon.device.mgt.common.ApplicationRegistrationException;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.EnrollmentConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.configuration.mgt.EnrollmentConfiguration;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
@ -112,7 +95,6 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Hashtable;
@ -124,8 +106,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
public final class DeviceManagerUtil {
public final class DeviceManagerUtil {
private static final Log log = LogFactory.getLog(DeviceManagerUtil.class);
public static final String GENERAL_CONFIG_RESOURCE_PATH = "general";
@ -166,7 +147,7 @@ import java.util.stream.IntStream;
List<JNDILookupDefinition.JNDIProperty> jndiPropertyList =
jndiConfig.getJndiProperties();
if (jndiPropertyList != null) {
Hashtable<Object, Object> jndiProperties = new Hashtable<Object, Object>();
Hashtable<Object, Object> jndiProperties = new Hashtable<>();
for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) {
jndiProperties.put(prop.getName(), prop.getValue());
}
@ -186,8 +167,8 @@ import java.util.stream.IntStream;
* @param isSharedWithAllTenants is this device type shared with all tenants.
* @return status of the operation
*/
public static boolean registerDeviceType(String typeName, int tenantId, boolean isSharedWithAllTenants
, DeviceTypeMetaDefinition deviceTypeDefinition)
public static boolean registerDeviceType(String typeName, int tenantId, boolean isSharedWithAllTenants,
DeviceTypeMetaDefinition deviceTypeDefinition)
throws DeviceManagementException {
boolean status;
try {
@ -210,11 +191,11 @@ import java.util.stream.IntStream;
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while registering the device type '"
+ typeName + "'", e);
+ typeName + "'", e);
} catch (TransactionManagementException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("SQL occurred while registering the device type '"
+ typeName + "'", e);
+ typeName + "'", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@ -229,7 +210,7 @@ import java.util.stream.IntStream;
* @return DeviceType which contains info about the device-type.
*/
public static DeviceType getDeviceType(String typeName, int tenantId) throws DeviceManagementException {
DeviceType deviceType = null;
DeviceType deviceType;
try {
DeviceManagementDAOFactory.openConnection();
DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
@ -316,7 +297,6 @@ import java.util.stream.IntStream;
return deviceIdentifiers;
}
public static String getServerBaseHttpsUrl() {
String hostName = "localhost";
try {
@ -356,10 +336,6 @@ import java.util.stream.IntStream;
/**
* returns the tenant Id of the specific tenant Domain
*
* @param tenantDomain
* @return
* @throws DeviceManagementException
*/
public static int getTenantId(String tenantDomain) throws DeviceManagementException {
try {
@ -390,14 +366,14 @@ import java.util.stream.IntStream;
return deviceManagementConfig.getPaginationConfiguration().getActivityListPageSize();
} else {
throw new OperationManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
"cdm-config.xml file.");
}
}
return limit;
}
public static PaginationRequest validateOperationListPageSize(PaginationRequest paginationRequest) throws
OperationManagementException {
public static PaginationRequest validateOperationListPageSize(PaginationRequest paginationRequest)
throws OperationManagementException {
if (paginationRequest.getRowCount() == 0) {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig();
@ -406,14 +382,14 @@ import java.util.stream.IntStream;
getOperationListPageSize());
} else {
throw new OperationManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
"cdm-config.xml file.");
}
}
return paginationRequest;
}
public static PaginationRequest validateNotificationListPageSize(PaginationRequest paginationRequest) throws
NotificationManagementException {
public static PaginationRequest validateNotificationListPageSize(PaginationRequest paginationRequest)
throws NotificationManagementException {
if (paginationRequest.getRowCount() == 0) {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig();
@ -421,15 +397,15 @@ import java.util.stream.IntStream;
paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration().
getNotificationListPageSize());
} else {
throw new NotificationManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
throw new NotificationManagementException("Device-Mgt configuration has not initialized. " +
"Please check the cdm-config.xml file.");
}
}
return paginationRequest;
}
public static PaginationRequest validateDeviceListPageSize(PaginationRequest paginationRequest) throws
DeviceManagementException {
public static PaginationRequest validateDeviceListPageSize(PaginationRequest paginationRequest)
throws DeviceManagementException {
if (paginationRequest.getRowCount() == 0) {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig();
@ -437,24 +413,24 @@ import java.util.stream.IntStream;
paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration().
getDeviceListPageSize());
} else {
throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
throw new DeviceManagementException("Device-Mgt configuration has not initialized. " +
"Please check the cdm-config.xml file.");
}
}
return paginationRequest;
}
public static GroupPaginationRequest validateGroupListPageSize(GroupPaginationRequest paginationRequest) throws
GroupManagementException {
public static GroupPaginationRequest validateGroupListPageSize(GroupPaginationRequest paginationRequest)
throws GroupManagementException {
if (paginationRequest.getRowCount() == 0) {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance()
.getDeviceManagementConfig();
if (deviceManagementConfig != null) {
paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration()
.getDeviceListPageSize());
.getDeviceListPageSize());
} else {
throw new GroupManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
throw new GroupManagementException("Device-Mgt configuration has not initialized. " +
"Please check the cdm-config.xml file.");
}
}
return paginationRequest;
@ -467,8 +443,8 @@ import java.util.stream.IntStream;
if (deviceManagementConfig != null) {
return deviceManagementConfig.getPaginationConfiguration().getDeviceListPageSize();
} else {
throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
throw new DeviceManagementException("Device-Mgt configuration has not initialized. " +
"Please check the cdm-config.xml file.");
}
}
return limit;
@ -480,8 +456,8 @@ import java.util.stream.IntStream;
if (deviceManagementConfig != null) {
return deviceManagementConfig.getOperationAnalyticsConfiguration().isPublishLocationResponseEnabled();
} else {
throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
throw new DeviceManagementException("Device-Mgt configuration has not initialized. " +
"Please check the cdm-config.xml file.");
}
}
@ -491,8 +467,8 @@ import java.util.stream.IntStream;
if (deviceManagementConfig != null) {
return deviceManagementConfig.getOperationAnalyticsConfiguration().isPublishDeviceInfoResponseEnabled();
} else {
throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
throw new DeviceManagementException("Device-Mgt configuration has not initialized. " +
"Please check the cdm-config.xml file.");
}
}
@ -503,8 +479,8 @@ import java.util.stream.IntStream;
return deviceManagementConfig.getOperationAnalyticsConfiguration()
.getOperationResponseConfigurations().isEnabled();
} else {
throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
throw new DeviceManagementException("Device-Mgt configuration has not initialized. " +
"Please check the cdm-config.xml file.");
}
}
@ -515,8 +491,8 @@ import java.util.stream.IntStream;
return deviceManagementConfig.getOperationAnalyticsConfiguration()
.getOperationResponseConfigurations().getOperations();
} else {
throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
throw new DeviceManagementException("Device-Mgt configuration has not initialized. " +
"Please check the cdm-config.xml file.");
}
}
@ -540,6 +516,7 @@ import java.util.stream.IntStream;
errorDeviceIdList.add(deviceIdentifier);
}
}
DeviceIDHolder deviceIDHolder = new DeviceIDHolder();
deviceIDHolder.setValidDeviceIDList(validDeviceIDList);
deviceIDHolder.setErrorDeviceIdList(errorDeviceIdList);
@ -553,8 +530,10 @@ import java.util.stream.IntStream;
if (device == null || device.getDeviceIdentifier() == null ||
device.getDeviceIdentifier().isEmpty() || device.getEnrolmentInfo() == null) {
return false;
} else
return !EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus());
} else if (EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus())) {
return false;
}
return true;
}
public static boolean isDeviceExists(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
@ -595,7 +574,7 @@ import java.util.stream.IntStream;
deviceCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
Duration(TimeUnit.SECONDS, deviceCacheExpiry)).setStoreByValue(true).build();
if(deviceCacheCapacity > 0 ) {
((CacheImpl)(manager.<DeviceCacheKey, Device>getCache(DeviceManagementConstants.DEVICE_CACHE))).
((CacheImpl) manager.<DeviceCacheKey, Device>getCache(DeviceManagementConstants.DEVICE_CACHE)).
setCapacity(deviceCacheCapacity);
}
} else {
@ -627,10 +606,10 @@ import java.util.stream.IntStream;
initializeDeviceCache();
}
if (manager != null) {
deviceCache = manager.<DeviceCacheKey, Device>getCache(DeviceManagementConstants.DEVICE_CACHE);
deviceCache = manager.getCache(DeviceManagementConstants.DEVICE_CACHE);
} else {
deviceCache = Caching.getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER).
<DeviceCacheKey, Device>getCache(DeviceManagementConstants.DEVICE_CACHE);
deviceCache = Caching.getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER)
.getCache(DeviceManagementConstants.DEVICE_CACHE);
}
}
return deviceCache;
@ -645,7 +624,7 @@ import java.util.stream.IntStream;
*/
@SuppressWarnings("PackageAccessibility")
public static AppRegistrationCredentials getApplicationRegistrationCredentials(String host, String port,
String username, String password)
String username, String password)
throws ApplicationRegistrationException {
if (host == null || port == null) {
String msg = "Required gatewayHost or gatewayPort system property is null";

@ -118,11 +118,6 @@ public class TestDeviceManager implements DeviceManager {
return true;
}
@Override
public boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, EnrolmentInfo.Status status)
throws DeviceManagementException {

@ -45,7 +45,7 @@ public class TestDataHolder {
public static Device generateDummyDeviceData(String deviceType) {
Device device = new Device();
device.setEnrolmentInfo(generateEnrollmentInfo(new Date().getTime(), new Date().getTime(), OWNER, EnrolmentInfo
.OwnerShip.BYOD, EnrolmentInfo.Status.CREATED));
.OwnerShip.BYOD, EnrolmentInfo.Status.ACTIVE));
device.setDescription("Test Description");
device.setDeviceIdentifier(initialDeviceIdentifier);
device.setType(deviceType);
@ -118,7 +118,7 @@ public class TestDataHolder {
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setOwner(OWNER);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED);
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setEnrolmentInfo(enrolmentInfo);
device.setDescription("Test Description");
device.setDeviceIdentifier(deviceId.getId());
@ -131,7 +131,7 @@ public class TestDataHolder {
public static Device generateDummyDeviceData(DeviceIdentifier deviceIdentifier) {
Device device = new Device();
device.setEnrolmentInfo(generateEnrollmentInfo(new Date().getTime(), new Date().getTime(), OWNER, EnrolmentInfo
.OwnerShip.BYOD, EnrolmentInfo.Status.CREATED));
.OwnerShip.BYOD, EnrolmentInfo.Status.ACTIVE));
device.setDescription("Test Description");
device.setDeviceIdentifier(deviceIdentifier.getId());
device.setType(deviceIdentifier.getType());

@ -42,7 +42,7 @@ public class EnrolmentPersistenceTests extends BaseDeviceManagementTest {
/* Initializing source enrolment configuration bean to be tested */
EnrolmentInfo source =
new EnrolmentInfo(owner, EnrolmentInfo.OwnerShip.BYOD,
EnrolmentInfo.Status.CREATED);
EnrolmentInfo.Status.ACTIVE);
/* Adding dummy enrolment configuration to the device management metadata store */
try {

@ -238,7 +238,7 @@ public class OperationManagementTests extends BaseDeviceManagementTest {
@Test(dependsOnMethods = "addProfileOperation")
public void getOperations() throws DeviceManagementException, OperationManagementException, InvalidDeviceException {
for (DeviceIdentifier deviceIdentifier : deviceIds) {
List operations = this.operationMgtService.getOperations(deviceIdentifier);
List<? extends Operation> operations = this.operationMgtService.getOperations(deviceIdentifier);
Assert.assertEquals(operations.size(), 4, "The operations should be 4, but found only " + operations.size());
}
}
@ -611,14 +611,16 @@ public class OperationManagementTests extends BaseDeviceManagementTest {
private void changeStatus(EnrolmentInfo.Status status) throws DeviceManagementException,
OperationManagementException {
Device device = this.deviceMgmtProvider.getDevice(this.deviceIds.get(1));
Device device = this.deviceMgmtProvider.getDevice(this.deviceIds.get(1), false);
Assert.assertTrue(device != null);
Assert.assertEquals(device.getType(), DEVICE_TYPE);
Assert.assertTrue(device.getEnrolmentInfo() != null);
device.getEnrolmentInfo().setStatus(status);
boolean modified = this.deviceMgmtProvider.changeDeviceStatus(this.deviceIds.get(1), status);
Assert.assertTrue(modified);
device = this.deviceMgmtProvider.getDevice(this.deviceIds.get(1));
if (device.getEnrolmentInfo().getStatus() != status) {
Assert.assertTrue(modified);
device.getEnrolmentInfo().setStatus(status);
}
device = this.deviceMgmtProvider.getDevice(this.deviceIds.get(1), false);
Assert.assertEquals(device.getEnrolmentInfo().getStatus(), status);
}

@ -108,10 +108,8 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes
private static final Log log = LogFactory.getLog(DeviceManagementProviderServiceTest.class);
public static final String DEVICE_ID = "9999";
private static final String ALTERNATE_DEVICE_ID = "1128";
private DeviceManagementProviderService providerService;
private static final String DEVICE_TYPE = "RANDOM_DEVICE_TYPE";
private static final String DEVICE_OWNER = "admin";
private DeviceDetailsDAO deviceDetailsDAO = DeviceManagementDAOFactory.getDeviceDetailsDAO();
private final DeviceDetailsDAO deviceDetailsDAO = DeviceManagementDAOFactory.getDeviceDetailsDAO();
DeviceManagementProviderService deviceMgtService;
@ -253,7 +251,7 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setOwner("user1");
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED);
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
Device alternateDevice = TestDataHolder.generateDummyDeviceData(DEVICE_ID, DEVICE_TYPE,
enrolmentInfo);
@ -884,8 +882,8 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes
@Test(dependsOnMethods = {"testReEnrollmentofSameDeviceUnderSameUser"})
public void testUpdateDevicesStatusWithDeviceID() throws DeviceManagementException {
if (!isMock()) {
boolean status = deviceMgtService.setStatus(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE), "user1",
EnrolmentInfo.Status.ACTIVE);
Device device = TestDataHolder.generateDummyDeviceData("abc");
boolean status = deviceMgtService.setStatus(device, EnrolmentInfo.Status.ACTIVE);
Assert.assertTrue(status);
}
}

@ -89,6 +89,7 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
OWNER VARCHAR(50) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,
IS_TRANSFERRED BOOLEAN NOT NULL DEFAULT FALSE,
DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL,
TENANT_ID INT NOT NULL,
@ -106,6 +107,13 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING (
PUSH_NOTIFICATION_STATUS VARCHAR(50) NULL,
CREATED_TIMESTAMP INT NOT NULL,
UPDATED_TIMESTAMP INT NOT NULL,
OPERATION_CODE VARCHAR(50) NOT NULL,
INITIATED_BY VARCHAR(100) NULL,
TYPE VARCHAR(20) NOT NULL,
DEVICE_ID INTEGER DEFAULT NULL,
DEVICE_TYPE VARCHAR(300) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES
DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
@ -118,7 +126,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE (
ENROLMENT_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
EN_OP_MAP_ID INTEGER NOT NULL,
OPERATION_RESPONSE LONGBLOB DEFAULT NULL,
OPERATION_RESPONSE VARCHAR(1024) DEFAULT NULL ,
IS_LARGE_RESPONSE BOOLEAN NOT NULL DEFAULT FALSE,
RECEIVED_TIMESTAMP TIMESTAMP NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES
@ -129,6 +138,21 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE (
DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE DM_DEVICE_OPERATION_RESPONSE_LARGE (
ID INTEGER NOT NULL,
OPERATION_RESPONSE LONGBLOB DEFAULT NULL,
OPERATION_ID INTEGER NOT NULL,
EN_OP_MAP_ID INTEGER NOT NULL,
RECEIVED_TIMESTAMP TIMESTAMP NULL,
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
CONSTRAINT fk_dm_device_operation_response_large_mapping FOREIGN KEY (ID)
REFERENCES DM_DEVICE_OPERATION_RESPONSE (ID)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_en_op_map_response_large FOREIGN KEY (EN_OP_MAP_ID)
REFERENCES DM_ENROLMENT_OP_MAPPING (ID)
ON DELETE NO ACTION ON UPDATE NO ACTION
);
-- POLICY RELATED TABLES --
CREATE TABLE IF NOT EXISTS DM_PROFILE (
@ -358,16 +382,14 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION (
CREATE TABLE IF NOT EXISTS DM_NOTIFICATION (
NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NULL,
TENANT_ID INTEGER NOT NULL,
STATUS VARCHAR(10) NULL,
DESCRIPTION VARCHAR(1000) NULL,
LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL,
PRIMARY KEY (NOTIFICATION_ID),
CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_operation_notification FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
-- NOTIFICATION TABLE END --

@ -40,21 +40,21 @@ import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceDetails;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DataSource;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.TableConfig;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Table;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceDetails;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Feature;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Table;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.TableConfig;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceDAODefinition;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager;
import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException;
@ -80,7 +80,7 @@ import javax.xml.stream.XMLStreamReader;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
@ -90,19 +90,18 @@ import java.util.List;
public class DeviceTypeManager implements DeviceManager {
private static final Log log = LogFactory.getLog(DeviceTypeManager.class);
private String deviceType;
private DeviceTypePluginDAOManager deviceTypePluginDAOManager;
private LicenseManager licenseManager;
private PlatformConfiguration defaultPlatformConfiguration;
private boolean propertiesExist;
private boolean requiredDeviceTypeAuthorization;
private boolean claimable;
private final String deviceType;
private final LicenseManager licenseManager;
private final PlatformConfiguration defaultPlatformConfiguration;
private final boolean requiredDeviceTypeAuthorization;
private static final String PATH_MOBILE_PLUGIN_CONF_DIR =
CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "device-mgt-plugin-configs" + File.separator
+ "mobile";
private FeatureManager featureManager;
private boolean propertiesExist;
private DeviceTypePluginDAOManager deviceTypePluginDAOManager;
public DeviceTypeManager(DeviceTypeConfigIdentifier deviceTypeConfigIdentifier,
DeviceTypeConfiguration deviceTypeConfiguration) {
@ -135,10 +134,6 @@ public class DeviceTypeManager implements DeviceManager {
String msg = "Error occurred while adding default license for " + deviceType + " devices.";
throw new DeviceTypeDeployerPayloadException(msg, e);
}
claimable = false;
if (deviceTypeConfiguration.getClaimable() != null ) {
claimable = deviceTypeConfiguration.getClaimable().isEnabled();
}
// Loading default platform configuration
try {
@ -295,8 +290,7 @@ public class DeviceTypeManager implements DeviceManager {
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
XMLStreamReader reader = factory.createXMLStreamReader(
new StringReader(new String((byte[]) resource.getContent(), Charset
.forName(DeviceTypePluginConstants.CHARSET_UTF8))));
new StringReader(new String((byte[]) resource.getContent(), StandardCharsets.UTF_8)));
JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
@ -476,11 +470,6 @@ public class DeviceTypeManager implements DeviceManager {
return true;
}
@Override
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
return claimable;
}
@Override
public boolean setStatus(DeviceIdentifier deviceIdentifier, String currentUser,
EnrolmentInfo.Status status) throws DeviceManagementException {

@ -80,17 +80,17 @@ public class DeviceTypeManagerService implements DeviceManagementService {
private static final String NOTIFIER_PROPERTY = "notifierType";
private static final String NOTIFIER_TYPE_LOCAL = "LOCAL";
private DeviceManager deviceManager;
private final DeviceManager deviceManager;
private PushNotificationConfig pushNotificationConfig;
private ProvisioningConfig provisioningConfig;
private String type;
private OperationMonitoringTaskConfig operationMonitoringConfigs;
private List<MonitoringOperation> monitoringOperations;
private final OperationMonitoringTaskConfig operationMonitoringConfigs;
private List<MonitoringOperation> monitoringOperations = new ArrayList<>();
private PolicyMonitoringManager policyMonitoringManager;
private InitialOperationConfig initialOperationConfig;
private final InitialOperationConfig initialOperationConfig;
private StartupOperationConfig startupOperationConfig;
private PullNotificationSubscriber pullNotificationSubscriber;
private DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig;
private final DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig;
private DeviceTypePlatformDetails deviceTypePlatformDetails;
private GeneralConfig generalConfig;
private boolean isRegistryBasedConfigs = false;
@ -141,6 +141,7 @@ public class DeviceTypeManagerService implements DeviceManagementService {
MonitoringOperation monitoringOperation = new MonitoringOperation();
monitoringOperation.setTaskName(op.getOperationName());
monitoringOperation.setRecurrentTimes(op.getRecurrency());
monitoringOperation.setResponsePersistence(op.getResponsePersistence());
monitoringOperations.add(monitoringOperation);
}
}

@ -25,7 +25,6 @@ import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfi
import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeDefinitionProvider;
import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Claimable;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceDetails;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Properties;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Features;
@ -60,9 +59,6 @@ public class HTTPDeviceTypeManagerService extends DeviceTypeManagerService imple
DeviceTypeConfiguration deviceTypeConfiguration = new DeviceTypeConfiguration();
if (deviceTypeMetaDefinition != null) {
Claimable claimable = new Claimable();
claimable.setEnabled(deviceTypeMetaDefinition.isClaimable());
deviceTypeConfiguration.setClaimable(claimable);
if (deviceTypeMetaDefinition.getProperties() != null &&
deviceTypeMetaDefinition.getProperties().size() > 0) {

@ -1,104 +0,0 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.extensions.device.type.template.config;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for DeviceDetails complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="DeviceDetails">
* &lt;simpleContent>
* &lt;extension base="&lt;http://www.w3.org/2001/XMLSchema>string">
* &lt;attribute name="table-id" type="{http://www.w3.org/2001/XMLSchema}string" />
* &lt;/extension>
* &lt;/simpleContent>
* &lt;/complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Claimable", propOrder = {
"value"
})
public class Claimable {
@XmlValue
protected String value;
@XmlAttribute(name = "enabled")
protected boolean enabled;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the enabled property.
*
* @return
* possible object is
* {@link String }
*
*/
public boolean isEnabled() {
return enabled;
}
/**
* Sets the value of the enabled property.
*
* @param enabled
* allowed object is
* {@link String }
*
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}

@ -78,8 +78,6 @@ public class DeviceTypeConfiguration {
@XmlElement(name = "DeviceDetails", required = true)
protected DeviceDetails deviceDetails;
@XmlElement(name = "Claimable", required = true)
protected Claimable claimable;
@XmlElement(name = "Features", required = true)
protected Features features;
@XmlElement(name = "PolicyUIConfigurations", required = true)
@ -198,27 +196,6 @@ public class DeviceTypeConfiguration {
this.deviceDetails = value;
}
/**
* Gets the value of the Claimable property.
*
* @return possible object is
* {@link DeviceDetails }
*/
public Claimable getClaimable() {
return claimable;
}
/**
* Sets the value of the deviceDetails property.
*
* @param value allowed object is
* {@link DeviceDetails }
*/
public void setClaimable(Claimable value) {
this.claimable = value;
}
/**
* Gets the value of the policyMonitoring property.
*

@ -67,6 +67,7 @@ public class TaskConfiguration {
private String operationName;
private int recurrency;
private boolean responsePersistence = true;
@XmlElement(name = "Name", required = true)
public String getOperationName() {
@ -86,6 +87,14 @@ public class TaskConfiguration {
this.recurrency = recurrency;
}
@XmlElement(name = "ResponsePersistence")
public boolean getResponsePersistence() {
return responsePersistence;
}
public void setResponsePersistence(boolean responsePersistence) {
this.responsePersistence = responsePersistence;
}
}
}

@ -23,6 +23,5 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template.util;
*/
public class DeviceTypePluginConstants {
public static final String MEDIA_TYPE_XML = "application/xml";
public static final String CHARSET_UTF8 = "UTF8";
public static final String LANGUAGE_CODE_ENGLISH_US = "en_US";
}

@ -220,7 +220,6 @@ public class HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest {
deviceTypeMetaDefinition = new DeviceTypeMetaDefinition();
deviceTypeMetaDefinition.setPushNotificationConfig(pushNotificationConfig);
deviceTypeMetaDefinition.setDescription("This is android_sense");
deviceTypeMetaDefinition.setClaimable(true);
deviceTypeMetaDefinition.setLicense(androidSenseLicense);
deviceTypeMetaDefinition.setFeatures(features);
}

@ -23,21 +23,20 @@ import org.wso2.carbon.device.mgt.oauth.extensions.internal.OAuthExtensionsDataH
import org.wso2.carbon.identity.oauth.cache.CacheEntry;
import org.wso2.carbon.identity.oauth.cache.OAuthCache;
import org.wso2.carbon.identity.oauth.cache.OAuthCacheKey;
import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.dao.TokenMgtDAO;
import org.wso2.carbon.identity.oauth2.dao.TokenManagementDAO;
import org.wso2.carbon.identity.oauth2.dao.TokenManagementDAOImpl;
import org.wso2.carbon.identity.oauth2.model.AccessTokenDO;
import org.wso2.carbon.identity.oauth2.model.ResourceScopeCacheEntry;
import org.wso2.carbon.identity.oauth2.validators.OAuth2ScopeValidator;
import java.util.Map;
@SuppressWarnings("unused")
public class ScopeValidationHandler extends OAuth2ScopeValidator {
private final static Log log = LogFactory.getLog(ScopeValidationHandler.class);
private Map<String, OAuth2ScopeValidator> scopeValidators;
private final String DEFAULT_PREFIX = "default";
private final Map<String, OAuth2ScopeValidator> scopeValidators;
public ScopeValidationHandler() {
scopeValidators = OAuthExtensionsDataHolder.getInstance().getScopeValidators();
@ -47,7 +46,7 @@ public class ScopeValidationHandler extends OAuth2ScopeValidator {
//returns true if scope validators are not defined
if (scopeValidators == null || scopeValidators.isEmpty()) {
if(log.isDebugEnabled()){
if (log.isDebugEnabled()) {
log.debug("OAuth2 scope validators are not loaded");
}
return true;
@ -57,30 +56,31 @@ public class ScopeValidationHandler extends OAuth2ScopeValidator {
//returns true if scope does not exist for the resource
if (resourceScope == null) {
if(log.isDebugEnabled()){
if (log.isDebugEnabled()) {
log.debug("Resource '" + resource + "' is not protected with a scope");
}
return true;
}
String scope[] = resourceScope.split(":");
String[] scope = resourceScope.split(":");
String scopePrefix = scope[0];
OAuth2ScopeValidator scopeValidator = scopeValidators.get(scopePrefix);
if (scopeValidator == null) {
if(log.isDebugEnabled()){
if (log.isDebugEnabled()) {
log.debug("OAuth2 scope validator cannot be identified for '" + scopePrefix + "' scope prefix");
}
// loading default scope validator if matching validator is not found
String DEFAULT_PREFIX = "default";
scopeValidator = scopeValidators.get(DEFAULT_PREFIX);
if(log.isDebugEnabled()){
if (log.isDebugEnabled()) {
log.debug("Loading default scope validator");
}
if (scopeValidator == null) {
if(log.isDebugEnabled()){
if (log.isDebugEnabled()) {
log.debug("Default scope validator is not available");
}
return true;
@ -95,35 +95,29 @@ public class ScopeValidationHandler extends OAuth2ScopeValidator {
String resourceScope = null;
boolean cacheHit = false;
// Check the cache, if caching is enabled.
if (OAuthServerConfiguration.getInstance().isCacheEnabled()) {
OAuthCache oauthCache = OAuthCache.getInstance();
OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
CacheEntry result = oauthCache.getValueFromCache(cacheKey);
//Cache hit
if (result instanceof ResourceScopeCacheEntry) {
resourceScope = ((ResourceScopeCacheEntry) result).getScope();
cacheHit = true;
}
OAuthCache oauthCache = OAuthCache.getInstance();
OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
CacheEntry result = oauthCache.getValueFromCache(cacheKey);
//Cache hit
if (result instanceof ResourceScopeCacheEntry) {
resourceScope = ((ResourceScopeCacheEntry) result).getScope();
cacheHit = true;
}
TokenMgtDAO tokenMgtDAO = new TokenMgtDAO();
if (!cacheHit) {
TokenManagementDAO tokenMgtDAO = new TokenManagementDAOImpl();
try {
resourceScope = tokenMgtDAO.findScopeOfResource(resource);
resourceScope = tokenMgtDAO.findTenantAndScopeOfResource(resource).getLeft();
} catch (IdentityOAuth2Exception e) {
log.error("Error occurred while retrieving scope for resource '" + resource + "'");
}
if (OAuthServerConfiguration.getInstance().isCacheEnabled()) {
OAuthCache oauthCache = OAuthCache.getInstance();
OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
ResourceScopeCacheEntry cacheEntry = new ResourceScopeCacheEntry(resourceScope);
//Store resourceScope in cache even if it is null (to avoid database calls when accessing resources for
//which scopes haven't been defined).
oauthCache.addToCache(cacheKey, cacheEntry);
}
ResourceScopeCacheEntry cacheEntry = new ResourceScopeCacheEntry(resourceScope);
//Store resourceScope in cache even if it is null (to avoid database calls when accessing resources for
//which scopes haven't been defined).
oauthCache.addToCache(cacheKey, cacheEntry);
}
return resourceScope;
}

@ -74,8 +74,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint {
DeviceManagementProviderService service = this.getDeviceManagementProviderService();
for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
Device device = service.getDevice(deviceIdentifier, false);
service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(),
EnrolmentInfo.Status.UNREACHABLE);
service.setStatus(device, EnrolmentInfo.Status.UNREACHABLE);
}
} catch (DeviceManagementException e) {
String msg = "Error occurred while setting the device as unreachable";
@ -91,8 +90,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint {
DeviceManagementProviderService service = this.getDeviceManagementProviderService();
for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
Device device = service.getDevice(deviceIdentifier, false);
service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(),
EnrolmentInfo.Status.INACTIVE);
service.setStatus(device, EnrolmentInfo.Status.INACTIVE);
}
} catch (DeviceManagementException e) {
String msg = "Error occurred while setting the device as inactive";
@ -109,8 +107,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(device.getDeviceIdentifier());
deviceIdentifier.setType(device.getType());
service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(),
EnrolmentInfo.Status.UNREACHABLE);
service.setStatus(device, EnrolmentInfo.Status.UNREACHABLE);
}
} catch (DeviceManagementException e) {
String msg = "Error occurred while setting the device as unreachable";
@ -126,8 +123,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint {
DeviceManagementProviderService service = this.getDeviceManagementProviderService();
Device device = service.getDevice(deviceIdentifier, false);
service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(),
EnrolmentInfo.Status.ACTIVE);
service.setStatus(device, EnrolmentInfo.Status.ACTIVE);
} catch (DeviceManagementException e) {
String msg = "Error occurred while setting the device as reachable for " +
@ -231,8 +227,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint {
try {
DeviceManagementProviderService service = this.getDeviceManagementProviderService();
Device device = service.getDevice(deviceIdentifier, false);
service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(),
EnrolmentInfo.Status.ACTIVE);
service.setStatus(device, EnrolmentInfo.Status.ACTIVE);
} catch (DeviceManagementException e) {
String msg = "Error occurred while marking device as compliance " + deviceIdentifier.getId() + " - " +
@ -246,11 +241,9 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint {
public void deactivateDevice(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException {
try {
DeviceManagementProviderService service = this.getDeviceManagementProviderService();
Device device = service.getDevice(deviceIdentifier, false);
service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(),
EnrolmentInfo.Status.INACTIVE);
service.setStatus(device, EnrolmentInfo.Status.INACTIVE);
} catch (DeviceManagementException e) {
String msg = "Error occurred while deactivating the device " + deviceIdentifier.getId() + " - " +
@ -266,8 +259,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint {
try {
DeviceManagementProviderService service = this.getDeviceManagementProviderService();
Device device = service.getDevice(deviceIdentifier, false);
service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(),
EnrolmentInfo.Status.ACTIVE);
service.setStatus(device, EnrolmentInfo.Status.ACTIVE);
} catch (DeviceManagementException e) {
String msg = "Error occurred while activating the device " + deviceIdentifier.getId() + " - " +

@ -150,15 +150,10 @@ public class MonitoringTask implements Task {
deviceType);
}
for (Device device : devices) {
EnrolmentInfo.Status status = device.getEnrolmentInfo().getStatus();
if (status.equals(EnrolmentInfo.Status.BLOCKED) ||
status.equals(EnrolmentInfo.Status.REMOVED) ||
status.equals(EnrolmentInfo.Status.UNCLAIMED) ||
status.equals(EnrolmentInfo.Status.DISENROLLMENT_REQUESTED) ||
status.equals(EnrolmentInfo.Status.SUSPENDED)) {
continue;
} else {
if (status.equals(EnrolmentInfo.Status.ACTIVE) ||
status.equals(EnrolmentInfo.Status.INACTIVE) ||
status.equals(EnrolmentInfo.Status.UNREACHABLE)) {
notifiableDevices.add(device);
}
}

@ -124,11 +124,6 @@ public class TypeXDeviceManager implements DeviceManager {
return false;
}
@Override
public boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, EnrolmentInfo.Status status)
throws DeviceManagementException {

@ -56,6 +56,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_PROPERTIES (
PRIMARY KEY (DEVICE_TYPE_NAME, DEVICE_IDENTIFICATION, PROPERTY_NAME)
);
DROP TABLE IF EXISTS GROUP_PROPERTIES;
CREATE TABLE IF NOT EXISTS GROUP_PROPERTIES (
GROUP_ID INTEGER NOT NULL,
PROPERTY_NAME VARCHAR(100) DEFAULT 0,
@ -97,6 +98,7 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
OWNER VARCHAR(50) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,
IS_TRANSFERRED BOOLEAN NOT NULL DEFAULT FALSE,
DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL,
TENANT_ID INT NOT NULL,
@ -111,9 +113,16 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING (
ENROLMENT_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
STATUS VARCHAR(50) NULL,
PUSH_NOTIFICATION_STATUS VARCHAR(50) NULL,
CREATED_TIMESTAMP INT NOT NULL,
UPDATED_TIMESTAMP INT NOT NULL,
PUSH_NOTIFICATION_STATUS VARCHAR(50),
OPERATION_CODE VARCHAR(50) NOT NULL,
INITIATED_BY VARCHAR(100) NULL,
TYPE VARCHAR(20) NOT NULL,
DEVICE_ID INTEGER DEFAULT NULL,
DEVICE_TYPE VARCHAR(300) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES
DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
@ -126,13 +135,29 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE (
ID INTEGER AUTO_INCREMENT NOT NULL,
ENROLMENT_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
OPERATION_RESPONSE BLOB DEFAULT NULL,
EN_OP_MAP_ID INTEGER NOT NULL,
OPERATION_RESPONSE VARCHAR(1024) DEFAULT NULL ,
IS_LARGE_RESPONSE BOOLEAN NOT NULL DEFAULT FALSE,
RECEIVED_TIMESTAMP TIMESTAMP NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES
DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_en_op_map_response FOREIGN KEY (EN_OP_MAP_ID) REFERENCES
DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
DROP TABLE IF EXISTS DM_DEVICE_OPERATION_RESPONSE_LARGE;
CREATE TABLE DM_DEVICE_OPERATION_RESPONSE_LARGE (
ID INTEGER NOT NULL,
OPERATION_RESPONSE LONGBLOB DEFAULT NULL,
OPERATION_ID INTEGER NOT NULL,
RECEIVED_TIMESTAMP TIMESTAMP NULL,
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
CONSTRAINT fk_dm_device_operation_response_large_mapping FOREIGN KEY (ID)
REFERENCES DM_DEVICE_OPERATION_RESPONSE (ID)
ON DELETE NO ACTION ON UPDATE NO ACTION
);
-- POLICY RELATED TABLES --
@ -174,6 +199,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
ON UPDATE NO ACTION
);
DROP TABLE IF EXISTS DM_POLICY_CORRECTIVE_ACTION;
CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION (
ID INT(11) NOT NULL AUTO_INCREMENT,
ACTION_TYPE VARCHAR(45) NOT NULL,
@ -268,7 +294,7 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY (
);
DROP TABLE IF EXISTS DM_DEVICE_POLICY_APPLIED;
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED (
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED (
ID INT NOT NULL AUTO_INCREMENT ,
DEVICE_ID INT NOT NULL ,
ENROLMENT_ID INT(11) NOT NULL,
@ -287,7 +313,6 @@ DROP TABLE IF EXISTS DM_DEVICE_POLICY_APPLIED;
ON UPDATE NO ACTION
);
DROP TABLE IF EXISTS DM_CRITERIA;
CREATE TABLE IF NOT EXISTS DM_CRITERIA (
ID INT NOT NULL AUTO_INCREMENT,
@ -296,7 +321,6 @@ CREATE TABLE IF NOT EXISTS DM_CRITERIA (
PRIMARY KEY (ID)
);
DROP TABLE IF EXISTS DM_POLICY_CRITERIA;
CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA (
ID INT NOT NULL AUTO_INCREMENT,
@ -315,6 +339,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA (
ON UPDATE NO ACTION
);
DROP TABLE IF EXISTS DM_POLICY_CRITERIA_PROPERTIES;
CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES (
ID INT NOT NULL AUTO_INCREMENT,
POLICY_CRITERION_ID INT NOT NULL,
@ -368,21 +393,6 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES (
ON UPDATE NO ACTION
);
DROP TABLE IF EXISTS DM_ENROLMENT;
CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
OWNER VARCHAR(50) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,
DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL,
TENANT_ID INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
DROP TABLE IF EXISTS DM_APPLICATION;
CREATE TABLE IF NOT EXISTS DM_APPLICATION (
ID INTEGER AUTO_INCREMENT NOT NULL,
@ -432,6 +442,7 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION (
);
-- NOTIFICATION TABLE END --
DROP TABLE IF EXISTS DM_DEVICE_INFO;
CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INT NULL,
@ -451,6 +462,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
ON UPDATE NO ACTION
);
DROP TABLE IF EXISTS DM_DEVICE_LOCATION;
CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INT NULL,
@ -478,7 +490,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
ON UPDATE NO ACTION
);
DROP TABLE IF EXISTS DM_DEVICE_DETAIL;
CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
ID INT NOT NULL AUTO_INCREMENT,
DEVICE_ID INT NOT NULL,
@ -512,8 +524,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
ON UPDATE NO ACTION
);
-- POLICY AND DEVICE GROUP MAPPING --
DROP TABLE IF EXISTS DM_DEVICE_GROUP_POLICY;
CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY (
@ -593,4 +603,4 @@ DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND
DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID
ORDER BY TENANT_ID, DEVICE_ID;
-- END OF DASHBOARD RELATED VIEWS --
-- END OF DASHBOARD RELATED VIEWS --

@ -28,7 +28,6 @@
<class name="org.wso2.carbon.policy.mgt.core.PolicyDAOTestCase"/>
<class name="org.wso2.carbon.policy.mgt.core.MonitoringTestCase" />
<class name="org.wso2.carbon.policy.mgt.core.PolicyEvaluationTestCase" />
</classes>
</test>

@ -37,9 +37,9 @@
<Provider>org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.XMPPBasedPushNotificationProvider</Provider>
</PushNotificationProviders>
</PushNotificationConfiguration>
<PullNotificationConfiguration>
<Enabled>false</Enabled>
</PullNotificationConfiguration>
<PullNotificationConfiguration>
<Enabled>false</Enabled>
</PullNotificationConfiguration>
<IdentityConfiguration>
<ServerUrl>https://localhost:9443</ServerUrl>
<AdminUsername>admin</AdminUsername>
@ -100,6 +100,11 @@
</DataSourceConfiguration>
<ArchivalTask>
<Enabled>false</Enabled>
<ArchivePendingOperations>false</ArchivePendingOperations>
<DBConfig>
<SourceDB>DM_DB</SourceDB>
<DestinationDB>ARCHIVAL_DB</DestinationDB>
</DBConfig>
<TaskClass>org.wso2.carbon.device.mgt.core.task.impl.ArchivalTask</TaskClass>
<!-- Cron expression to run the task at specified time -->
<CronExpression>0 0 0 1/1 * ? *</CronExpression>

@ -8,10 +8,10 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION_ARCH (
INITIATED_BY VARCHAR(100) NULL,
OPERATION_DETAILS BLOB DEFAULT NULL,
ENABLED BOOLEAN NOT NULL DEFAULT FALSE,
ARCHIVED_AT TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (ID)
ARCHIVED_AT TIMESTAMP DEFAULT NOW()
)ENGINE = InnoDB;
CREATE INDEX IDX_OPR_ARC ON DM_OPERATION_ARCH(ARCHIVED_AT);
CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING_ARCH (
ID INTEGER NOT NULL,
@ -20,20 +20,31 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING_ARCH (
STATUS VARCHAR(50) NULL,
CREATED_TIMESTAMP INTEGER NOT NULL,
UPDATED_TIMESTAMP INTEGER NOT NULL,
ARCHIVED_AT TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (ID)
ARCHIVED_AT TIMESTAMP DEFAULT NOW()
)ENGINE = InnoDB;
CREATE INDEX IDX_EN_OP_MAP_ARCH ON DM_ENROLMENT_OP_MAPPING_ARCH(ARCHIVED_AT);
CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE_ARCH (
ID INT(11) NOT NULL,
ENROLMENT_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
OPERATION_RESPONSE LONGBLOB DEFAULT NULL,
OPERATION_RESPONSE VARCHAR(4096) DEFAULT NULL,
RECEIVED_TIMESTAMP TIMESTAMP NULL,
ARCHIVED_AT TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (ID)
IS_LARGE_RESPONSE BOOLEAN NOT NULL DEFAULT FALSE
)ENGINE = InnoDB;
CREATE INDEX IDX_OPR_RES_ARCH ON DM_DEVICE_OPERATION_RESPONSE_ARCH(ARCHIVED_AT);
CREATE TABLE DM_DEVICE_OPERATION_RESPONSE_LARGE_ARCH (
ID INT(11) NOT NULL,
OPERATION_RESPONSE LONGBLOB DEFAULT NULL,
ARCHIVED_AT TIMESTAMP DEFAULT NOW()
)ENGINE = InnoDB;
CREATE INDEX IDX_OPR_RES_LRG_ARCH ON DM_DEVICE_OPERATION_RESPONSE_LARGE_ARCH(ARCHIVED_AT);
CREATE TABLE IF NOT EXISTS DM_NOTIFICATION_ARCH (
NOTIFICATION_ID INTEGER NOT NULL,
DEVICE_ID INTEGER NOT NULL,
@ -41,6 +52,7 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION_ARCH (
TENANT_ID INTEGER NOT NULL,
STATUS VARCHAR(10) NULL,
DESCRIPTION VARCHAR(1000) NULL,
ARCHIVED_AT TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (NOTIFICATION_ID)
ARCHIVED_AT TIMESTAMP DEFAULT NOW()
)ENGINE = InnoDB;
CREATE INDEX IDX_NOT_ARCH ON DM_NOTIFICATION_ARCH(ARCHIVED_AT);

@ -0,0 +1,57 @@
CREATE TABLE IF NOT EXISTS DM_OPERATION_ARCH (
ID INTEGER NOT NULL,
TYPE VARCHAR(20) NOT NULL,
CREATED_TIMESTAMP TIMESTAMP(0) NOT NULL,
RECEIVED_TIMESTAMP TIMESTAMP(0) NULL,
OPERATION_CODE VARCHAR(50) NOT NULL,
INITIATED_BY VARCHAR(100) NULL,
OPERATION_DETAILS BYTEA DEFAULT NULL,
ENABLED BOOLEAN NOT NULL DEFAULT FALSE,
ARCHIVED_AT TIMESTAMP(0) DEFAULT NOW()
);
CREATE INDEX IDX_OPR_ARC ON DM_OPERATION_ARCH(ARCHIVED_AT);
CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING_ARCH (
ID INTEGER NOT NULL,
ENROLMENT_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
STATUS VARCHAR(50) NULL,
CREATED_TIMESTAMP INTEGER NOT NULL,
UPDATED_TIMESTAMP INTEGER NOT NULL,
ARCHIVED_AT TIMESTAMP(0) DEFAULT NOW()
);
CREATE INDEX IDX_EN_OP_MAP_ARCH ON DM_ENROLMENT_OP_MAPPING_ARCH(ARCHIVED_AT);
CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE_ARCH (
ID INT NOT NULL,
ENROLMENT_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
OPERATION_RESPONSE VARCHAR(4096) DEFAULT NULL,
RECEIVED_TIMESTAMP TIMESTAMP(0) NULL,
ARCHIVED_AT TIMESTAMP(0) DEFAULT NOW(),
IS_LARGE_RESPONSE BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE INDEX IDX_OPR_RES_ARCH ON DM_DEVICE_OPERATION_RESPONSE_ARCH(ARCHIVED_AT);
CREATE TABLE DM_DEVICE_OPERATION_RESPONSE_LARGE_ARCH (
ID INT NOT NULL,
OPERATION_RESPONSE BYTEA DEFAULT NULL,
ARCHIVED_AT TIMESTAMP(0) DEFAULT NOW()
);
CREATE INDEX IDX_OPR_RES_LRG_ARCH ON DM_DEVICE_OPERATION_RESPONSE_LARGE_ARCH(ARCHIVED_AT);
CREATE TABLE IF NOT EXISTS DM_NOTIFICATION_ARCH (
NOTIFICATION_ID INTEGER NOT NULL,
DEVICE_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
TENANT_ID INTEGER NOT NULL,
STATUS VARCHAR(10) NULL,
DESCRIPTION VARCHAR(1000) NULL,
ARCHIVED_AT TIMESTAMP(0) DEFAULT NOW()
);
CREATE INDEX IDX_NOT_ARCH ON DM_NOTIFICATION_ARCH(ARCHIVED_AT);

@ -98,6 +98,7 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
OWNER VARCHAR(255) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,
IS_TRANSFERRED BOOLEAN NOT NULL DEFAULT FALSE,
DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL,
TENANT_ID INT NOT NULL,
@ -115,6 +116,13 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING (
PUSH_NOTIFICATION_STATUS VARCHAR(50) NULL,
CREATED_TIMESTAMP INT NOT NULL,
UPDATED_TIMESTAMP INT NOT NULL,
OPERATION_CODE VARCHAR(50) NOT NULL,
INITIATED_BY VARCHAR(100) NULL,
TYPE VARCHAR(20) NOT NULL,
DEVICE_ID INTEGER DEFAULT NULL,
DEVICE_TYPE VARCHAR(300) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES
DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
@ -127,7 +135,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE (
ENROLMENT_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
EN_OP_MAP_ID INTEGER NOT NULL,
OPERATION_RESPONSE LONGBLOB DEFAULT NULL,
OPERATION_RESPONSE VARCHAR(1024) DEFAULT NULL ,
IS_LARGE_RESPONSE BOOLEAN NOT NULL DEFAULT FALSE,
RECEIVED_TIMESTAMP TIMESTAMP NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES
@ -138,6 +147,21 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE (
DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE DM_DEVICE_OPERATION_RESPONSE_LARGE (
ID INTEGER NOT NULL,
OPERATION_RESPONSE LONGBLOB DEFAULT NULL,
OPERATION_ID INTEGER NOT NULL,
EN_OP_MAP_ID INTEGER NOT NULL,
RECEIVED_TIMESTAMP TIMESTAMP NULL,
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
CONSTRAINT fk_dm_device_operation_response_large_mapping FOREIGN KEY (ID)
REFERENCES DM_DEVICE_OPERATION_RESPONSE (ID)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_en_op_map_response_large FOREIGN KEY (EN_OP_MAP_ID)
REFERENCES DM_ENROLMENT_OP_MAPPING (ID)
ON DELETE NO ACTION ON UPDATE NO ACTION
);
-- POLICY RELATED TABLES --
CREATE TABLE IF NOT EXISTS DM_PROFILE (

@ -114,47 +114,11 @@ CREATE TABLE DM_OPERATION (
RECEIVED_TIMESTAMP DATETIME2 NULL,
OPERATION_CODE VARCHAR(50) NOT NULL,
INITIATED_BY VARCHAR(100) NULL,
PRIMARY KEY (ID)
);
IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_CONFIG_OPERATION]') AND TYPE IN (N'U'))
CREATE TABLE DM_CONFIG_OPERATION (
OPERATION_ID INTEGER NOT NULL,
OPERATION_CONFIG VARBINARY(MAX) DEFAULT NULL,
ENABLED BIT NOT NULL DEFAULT 0,
PRIMARY KEY (OPERATION_ID),
CONSTRAINT FK_DM_OPERATION_CONFIG FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_COMMAND_OPERATION]') AND TYPE IN (N'U'))
CREATE TABLE DM_COMMAND_OPERATION (
OPERATION_ID INTEGER NOT NULL,
ENABLED BIT NOT NULL DEFAULT 0,
PRIMARY KEY (OPERATION_ID),
CONSTRAINT FK_DM_OPERATION_COMMAND FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_POLICY_OPERATION]') AND TYPE IN (N'U'))
CREATE TABLE DM_POLICY_OPERATION (
OPERATION_ID INTEGER NOT NULL,
ENABLED INTEGER NOT NULL DEFAULT 0,
OPERATION_DETAILS VARBINARY(MAX) DEFAULT NULL,
PRIMARY KEY (OPERATION_ID),
CONSTRAINT FK_DM_OPERATION_POLICY FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
ENABLED BIT NOT NULL DEFAULT 0,
PRIMARY KEY (ID)
);
IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_PROFILE_OPERATION]') AND TYPE IN (N'U'))
CREATE TABLE DM_PROFILE_OPERATION (
OPERATION_ID INTEGER NOT NULL,
ENABLED INTEGER NOT NULL DEFAULT 0,
OPERATION_DETAILS VARBINARY(MAX) DEFAULT NULL,
PRIMARY KEY (OPERATION_ID),
CONSTRAINT FK_DM_OPERATION_PROFILE FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_ENROLMENT]') AND TYPE IN (N'U'))
CREATE TABLE DM_ENROLMENT (
@ -163,6 +127,7 @@ CREATE TABLE DM_ENROLMENT (
OWNER VARCHAR(255) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,
IS_TRANSFERRED TINYINT NOT NULL DEFAULT 0,
DATE_OF_ENROLMENT DATETIME2 DEFAULT NULL,
DATE_OF_LAST_UPDATE DATETIME2 DEFAULT NULL,
TENANT_ID INTEGER NOT NULL,
@ -205,7 +170,8 @@ CREATE TABLE DM_DEVICE_OPERATION_RESPONSE (
ENROLMENT_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
EN_OP_MAP_ID INTEGER NOT NULL,
OPERATION_RESPONSE VARBINARY(MAX) DEFAULT NULL,
OPERATION_RESPONSE VARCHAR(1024) DEFAULT NULL,
IS_LARGE_RESPONSE BIT NOT NULL DEFAULT 0,
RECEIVED_TIMESTAMP DATETIME2 DEFAULT NULL
PRIMARY KEY (ID),
CONSTRAINT FK_DM_DEVICE_OPERATION_RESP_ENROLMENT FOREIGN KEY (ENROLMENT_ID) REFERENCES
@ -222,6 +188,26 @@ CREATE INDEX IDX_ENID_OPID ON DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID, ENROLME
IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_DM_EN_OP_MAP_RES' AND OBJECT_ID = OBJECT_ID('DM_DEVICE_OPERATION_RESPONSE'))
CREATE INDEX IDX_DM_EN_OP_MAP_RES ON DM_DEVICE_OPERATION_RESPONSE(EN_OP_MAP_ID);
IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_DEVICE_OPERATION_RESPONSE_LARGE]') AND TYPE IN (N'U'))
CREATE TABLE DM_DEVICE_OPERATION_RESPONSE_LARGE (
ID INTEGER IDENTITY(1,1) NOT NULL,
OPERATION_ID INTEGER NOT NULL,
EN_OP_MAP_ID INTEGER NOT NULL,
OPERATION_RESPONSE VARBINARY(MAX) DEFAULT NULL,
RECEIVED_TIMESTAMP DATETIME2 DEFAULT NULL
PRIMARY KEY (ID),
CONSTRAINT FK_DM_DEVICE_OPERATION_RESP_LARGE_OPERATION FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT FK_DM_EN_OP_MAP_RESPONSE_LARGE FOREIGN KEY (EN_OP_MAP_ID) REFERENCES
DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_ENID_OPID_LARGE' AND OBJECT_ID = OBJECT_ID('DM_DEVICE_OPERATION_RESPONSE_LARGE'))
CREATE INDEX IDX_ENID_OPID_LARGE ON DM_DEVICE_OPERATION_RESPONSE_LARGE(OPERATION_ID);
IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_DM_EN_OP_MAP_RES_LARGE' AND OBJECT_ID = OBJECT_ID('DM_DEVICE_OPERATION_RESPONSE_LARGE'))
CREATE INDEX IDX_DM_EN_OP_MAP_RES_LARGE ON DM_DEVICE_OPERATION_RESPONSE_LARGE(EN_OP_MAP_ID);
-- POLICY RELATED TABLES --
IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_PROFILE]') AND TYPE IN (N'U'))

@ -113,6 +113,7 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
OWNER VARCHAR(255) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,
IS_TRANSFERRED BOOLEAN NOT NULL DEFAULT FALSE,
DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL,
TENANT_ID INT NOT NULL,
@ -133,6 +134,13 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING (
PUSH_NOTIFICATION_STATUS VARCHAR(50) NULL,
CREATED_TIMESTAMP INTEGER NOT NULL,
UPDATED_TIMESTAMP INTEGER NOT NULL,
OPERATION_CODE VARCHAR(50) NOT NULL,
INITIATED_BY VARCHAR(100) NULL,
TYPE VARCHAR(20) NOT NULL,
DEVICE_ID INTEGER DEFAULT NULL,
DEVICE_TYPE VARCHAR(300) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0;
PRIMARY KEY (ID),
KEY `fk_dm_device_operation_mapping_operation` (`OPERATION_ID`),
KEY `IDX_DM_ENROLMENT_OP_MAPPING` (`ENROLMENT_ID`,`OPERATION_ID`),
@ -148,25 +156,44 @@ CREATE INDEX IDX_EN_OP_MAPPING_EN_ID ON DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID);
CREATE INDEX IDX_EN_OP_MAPPING_OP_ID ON DM_ENROLMENT_OP_MAPPING(OPERATION_ID);
CREATE INDEX IDX_EN_OP_MAPPING_EN_ID_STATUS ON DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID, STATUS);
CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE (
ID INT(11) NOT NULL AUTO_INCREMENT,
ENROLMENT_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
EN_OP_MAP_ID INTEGER NOT NULL,
OPERATION_RESPONSE LONGBLOB DEFAULT NULL,
RECEIVED_TIMESTAMP TIMESTAMP NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES
DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_en_op_map_response FOREIGN KEY (EN_OP_MAP_ID) REFERENCES
DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
)ENGINE = InnoDB;
CREATE INDEX IDX_ENID_OPID ON DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID, ENROLMENT_ID);
CREATE INDEX IDX_DM_EN_OP_MAP_RES ON DM_DEVICE_OPERATION_RESPONSE(EN_OP_MAP_ID);
CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE
(
ID INT(11) NOT NULL AUTO_INCREMENT,
ENROLMENT_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
EN_OP_MAP_ID INTEGER NOT NULL,
OPERATION_RESPONSE VARCHAR(1024) DEFAULT NULL,
IS_LARGE_RESPONSE BOOLEAN NOT NULL DEFAULT FALSE,
RECEIVED_TIMESTAMP TIMESTAMP NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES
DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_en_op_map_response FOREIGN KEY (EN_OP_MAP_ID) REFERENCES
DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE = InnoDB;
CREATE INDEX IDX_DM_RES_RT ON DM_DEVICE_OPERATION_RESPONSE(RECEIVED_TIMESTAMP);
CREATE INDEX IDX_ENID_OP_ID ON DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID, ENROLMENT_ID);
CREATE INDEX IDX_DM_EN_OP_MAP_ID ON DM_DEVICE_OPERATION_RESPONSE(EN_OP_MAP_ID);
CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE_LARGE
(
ID INT(11) NOT NULL,
OPERATION_RESPONSE LONGBLOB DEFAULT NULL,
OPERATION_ID INTEGER NOT NULL,
EN_OP_MAP_ID INTEGER NOT NULL,
RECEIVED_TIMESTAMP TIMESTAMP NULL,
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
CONSTRAINT fk_dm_device_operation_response_large FOREIGN KEY (ID) REFERENCES
DM_DEVICE_OPERATION_RESPONSE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_en_op_map_response_large FOREIGN KEY (EN_OP_MAP_ID) REFERENCES
DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE = InnoDB;
CREATE INDEX IDX_DM_RES_LRG_RT ON DM_DEVICE_OPERATION_RESPONSE_LARGE(RECEIVED_TIMESTAMP);
CREATE INDEX IDX_DM_EN_OP_MAP_ID ON DM_DEVICE_OPERATION_RESPONSE_LARGE(EN_OP_MAP_ID);
-- POLICY RELATED TABLES ---
@ -451,6 +478,8 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION (
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
)ENGINE = InnoDB;
CREATE INDEX IDX_NOTF_UT ON DM_NOTIFICATION(LAST_UPDATED_TIMESTAMP);
-- END NOTIFICATION TABLES --
CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (

@ -176,6 +176,8 @@ CREATE TABLE DM_OPERATION (
RECEIVED_TIMESTAMP TIMESTAMP(0) NULL,
OPERATION_CODE VARCHAR2(1000) NOT NULL,
INITIATED_BY VARCHAR2(100) NULL,
ENABLED NUMBER(10) DEFAULT 0 NOT NULL,
OPERATION_DETAILS BLOB DEFAULT NULL,
CONSTRAINT PK_DM_OPERATION PRIMARY KEY (ID)
)
/
@ -193,47 +195,14 @@ WHEN (NEW.ID IS NULL)
END;
/
CREATE TABLE DM_CONFIG_OPERATION (
OPERATION_ID NUMBER(10) NOT NULL,
OPERATION_CONFIG BLOB DEFAULT NULL,
ENABLED NUMBER(10) DEFAULT 0 NOT NULL,
CONSTRAINT PK_DM_CONFIG_OPERATION PRIMARY KEY (OPERATION_ID),
CONSTRAINT FK_DM_OPERATION_CONFIG FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID)
)
/
CREATE TABLE DM_COMMAND_OPERATION (
OPERATION_ID NUMBER(10) NOT NULL,
ENABLED NUMBER(10) DEFAULT 0 NOT NULL,
CONSTRAINT PK_DM_COMMAND_OPERATION PRIMARY KEY (OPERATION_ID),
CONSTRAINT FK_DM_OPERATION_COMMAND FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID)
)
/
CREATE TABLE DM_POLICY_OPERATION (
OPERATION_ID NUMBER(10) NOT NULL,
ENABLED NUMBER(10) DEFAULT 0 NOT NULL,
OPERATION_DETAILS BLOB DEFAULT NULL,
CONSTRAINT PK_DM_POLICY_OPERATION PRIMARY KEY (OPERATION_ID),
CONSTRAINT FK_DM_OPERATION_POLICY FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID)
)
/
CREATE TABLE DM_PROFILE_OPERATION (
OPERATION_ID NUMBER(10) NOT NULL,
ENABLED NUMBER(10) DEFAULT 0 NOT NULL,
OPERATION_DETAILS BLOB DEFAULT NULL,
CONSTRAINT PK_DM_PROFILE_OPERATION PRIMARY KEY (OPERATION_ID),
CONSTRAINT FK_DM_OPERATION_PROFILE FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID)
)
/
CREATE TABLE DM_ENROLMENT (
ID NUMBER(10) NOT NULL,
DEVICE_ID NUMBER(10) NOT NULL,
OWNER VARCHAR2(255) NOT NULL,
OWNERSHIP VARCHAR2(45) DEFAULT NULL,
STATUS VARCHAR2(50) NULL,
IS_TRANSFERRED NUMBER(1) DEFAULT 0 NOT NULL,
DATE_OF_ENROLMENT TIMESTAMP(0) DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP(0) DEFAULT NULL,
TENANT_ID NUMBER(10) NOT NULL,

Loading…
Cancel
Save