@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();
   }
 }
  public static MobileDevice convertToMobileDevice(Device device) {
    MobileDevice mobileDevice = null;
    if (device != null) {
      mobileDevice = new MobileDevice();
      mobileDevice.setMobileDeviceId(device.getDeviceIdentifier());
      mobileDevice.setImei(getPropertyValue(device, MOBILE_DEVICE_IMEI));
      mobileDevice.setImsi(getPropertyValue(device, MOBILE_DEVICE_IMSI));
      mobileDevice.setModel(getPropertyValue(device, MOBILE_DEVICE_MODEL));
      mobileDevice.setOsVersion(getPropertyValue(device, MOBILE_DEVICE_OS_VERSION));
      mobileDevice.setVendor(getPropertyValue(device, MOBILE_DEVICE_VENDOR));
      mobileDevice.setLatitude(getPropertyValue(device, MOBILE_DEVICE_LATITUDE));
      mobileDevice.setLongitude(getPropertyValue(device, MOBILE_DEVICE_LONGITUDE));
      mobileDevice.setSerial(getPropertyValue(device, MOBILE_DEVICE_SERIAL));
      mobileDevice.setOsBuildDate(getPropertyValue(device, MOBILE_DEVICE_OS_BUILD_DATE));

      if (device.getProperties() != null) {
        Map<String, String> deviceProperties = new HashMap<String, String>();
        for (Device.Property deviceProperty : device.getProperties()) {
          deviceProperties.put(deviceProperty.getName(), deviceProperty.getValue());
        }

        mobileDevice.setDeviceProperties(deviceProperties);
      } else {
        mobileDevice.setDeviceProperties(new HashMap<String, String>());
      }
    }
    return mobileDevice;
  }
  public static Device convertToDevice(MobileDevice mobileDevice) {
    Device device = null;
    if (mobileDevice != null) {
      device = new Device();
      List<Device.Property> propertyList = new ArrayList<Device.Property>();
      propertyList.add(getProperty(MOBILE_DEVICE_IMEI, mobileDevice.getImei()));
      propertyList.add(getProperty(MOBILE_DEVICE_IMSI, mobileDevice.getImsi()));
      propertyList.add(getProperty(MOBILE_DEVICE_MODEL, mobileDevice.getModel()));
      propertyList.add(getProperty(MOBILE_DEVICE_OS_VERSION, mobileDevice.getOsVersion()));
      propertyList.add(getProperty(MOBILE_DEVICE_OS_BUILD_DATE, mobileDevice.getOsBuildDate()));
      propertyList.add(getProperty(MOBILE_DEVICE_VENDOR, mobileDevice.getVendor()));
      if (mobileDevice.getLatitude() != null) {
        propertyList.add(getProperty(MOBILE_DEVICE_LATITUDE, mobileDevice.getLatitude()));
      }
      if (mobileDevice.getLongitude() != null) {
        propertyList.add(getProperty(MOBILE_DEVICE_LONGITUDE, mobileDevice.getLongitude()));
      }
      propertyList.add(getProperty(MOBILE_DEVICE_SERIAL, mobileDevice.getSerial()));

      if (mobileDevice.getDeviceProperties() != null) {
        for (Map.Entry<String, String> deviceProperty :
            mobileDevice.getDeviceProperties().entrySet()) {
          propertyList.add(getProperty(deviceProperty.getKey(), deviceProperty.getValue()));
        }
      }

      device.setProperties(propertyList);
      device.setDeviceIdentifier(mobileDevice.getMobileDeviceId());
    }
    return device;
  }
 public boolean addDevice(Device device) throws DigitalDisplayDeviceMgtPluginException {
   boolean status = false;
   Connection conn = null;
   PreparedStatement stmt = null;
   try {
     conn = DigitalDisplayDAO.getConnection();
     String createDBQuery =
         "INSERT INTO DIGITAL_DISPLAY_DEVICE(DIGITAL_DISPLAY_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
     stmt = conn.prepareStatement(createDBQuery);
     stmt.setString(1, device.getDeviceIdentifier());
     stmt.setString(2, device.getName());
     int rows = stmt.executeUpdate();
     if (rows > 0) {
       status = true;
       if (log.isDebugEnabled()) {
         log.debug(
             "Digital Display device "
                 + device.getDeviceIdentifier()
                 + " data has been"
                 + " added to the Digital Display database.");
       }
     }
   } catch (SQLException e) {
     String msg =
         "Error occurred while adding the Digital Display device '"
             + device.getDeviceIdentifier()
             + "' to the Digital Display db.";
     log.error(msg, e);
     throw new DigitalDisplayDeviceMgtPluginException(msg, e);
   } finally {
     DigitalDisplayUtils.cleanupResources(stmt, null);
   }
   return status;
 }
 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;
   }
 }
 public Device getDevice(String iotDeviceId) throws DigitalDisplayDeviceMgtPluginException {
   Connection conn = null;
   PreparedStatement stmt = null;
   Device device = null;
   ResultSet resultSet = null;
   try {
     conn = DigitalDisplayDAO.getConnection();
     String selectDBQuery =
         "SELECT DIGITAL_DISPLAY_DEVICE_ID, DEVICE_NAME"
             + " FROM DIGITAL_DISPLAY_DEVICE WHERE DIGITAL_DISPLAY_DEVICE_ID = ?";
     stmt = conn.prepareStatement(selectDBQuery);
     stmt.setString(1, iotDeviceId);
     resultSet = stmt.executeQuery();
     if (resultSet.next()) {
       device = new Device();
       device.setName(resultSet.getString(DigitalDisplayConstants.DEVICE_PLUGIN_DEVICE_NAME));
       if (log.isDebugEnabled()) {
         log.debug(
             "Digital Display device "
                 + iotDeviceId
                 + " data has been fetched from "
                 + "Digital Display database.");
       }
     }
   } catch (SQLException e) {
     String msg = "Error occurred while fetching Digital Display device : '" + iotDeviceId + "'";
     log.error(msg, e);
     throw new DigitalDisplayDeviceMgtPluginException(msg, e);
   } finally {
     DigitalDisplayUtils.cleanupResources(stmt, resultSet);
     DigitalDisplayDAO.closeConnection();
   }
   return device;
 }
  public List<Device> getAllDevices() throws DigitalDisplayDeviceMgtPluginException {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet resultSet = null;
    Device iotDevice;
    List<Device> iotDevices = new ArrayList<Device>();

    try {
      conn = DigitalDisplayDAO.getConnection();
      String selectDBQuery =
          "SELECT DIGITAL_DISPLAY_DEVICE_ID, DEVICE_NAME FROM DIGITAL_DISPLAY_DEVICE";
      stmt = conn.prepareStatement(selectDBQuery);
      resultSet = stmt.executeQuery();
      while (resultSet.next()) {
        iotDevice = new Device();
        iotDevice.setDeviceIdentifier(
            resultSet.getString(DigitalDisplayConstants.DEVICE_PLUGIN_DEVICE_ID));
        iotDevice.setName(resultSet.getString(DigitalDisplayConstants.DEVICE_PLUGIN_DEVICE_NAME));
        iotDevices.add(iotDevice);
      }
      if (log.isDebugEnabled()) {
        log.debug("All Digital Display device details have fetched from Digital Display database.");
      }
      return iotDevices;
    } catch (SQLException e) {
      String msg = "Error occurred while fetching all Digital Display device data'";
      log.error(msg, e);
      throw new DigitalDisplayDeviceMgtPluginException(msg, e);
    } finally {
      DigitalDisplayUtils.cleanupResources(stmt, resultSet);
      DigitalDisplayDAO.closeConnection();
    }
  }
 public boolean updateDevice(Device device) throws DigitalDisplayDeviceMgtPluginException {
   boolean status = false;
   Connection conn = null;
   PreparedStatement stmt = null;
   try {
     conn = DigitalDisplayDAO.getConnection();
     String updateDBQuery =
         "UPDATE DIGITAL_DISPLAY_DEVICE SET  DEVICE_NAME = ? WHERE DIGITAL_DISPLAY_DEVICE_ID = ?";
     stmt = conn.prepareStatement(updateDBQuery);
     stmt.setString(1, device.getName());
     stmt.setString(2, device.getDeviceIdentifier());
     int rows = stmt.executeUpdate();
     if (rows > 0) {
       status = true;
       if (log.isDebugEnabled()) {
         log.debug(
             "Digital Display device "
                 + device.getDeviceIdentifier()
                 + " data has been"
                 + " modified.");
       }
     }
   } catch (SQLException e) {
     String msg =
         "Error occurred while modifying the Digital Display device '"
             + device.getDeviceIdentifier()
             + "' data.";
     log.error(msg, e);
     throw new DigitalDisplayDeviceMgtPluginException(msg, e);
   } finally {
     DigitalDisplayUtils.cleanupResources(stmt, null);
   }
   return status;
 }
  /**
   * 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;
  }
 private static String getPropertyValue(Device device, String property) {
   if (device != null && device.getProperties() != null) {
     for (Device.Property prop : device.getProperties()) {
       if (property.equals(prop.getName())) {
         return prop.getValue();
       }
     }
   }
   return null;
 }
  public PolicyEnforcementDelegatorImpl(List<Device> devices) {

    log.info("Policy re-enforcing stared due to change of the policies.");

    if (log.isDebugEnabled()) {
      for (Device device : devices) {
        log.debug(
            "Policy re-enforcing for device :"
                + device.getDeviceIdentifier()
                + " - Type : "
                + device.getType());
      }
    }
    this.devices = devices;
  }
  /**
   * @param applicationOperationDevice holds the information needs to retrieve device list.
   * @return List of devices
   * @throws MobileApplicationException
   */
  public List<Device> getDevices(ApplicationOperationDevice applicationOperationDevice)
      throws MobileApplicationException {

    List<Device> devices;
    try {
      List<org.wso2.carbon.device.mgt.common.Device> deviceList =
          MDMServiceAPIUtils.getDeviceManagementService(applicationOperationDevice.getTenantId())
              .getDevicesOfUser(applicationOperationDevice.getCurrentUser().getUsername());
      devices = new ArrayList<>(deviceList.size());
      if (log.isDebugEnabled()) {
        log.debug("device list got from mdm " + deviceList.toString());
      }
      for (org.wso2.carbon.device.mgt.common.Device commonDevice : deviceList) {
        if (MDMAppConstants.ACTIVE.equals(
            commonDevice.getEnrolmentInfo().getStatus().toString().toLowerCase())) {
          Device device = new Device();
          org.wso2.carbon.appmgt.mobile.beans.DeviceIdentifier deviceIdentifier =
              new org.wso2.carbon.appmgt.mobile.beans.DeviceIdentifier();
          deviceIdentifier.setId(commonDevice.getDeviceIdentifier());
          deviceIdentifier.setType(commonDevice.getType());
          device.setDeviceIdentifier(deviceIdentifier);
          device.setName(commonDevice.getName());
          device.setModel(commonDevice.getName());
          device.setType(MDMAppConstants.MOBILE_DEVICE);
          String imgUrl;
          if (MDMAppConstants.ANDROID.equalsIgnoreCase(commonDevice.getType())) {
            imgUrl =
                String.format(
                    applicationOperationDevice.getConfigParams().get(MDMAppConstants.IMAGE_URL),
                    MDMAppConstants.NEXUS);
          } else if (MDMAppConstants.IOS.equalsIgnoreCase(commonDevice.getType())) {
            imgUrl =
                String.format(
                    applicationOperationDevice.getConfigParams().get(MDMAppConstants.IMAGE_URL),
                    MDMAppConstants.IPHONE);
          } else {
            imgUrl =
                String.format(
                    applicationOperationDevice.getConfigParams().get(MDMAppConstants.IMAGE_URL),
                    MDMAppConstants.NONE);
          }
          device.setImage(imgUrl);
          device.setPlatform(commonDevice.getType());
          devices.add(device);
        }
      }
    } catch (DeviceManagementException e) {
      logError("Error While retrieving Device List.", e);
      throw new MobileApplicationException(e.getMessage());
    }
    return devices;
  }
  @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);
    }
  }
  /**
   * {@inheritDoc} VirtualFirealarm device-type specific implementation to process incoming
   * messages. This is the specific method signature of the overloaded "processIncomingMessage"
   * method that gets called from the messageArrived() callback of the "MQTTTransportHandler".
   */
  @Override
  public void processIncomingMessage(MqttMessage mqttMessage, String... messageParams) {
    if (messageParams.length != 0) {
      // owner and the deviceId are extracted from the MQTT topic to which the message was received.
      // <Topic> = [ServerName/Owner/DeviceType/DeviceId/"publisher"]
      String topic = messageParams[0];
      String[] topicParams = topic.split("/");
      String deviceId = topicParams[2];
      if (log.isDebugEnabled()) {
        log.debug("Received MQTT message for: [DEVICE.ID-" + deviceId + "]");
      }

      String actualMessage;
      try {
        // the hash-code of the deviceId is used as the alias for device certificates during SCEP
        // enrollment.
        // hence, the same is used here to fetch the device-specific-certificate from the key store.
        PublicKey clientPublicKey = VirtualFireAlarmServiceUtils.getDevicePublicKey(deviceId);
        PrivateKey serverPrivateKey = SecurityManager.getServerPrivateKey();

        // the MQTT-messages from VirtualFireAlarm devices are in the form {"Msg":<MESSAGE>,
        // "Sig":<SIGNATURE>}
        actualMessage =
            VirtualFireAlarmServiceUtils.extractMessageFromPayload(
                mqttMessage.toString(), serverPrivateKey, clientPublicKey);
        if (log.isDebugEnabled()) {
          log.debug("MQTT: Received Message [" + actualMessage + "] topic: [" + topic + "]");
        }

        if (actualMessage.contains("PUBLISHER")) {
          float temperature = Float.parseFloat(actualMessage.split(":")[2]);
          try {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            DeviceManagementProviderService deviceManagementProviderService =
                (DeviceManagementProviderService)
                    ctx.getOSGiService(DeviceManagementProviderService.class, null);
            if (deviceManagementProviderService != null) {
              DeviceIdentifier identifier =
                  new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE);
              Device device = deviceManagementProviderService.getDevice(identifier);
              if (device != null) {
                String owner = device.getEnrolmentInfo().getOwner();
                ctx.setTenantDomain(MultitenantUtils.getTenantDomain(owner), true);
                ctx.setUsername(owner);
                if (!VirtualFireAlarmServiceUtils.publishToDAS(deviceId, temperature)) {
                  log.error("MQTT Subscriber: Publishing data to DAS failed.");
                }
              }
            }
          } catch (DeviceManagementException e) {
            log.error(
                "Failed to retreive the device managment service for device type "
                    + VirtualFireAlarmConstants.DEVICE_TYPE,
                e);
          } finally {
            PrivilegedCarbonContext.endTenantFlow();
          }
          if (log.isDebugEnabled()) {
            log.debug("MQTT Subscriber: Published data to DAS successfully.");
          }

        } else if (actualMessage.contains("TEMPERATURE")) {
          String temperatureValue = actualMessage.split(":")[1];
        }
      } catch (VirtualFireAlarmException e) {
        String errorMsg =
            "CertificateManagementService failure oo Signature-Verification/Decryption was unsuccessful.";
        log.error(errorMsg, e);
      }
    } else {
      String errorMsg =
          "MQTT message ["
              + mqttMessage.toString()
              + "] was received without the topic information.";
      log.warn(errorMsg);
    }
  }
  @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();
    }
  }