private boolean register(String deviceId, String name) {
   try {
     DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
     deviceIdentifier.setId(deviceId);
     deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE);
     if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
       return false;
     }
     Device device = new Device();
     device.setDeviceIdentifier(deviceId);
     EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
     enrolmentInfo.setDateOfEnrolment(new Date().getTime());
     enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
     enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
     enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
     device.setName(name);
     device.setType(VirtualFireAlarmConstants.DEVICE_TYPE);
     enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
     device.setEnrolmentInfo(enrolmentInfo);
     return APIUtil.getDeviceManagementService().enrollDevice(device);
   } catch (DeviceManagementException e) {
     log.error(e.getMessage(), e);
     return false;
   }
 }
 @Override
 public List<Application> getApplicationListForDevice(DeviceIdentifier deviceId)
     throws ApplicationManagementException {
   Device device;
   try {
     int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
     DeviceManagementDAOFactory.openConnection();
     device = deviceDAO.getDevice(deviceId, tenantId);
     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");
       }
       return null;
     }
     return applicationDAO.getInstalledApplications(device.getId());
   } catch (DeviceManagementDAOException e) {
     throw new ApplicationManagementException(
         "Error occurred while fetching the Application List of '"
             + deviceId.getType()
             + "' device carrying the identifier'"
             + deviceId.getId(),
         e);
   } catch (SQLException e) {
     throw new ApplicationManagementException(
         "Error occurred while opening a connection to the data source", e);
   } finally {
     DeviceManagementDAOFactory.closeConnection();
   }
 }
  /**
   * Create a new device identifier from Device object.
   *
   * @param device device which is to be retrieved type and id
   * @return created device identifier
   */
  private static DeviceIdentifier getDeviceIdentifierByDevice(
      org.wso2.carbon.device.mgt.common.Device device) {
    DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
    deviceIdentifier.setId(device.getDeviceIdentifier());
    deviceIdentifier.setType(device.getType());

    return deviceIdentifier;
  }
 public void testGetOperations() {
   try {
     // TODO:- operationManager.getOperations is not implemented
     DeviceIdentifier deviceId = new DeviceIdentifier();
     deviceId.setId("4892813d-0b18-4a02-b7b1-61775257400e");
     deviceId.setType("android");
     List<? extends Operation> operations = operationManager.getOperations(deviceId);
     Assert.assertNotNull(operations);
     boolean notEmpty = operations.size() > 0;
     Assert.assertTrue(notEmpty);
   } catch (OperationManagementException e) {
     e.printStackTrace();
   }
 }
  @Override
  public void delegate() throws PolicyDelegationException {

    for (Device device : devices) {
      DeviceIdentifier identifier = new DeviceIdentifier();
      identifier.setId(device.getDeviceIdentifier());
      identifier.setType(device.getType());

      Policy policy = this.getEffectivePolicy(identifier);

      if (policy != null) {
        List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
        deviceIdentifiers.add(identifier);
        this.addPolicyOperation(deviceIdentifiers, policy);
      }
    }
  }
  @Override
  public Activity installApplicationForUsers(Operation operation, List<String> userNameList)
      throws ApplicationManagementException {

    String userName = null;
    try {
      List<Device> deviceList;
      List<DeviceIdentifier> deviceIdentifierList = new ArrayList<>();
      DeviceIdentifier deviceIdentifier;

      for (String user : userNameList) {
        userName = user;
        deviceList =
            DeviceManagementDataHolder.getInstance()
                .getDeviceManagementProvider()
                .getDevicesOfUser(user);
        for (Device device : deviceList) {
          deviceIdentifier = new DeviceIdentifier();
          deviceIdentifier.setId(Integer.toString(device.getId()));
          deviceIdentifier.setType(device.getType());

          deviceIdentifierList.add(deviceIdentifier);
        }
      }
      // TODO: Fix this properly later adding device type to be passed in when the task manage
      // executes "addOperations()"
      String type = null;
      if (deviceIdentifierList.size() > 0) {
        type = deviceIdentifierList.get(0).getType();
      }

      return DeviceManagementDataHolder.getInstance()
          .getDeviceManagementProvider()
          .addOperation(type, operation, deviceIdentifierList);
    } catch (InvalidDeviceException e) {
      throw new ApplicationManagementException("Invalid DeviceIdentifiers found.", e);
    } catch (DeviceManagementException e) {
      throw new ApplicationManagementException(
          "Error in get devices for user: "******" in app installation", e);

    } catch (OperationManagementException e) {
      throw new ApplicationManagementException("Error in add operation at app installation", e);
    }
  }
  @Test
  public void testAddOperation() throws Exception {
    CommandOperation op = new CommandOperation();
    op.setEnabled(true);
    op.setType(Operation.Type.COMMAND);
    op.setCode("OPCODE1");

    List<DeviceIdentifier> deviceIds = new ArrayList<DeviceIdentifier>();
    DeviceIdentifier deviceId = new DeviceIdentifier();
    deviceId.setId("4892813d-0b18-4a02-b7b1-61775257400e");
    deviceId.setType("android");
    deviceIds.add(deviceId);

    try {
      boolean isAdded = operationManager.addOperation(op, deviceIds);
      Assert.assertTrue(isAdded);
    } catch (OperationManagementException e) {
      e.printStackTrace();
      throw new Exception(e);
    }
  }
  @Override
  public void updateApplicationListInstalledInDevice(
      DeviceIdentifier deviceIdentifier, List<Application> applications)
      throws ApplicationManagementException {
    List<Application> installedAppList = getApplicationListForDevice(deviceIdentifier);
    try {
      int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
      DeviceManagementDAOFactory.beginTransaction();
      Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);

      if (log.isDebugEnabled()) {
        log.debug("Device:" + device.getId() + ":identifier:" + deviceIdentifier.getId());
      }

      if (log.isDebugEnabled()) {
        log.debug("num of apps installed:" + installedAppList.size());
      }
      List<Application> appsToAdd = new ArrayList<>();
      List<Integer> appIdsToRemove = new ArrayList<>(installedAppList.size());

      for (Application installedApp : installedAppList) {
        if (!applications.contains(installedApp)) {
          if (log.isDebugEnabled()) {
            log.debug("Remove app Id:" + installedApp.getId());
          }
          appIdsToRemove.add(installedApp.getId());
        }
      }
      applicationMappingDAO.removeApplicationMapping(device.getId(), appIdsToRemove, tenantId);
      Application installedApp;
      List<Integer> applicationIds = new ArrayList<>();

      for (Application application : applications) {
        if (!installedAppList.contains(application)) {
          installedApp =
              applicationDAO.getApplication(
                  application.getApplicationIdentifier(), application.getVersion(), tenantId);
          if (installedApp == null) {
            appsToAdd.add(application);
          } else {
            applicationIds.add(installedApp.getId());
          }
        }
      }
      if (log.isDebugEnabled()) {
        log.debug("num of apps add:" + appsToAdd.size());
      }
      applicationIds.addAll(applicationDAO.addApplications(appsToAdd, tenantId));

      if (log.isDebugEnabled()) {
        log.debug("num of app Ids:" + applicationIds.size());
      }
      applicationMappingDAO.addApplicationMappings(device.getId(), applicationIds, tenantId);

      if (log.isDebugEnabled()) {
        log.debug("num of remove app Ids:" + appIdsToRemove.size());
      }

      DeviceManagementDAOFactory.commitTransaction();
    } catch (DeviceManagementDAOException e) {
      DeviceManagementDAOFactory.rollbackTransaction();
      throw new ApplicationManagementException(
          "Error occurred saving application list to the device", e);
    } catch (TransactionManagementException e) {
      throw new ApplicationManagementException("Error occurred while initializing transaction", e);
    } finally {
      DeviceManagementDAOFactory.closeConnection();
    }
  }
  /**
   * @param applicationOperationAction holds the information needs to perform an action on mdm.
   * @throws MobileApplicationException
   */
  public String performAction(ApplicationOperationAction applicationOperationAction)
      throws MobileApplicationException {
    if (log.isDebugEnabled()) {
      log.debug(
          applicationOperationAction.getAction()
              + " action is triggered for "
              + applicationOperationAction.getType()
              + ".");
    }

    Operation operation = null;
    List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
    List<org.wso2.carbon.device.mgt.common.Device> deviceList;
    if (MDMAppConstants.USER.equals(applicationOperationAction.getType())) {
      String userName = null;
      try {
        for (String param : applicationOperationAction.getParams()) {
          userName = param;

          deviceList =
              MDMServiceAPIUtils.getDeviceManagementService(
                      applicationOperationAction.getTenantId())
                  .getDevicesOfUser(userName);

          for (org.wso2.carbon.device.mgt.common.Device device : deviceList) {
            deviceIdentifiers.add(getDeviceIdentifierByDevice(device));
          }
        }
      } catch (DeviceManagementException devEx) {
        String errorMsg =
            "Error occurred fetch device for user " + userName + " at app installation";
        logError(errorMsg, devEx);
        throw new MobileApplicationException(errorMsg, devEx);
      }
    } else if (MDMAppConstants.ROLE.equals(applicationOperationAction.getType())) {
      String userRole = null;
      try {
        for (String param : applicationOperationAction.getParams()) {
          userRole = param;

          deviceList =
              MDMServiceAPIUtils.getDeviceManagementService(
                      applicationOperationAction.getTenantId())
                  .getAllDevicesOfRole(userRole);

          for (org.wso2.carbon.device.mgt.common.Device device : deviceList) {
            deviceIdentifiers.add(getDeviceIdentifierByDevice(device));
          }
        }
      } catch (DeviceManagementException devMgtEx) {
        String errorMsg =
            "Error occurred fetch device for user role " + userRole + " at app installation";
        logError(errorMsg, devMgtEx);
        throw new MobileApplicationException(errorMsg, devMgtEx);
      }

    } else if (MDMAppConstants.DEVICE.equals(applicationOperationAction.getType())) {
      DeviceIdentifier deviceIdentifier;
      for (String param : applicationOperationAction.getParams()) {
        deviceIdentifier = new DeviceIdentifier();
        if (isValidJSON(param)) {
          JSONParser parser = new JSONParser();
          try {
            JSONObject parsedObj = (JSONObject) parser.parse(param);
            deviceIdentifier.setId((String) parsedObj.get(MDMAppConstants.ID));
            deviceIdentifier.setType((String) parsedObj.get(MDMAppConstants.TYPE));
            deviceIdentifiers.add(deviceIdentifier);
          } catch (ParseException e) {
            logError("Device Identifier is not valid json object.", e);
            throw new MobileApplicationException(e);
          }
        }
      }
    } else {
      throw new IllegalStateException("invalid type is received from app store.");
    }
    App app = applicationOperationAction.getApp();
    MobileApp mobileApp = new MobileApp();
    mobileApp.setId(app.getId());
    mobileApp.setType(MobileAppTypes.valueOf(app.getType().toUpperCase()));
    mobileApp.setAppIdentifier(app.getAppIdentifier());
    mobileApp.setIconImage(app.getIconImage());
    mobileApp.setIdentifier(app.getIdentifier());
    mobileApp.setLocation(app.getLocation());
    mobileApp.setName(app.getName());
    mobileApp.setPackageName(app.getPackageName());
    mobileApp.setPlatform(app.getPlatform());
    mobileApp.setVersion(app.getVersion());
    Properties properties = new Properties();

    if (MDMAppConstants.IOS.equals(app.getPlatform())) {
      if (MDMAppConstants.ENTERPRISE.equals(app.getType())) {
        properties.put(MDMAppConstants.IOSConstants.IS_REMOVE_APP, true);
        properties.put(MDMAppConstants.IOSConstants.IS_PREVENT_BACKUP, true);
      } else if (MDMAppConstants.IOSConstants.PUBLIC.equals(app.getType())) {
        properties.put(MDMAppConstants.IOSConstants.I_TUNES_ID, app.getIdentifier());
        properties.put(MDMAppConstants.IOSConstants.IS_REMOVE_APP, true);
        properties.put(MDMAppConstants.IOSConstants.IS_PREVENT_BACKUP, true);
      } else if (MDMAppConstants.WEBAPP.equals(app.getType())) {
        properties.put(MDMAppConstants.IOSConstants.LABEL, app.getName());
        properties.put(MDMAppConstants.IOSConstants.IS_REMOVE_APP, true);
      }
    } else if (MDMAppConstants.WEBAPP.equals(app.getPlatform())) {
      properties.put(MDMAppConstants.IOSConstants.LABEL, app.getName());
      properties.put(MDMAppConstants.IOSConstants.IS_REMOVE_APP, true);
    }
    mobileApp.setProperties(properties);
    try {
      for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
        if (deviceIdentifier.getType().equalsIgnoreCase(Platform.ANDROID.toString())) {
          if (MDMAppConstants.INSTALL.equals(applicationOperationAction.getAction())) {
            operation =
                AndroidApplicationOperationUtil.createInstallAppOperation(
                    mobileApp, applicationOperationAction.getSchedule());
          } else if (MDMAppConstants.UPDATE.equals(applicationOperationAction.getAction())) {
            operation =
                AndroidApplicationOperationUtil.createUpdateAppOperation(
                    mobileApp, applicationOperationAction.getSchedule());

          } else {
            operation =
                AndroidApplicationOperationUtil.createAppUninstallOperation(
                    mobileApp, applicationOperationAction.getSchedule());
          }
        } else if (deviceIdentifier.getType().equalsIgnoreCase(Platform.IOS.toString())) {
          if (MDMAppConstants.INSTALL.equals(applicationOperationAction.getAction())) {
            operation = IOSApplicationOperationUtil.createInstallAppOperation(mobileApp);
          } else {
            operation = IOSApplicationOperationUtil.createAppUninstallOperation(mobileApp);
          }
        }
        Activity activity =
            MDMServiceAPIUtils.getAppManagementService(applicationOperationAction.getTenantId())
                .installApplicationForDevices(operation, deviceIdentifiers);

        return activity.getActivityId();
      }
    } catch (DeviceApplicationException mdmExce) {
      logError("Error in creating operation object using app.", mdmExce);
      throw new MobileApplicationException(mdmExce.getMessage());
    } catch (ApplicationManagementException appMgtExce) {
      logError("Error in app installation.", appMgtExce);
      throw new MobileApplicationException(appMgtExce.getErrorMessage());
    }
    return null;
  }