private List<Add> appendAddConfiguration(Operation operation) throws WindowsOperationException {

    List<Add> addList = new ArrayList<Add>();
    Gson gson = new Gson();

    if (SyncmlCommandType.WIFI.getValue().equals(operation.getCode())) {

      Add add = new Add();

      String operationCode = operation.getCode();

      Wifi wifiObject = gson.fromJson((String) operation.getPayLoad(), Wifi.class);

      String data =
          "&lt;?xml version=&quot;1.0&quot;?&gt;&lt;WLANProfile"
              + "xmlns=&quot;http://www.microsoft.com/networking/WLAN/profile/v1&quot;&gt;&lt;name&gt;"
              + wifiObject.getNetworkName()
              + "&lt;/name&gt;&lt;SSIDConfig&gt;&lt;SSID&gt;&lt;name&gt;"
              + wifiObject.getSsid()
              + "&lt;/name&gt;&lt;/SSID&gt;&lt;/SSIDConfig&gt;&lt;connectionType&gt;"
              + wifiObject.getConnectionType()
              + "&lt;/connectionType&gt;&lt;connectionMode&gt;"
              + wifiObject.getConnectionMode()
              + "&lt;/connectionMode&gt;&lt;MSM&gt;&lt;security&gt;&lt;"
              + "authEncryption&gt;&lt;authentication&gt;"
              + wifiObject.getAuthentication()
              + "&lt;/authentication&gt;&lt;encryption&gt;"
              + wifiObject.getEncryption()
              + "&lt;/encryption&gt;&lt;/authEncryption&gt;&lt;sharedKey&gt;&lt;keyType&gt;"
              + wifiObject.getKeyType()
              + "&lt;/keyType&gt;&lt;protected&gt;"
              + wifiObject.getProtection()
              + "&lt;/protected&gt;&lt;keyMaterial&gt;"
              + wifiObject.getKeyMaterial()
              + "&lt;/keyMaterial&gt;&lt;/sharedKey&gt;&lt;/security&gt;&lt;/MSM&gt;&lt;/WLANProfile&gt;";

      Meta meta = new Meta();
      meta.setFormat("chr");
      List<Item> items = new ArrayList<Item>();

      for (Configure configure : Configure.values()) {
        if (operationCode != null && operationCode.equals(configure.name())) {
          Target target = new Target();
          target.setLocURI(configure.getCode());
          items.get(0).setTarget(target);
        }
      }
      items.get(0).setMeta(meta);
      items.get(0).setData(data);

      add.setCommandId(301);
      add.setItems(items);
      addList.add(add);
      return addList;
    }
    return null;
  }
 public static Operation convertMobileOperationToOperation(MobileOperation mobileOperation) {
   Operation operation = new Operation();
   Properties properties = new Properties();
   operation.setCode(mobileOperation.getFeatureCode());
   for (MobileOperationProperty mobileOperationProperty : mobileOperation.getProperties()) {
     properties.put(mobileOperationProperty.getProperty(), mobileOperationProperty.getValue());
   }
   operation.setProperties(properties);
   return operation;
 }
  private void appendOperations(SyncmlBody syncmlBody) throws WindowsOperationException {
    Get getElement = new Get();
    List<Item> itemsGet = new ArrayList<Item>();

    Exec execElement = new Exec();
    List<Item> itemsExec = new ArrayList<Item>();

    Atomic atomicElement = new Atomic();
    List<Add> addsAtomic = new ArrayList<Add>();

    if (operations != null) {
      for (int x = 0; x < operations.size(); x++) {
        Operation operation = operations.get(x);
        Operation.Type type = operation.getType();
        switch (type) {
          case CONFIG:
            List<Add> addConfig = appendAddConfiguration(operation);
            for (Add addConfiguration : addConfig) {
              addsAtomic.add(addConfiguration);
            }
            break;
          case MESSAGE:;
            break;
          case INFO:
            Item itemGet = appendGetInfo(operation);
            itemsGet.add(itemGet);
            break;
          case COMMAND:
            Item itemExec = appendExecInfo(operation);
            itemsExec.add(itemExec);
            break;
          default:
            throw new WindowsOperationException("Operation with no type found");
        }
      }
    }

    if (!itemsGet.isEmpty()) {
      getElement.setCommandId(75);
      getElement.setItems(itemsGet);
    }

    if (!itemsExec.isEmpty()) {
      execElement.setCommandId(5);
      execElement.setItems(itemsExec);
    }

    if (!addsAtomic.isEmpty()) {
      atomicElement.setCommandId(300);
      atomicElement.setAdds(addsAtomic);
    }

    syncmlBody.setGet(getElement);
    syncmlBody.setExec(execElement);
  }
  /**
   * Update operation statuses.
   *
   * @param deviceId specific device Id.
   * @param operations operation list to be update.
   * @throws OperationManagementException
   */
  public void updateOperations(
      String deviceId,
      List<? extends org.wso2.carbon.device.mgt.common.operation.mgt.Operation> operations)
      throws OperationManagementException {

    for (Operation operation : operations) {
      WindowsAPIUtils.updateOperation(deviceId, operation);
      if (log.isDebugEnabled()) {
        log.debug("Updating operation '" + operation.toString() + "'");
      }
    }
  }
 public static MobileOperation convertToMobileOperation(Operation operation) {
   MobileOperation mobileOperation = new MobileOperation();
   MobileOperationProperty operationProperty;
   List<MobileOperationProperty> properties = new LinkedList<MobileOperationProperty>();
   mobileOperation.setFeatureCode(operation.getCode());
   mobileOperation.setCreatedDate(new Date().getTime());
   Properties operationProperties = operation.getProperties();
   for (String key : operationProperties.stringPropertyNames()) {
     operationProperty = new MobileOperationProperty();
     operationProperty.setProperty(key);
     operationProperty.setValue(operationProperties.getProperty(key));
     properties.add(operationProperty);
   }
   mobileOperation.setProperties(properties);
   return mobileOperation;
 }
  /**
   * * Update the status of the DataWipe operation.
   *
   * @param status Status of the data wipe.
   * @param syncmlDocument Parsed syncml payload from the syncml engine.
   * @param deviceIdentifier specific device id to be wiped.
   * @throws OperationManagementException
   * @throws DeviceManagementException
   */
  public void dataWipe(
      StatusTag status, SyncmlDocument syncmlDocument, DeviceIdentifier deviceIdentifier)
      throws OperationManagementException, DeviceManagementException {

    if ((Constants.SyncMLResponseCodes.ACCEPTED.equals(status.getData()))) {
      pendingDataOperations =
          WindowsAPIUtils.getDeviceManagementService()
              .getOperationsByDeviceAndStatus(deviceIdentifier, Operation.Status.PENDING);
      for (Operation operation : pendingDataOperations) {

        if ((OperationCode.Command.WIPE_DATA.equals(operation.getCode()))
            && (operation.getId() == status.getCommandReference())) {
          operation.setStatus(Operation.Status.COMPLETED);
          updateOperations(
              syncmlDocument.getHeader().getSource().getLocURI(), pendingDataOperations);
        }
      }
    }
  }
 private Item appendGetInfo(Operation operation) {
   Item item = new Item();
   String operationCode = operation.getCode();
   for (Info info : Info.values()) {
     if (operationCode != null && operationCode.equals(info.name())) {
       Target target = new Target();
       target.setLocURI(info.getCode());
       item.setTarget(target);
     }
   }
   return item;
 }
 private Item appendExecInfo(Operation operation) {
   Item item = new Item();
   String operationCode = operation.getCode();
   for (Command command : Command.values()) {
     if (operationCode != null && operationCode.equals(command.name())) {
       Target target = new Target();
       target.setLocURI(command.getCode());
       item.setTarget(target);
     }
   }
   return item;
 }
  /**
   * Update Status of the lock operation.
   *
   * @param status Status of the operation.
   * @param syncmlDocument parsed syncml payload.
   * @param deviceIdentifier Device Id.
   * @throws OperationManagementException
   * @throws DeviceManagementException
   * @throws NotificationManagementException
   */
  public void lockOperationUpdate(
      StatusTag status, SyncmlDocument syncmlDocument, DeviceIdentifier deviceIdentifier)
      throws OperationManagementException, DeviceManagementException,
          NotificationManagementException {

    pendingDataOperations =
        WindowsAPIUtils.getDeviceManagementService()
            .getOperationsByDeviceAndStatus(deviceIdentifier, Operation.Status.PENDING);
    if (Constants.SyncMLResponseCodes.ACCEPTED.equals(status.getData())) {
      for (Operation operation : pendingDataOperations) {
        if ((OperationCode.Command.DEVICE_LOCK.getCode().equals(operation.getCode()))
            && operation.getId() == status.getCommandReference()) {
          operation.setStatus(Operation.Status.COMPLETED);
          new OperationUtils()
              .updateOperations(
                  syncmlDocument.getHeader().getSource().getLocURI(), pendingDataOperations);
        }
      }
    }
    if (Constants.SyncMLResponseCodes.PIN_NOTFOUND.equals(status.getData())) {
      for (Operation operation : pendingDataOperations) {

        if ((OperationCode.Command.DEVICE_LOCK.getCode().equals(operation.getCode())
            && operation.getId() == status.getCommandReference())) {
          operation.setStatus(Operation.Status.ERROR);
          new OperationUtils()
              .updateOperations(
                  syncmlDocument.getHeader().getSource().getLocURI(), pendingDataOperations);
          try {
            NotificationManagementService nmService =
                WindowsAPIUtils.getNotificationManagementService();
            Notification lockResetNotification = new Notification();
            lockResetNotification.setOperationId(status.getCommandReference());
            lockResetNotification.setStatus(String.valueOf(Notification.Status.NEW));
            lockResetNotification.setDeviceIdentifier(deviceIdentifier);
            lockResetNotification.setDescription(
                Constants.SyncMLResponseCodes.LOCKRESET_NOTIFICATION);

            nmService.addNotification(lockResetNotification);
          } catch (NotificationManagementException e) {
            String msg = "Failure occurred in getting notification service";
            log.error(msg, e);
            throw new NotificationManagementException(msg, e);
          }
        }
      }
    }
  }
  /**
   * Update the completed/Error status of the operation which have the URI of the operation code in
   * the syncml payload.
   *
   * @param syncmlDocument SyncmlDocument object generated from the the syncml engine.
   * @throws DeviceManagementException
   * @throws NotificationManagementException
   * @throws OperationManagementException
   */
  public void UpdateUriOperations(SyncmlDocument syncmlDocument)
      throws DeviceManagementException, NotificationManagementException,
          OperationManagementException, WindowsOperationException {
    DeviceIdentifier deviceIdentifier =
        convertToDeviceIdentifierObject(syncmlDocument.getHeader().getSource().getLocURI());
    List<StatusTag> statuses = syncmlDocument.getBody().getStatus();
    OperationUtils operationUtils = new OperationUtils();

    for (StatusTag status : statuses) {

      if ((Constants.EXECUTE.equals(status.getCommand()))) {
        if (status.getTargetReference() == null) {
          operationUtils.updateDeviceOperations(status, syncmlDocument, deviceIdentifier);
        } else {
          if ((OperationCode.Command.DEVICE_LOCK.equals(status.getTargetReference()))) {
            operationUtils.lockOperationUpdate(status, syncmlDocument, deviceIdentifier);
          }
          if ((OperationCode.Command.DEVICE_RING.equals(status.getTargetReference()))) {
            operationUtils.ring(status, syncmlDocument, deviceIdentifier);
          }
          if (equals(OperationCode.Command.WIPE_DATA.equals(status.getTargetReference()))) {
            operationUtils.dataWipe(status, syncmlDocument, deviceIdentifier);
          }
        }
      }
      if ((Constants.SEQUENCE.equals(status.getCommand()))) {
        if ((Constants.SyncMLResponseCodes.ACCEPTED.equals(status.getData()))) {

          pendingDataOperations =
              WindowsAPIUtils.getDeviceManagementService()
                  .getOperationsByDeviceAndStatus(deviceIdentifier, Operation.Status.PENDING);
          for (Operation operation : pendingDataOperations) {
            if ((PluginConstants.OperationCodes.POLICY_BUNDLE.equals(operation.getCode()))
                && operation.getId() == status.getCommandReference()) {
              operation.setStatus(Operation.Status.COMPLETED);
            }
            if ((PluginConstants.OperationCodes.MONITOR.equals(operation.getCode()))
                && operation.getId() == status.getCommandReference()) {
              operation.setStatus(Operation.Status.COMPLETED);
            }
          }
          operationUtils.updateOperations(
              syncmlDocument.getHeader().getSource().getLocURI(), pendingDataOperations);
        } else {
          pendingDataOperations =
              WindowsAPIUtils.getDeviceManagementService()
                  .getOperationsByDeviceAndStatus(deviceIdentifier, Operation.Status.PENDING);
          for (Operation operation : pendingDataOperations) {

            if ((PluginConstants.OperationCodes.POLICY_BUNDLE.equals(operation.getCode()))
                && operation.getId() == status.getCommandReference()) {
              operation.setStatus(Operation.Status.ERROR);
            }
            if ((PluginConstants.OperationCodes.MONITOR.equals(operation.getCode()))
                && operation.getId() == status.getCommandReference()) {
              operation.setStatus(Operation.Status.ERROR);
            }
          }
          operationUtils.updateOperations(
              syncmlDocument.getHeader().getSource().getLocURI(), pendingDataOperations);
        }
      }
    }
  }
  @POST
  @Path("device/{deviceId}/buzz")
  public Response switchBuzzer(
      @PathParam("deviceId") String deviceId, @FormParam("state") String state) {
    if (state == null || state.isEmpty()) {
      log.error("State is not defined for the buzzer operation");
      return Response.status(Response.Status.BAD_REQUEST).build();
    }
    String switchToState = state.toUpperCase();
    if (!switchToState.equals(VirtualFireAlarmConstants.STATE_ON)
        && !switchToState.equals(VirtualFireAlarmConstants.STATE_OFF)) {
      log.error("The requested state change shoud be either - 'ON' or 'OFF'");
      return Response.status(Response.Status.BAD_REQUEST).build();
    }
    try {
      if (!APIUtil.getDeviceAccessAuthorizationService()
          .isUserAuthorized(
              new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE),
              DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
        return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
      }
      String resource = VirtualFireAlarmConstants.BULB_CONTEXT.replace("/", "");
      PrivateKey serverPrivateKey = VirtualFirealarmSecurityManager.getServerPrivateKey();
      String actualMessage = resource + ":" + switchToState;
      String encryptedMsg =
          VirtualFireAlarmServiceUtils.prepareSecurePayLoad(actualMessage, serverPrivateKey);
      String publishTopic =
          APIUtil.getTenantDomainOftheUser()
              + "/"
              + VirtualFireAlarmConstants.DEVICE_TYPE
              + "/"
              + deviceId;

      Operation commandOp = new CommandOperation();
      commandOp.setCode("buzz");
      commandOp.setType(Operation.Type.COMMAND);
      commandOp.setEnabled(true);
      commandOp.setPayLoad(encryptedMsg);

      Properties props = new Properties();
      props.setProperty(VirtualFireAlarmConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
      props.setProperty(
          VirtualFireAlarmConstants.CLIENT_JID_PROPERTY_KEY,
          deviceId + "@" + XmppConfig.getInstance().getServerName());
      props.setProperty(VirtualFireAlarmConstants.SUBJECT_PROPERTY_KEY, "CONTROL-REQUEST");
      props.setProperty(
          VirtualFireAlarmConstants.MESSAGE_TYPE_PROPERTY_KEY,
          VirtualFireAlarmConstants.CHAT_PROPERTY_KEY);
      commandOp.setProperties(props);

      List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
      deviceIdentifiers.add(new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE));
      APIUtil.getDeviceManagementService()
          .addOperation(VirtualFireAlarmConstants.DEVICE_TYPE, commandOp, deviceIdentifiers);
      return Response.ok().build();
    } catch (DeviceAccessAuthorizationException e) {
      log.error(e.getErrorMessage(), e);
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } catch (VirtualFireAlarmException e) {
      String errorMsg = "Preparing Secure payload failed for device - [" + deviceId + "]";
      log.error(errorMsg);
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } catch (OperationManagementException e) {
      String msg = "Error occurred while executing command operation upon ringing the buzzer";
      log.error(msg, e);
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }
  }