/**
   * Set the field value, to a content according the content structure
   *
   * @param structure The content structure
   * @param contentlet The content
   * @param fieldName The field name
   * @param value The field value
   * @throws DotDataException
   */
  private static void setField(
      Structure structure, Contentlet contentlet, String fieldName, String[] values)
      throws DotDataException {

    Field field = structure.getFieldVar(fieldName);
    String value = "";
    if (UtilMethods.isSet(field) && APILocator.getFieldAPI().valueSettable(field)) {
      try {
        if (field.getFieldType().equals(Field.FieldType.HOST_OR_FOLDER.toString())) {
          value = VelocityUtil.cleanVelocity(values[0]);
          Host host =
              APILocator.getHostAPI().find(value, APILocator.getUserAPI().getSystemUser(), false);
          if (host != null && InodeUtils.isSet(host.getIdentifier())) {
            contentlet.setHost(host.getIdentifier());
            contentlet.setFolder(FolderAPI.SYSTEM_FOLDER);
          } else {
            Folder folder =
                APILocator.getFolderAPI()
                    .find(value, APILocator.getUserAPI().getSystemUser(), false);
            if (folder != null && InodeUtils.isSet(folder.getInode())) {
              contentlet.setHost(folder.getHostId());
              contentlet.setFolder(folder.getInode());
            }
          }
        } else if (field.getFieldType().equals(Field.FieldType.MULTI_SELECT.toString())
            || field.getFieldType().equals(Field.FieldType.CHECKBOX.toString())) {
          if (field.getFieldContentlet().startsWith("float")
              || field.getFieldContentlet().startsWith("integer")) {
            value = values[0];
          } else {
            for (String temp : values) {
              value = temp + "," + value;
            }
          }
        } else if (field.getFieldType().equals(Field.FieldType.DATE.toString())) {
          value = VelocityUtil.cleanVelocity(values[0]);
          if (value instanceof String) {
            value = value + " 00:00:00";
          }
        } else {

          value = VelocityUtil.cleanVelocity(values[0]);
        }
        conAPI.setContentletProperty(contentlet, field, value);

      } catch (Exception e) {
        Logger.debug(SubmitContentUtil.class, e.getMessage());
      }
    }
  }
  /**
   * Save the file uploaded
   *
   * @param user the user that save the file
   * @param host Current host
   * @param uploadedFile
   * @param folder The folder where the file is going to be save
   * @param title The filename
   * @return File
   * @throws Exception
   */
  @SuppressWarnings("unchecked")
  private static FileAsset saveFile(
      User user, Host host, java.io.File uploadedFile, String folderPath, String title)
      throws Exception {

    Folder folder = APILocator.getFolderAPI().findFolderByPath(folderPath, host, user, false);
    if (!UtilMethods.isSet(folder.getInode())) {
      User systemUser = APILocator.getUserAPI().getSystemUser();
      folder =
          APILocator.getFolderAPI()
              .createFolders(folderPath, host, APILocator.getUserAPI().getSystemUser(), false);
    }

    byte[] bytes = FileUtil.getBytes(uploadedFile);

    if (bytes != null) {
      String newFileName = "";
      String name = UtilMethods.getFileName(title);
      int counter = 1;
      String fileName = name + "." + UtilMethods.getFileExtension(title);
      while (APILocator.getFileAPI().fileNameExists(folder, fileName)) {
        newFileName = name + "(" + counter + ")";
        fileName = newFileName + "." + UtilMethods.getFileExtension(title);
        counter++;
      }
      while (APILocator.getFileAssetAPI().fileNameExists(host, folder, name, "")) {
        newFileName = name + "(" + counter + ")";
        fileName = newFileName + "." + UtilMethods.getFileExtension(title);
        counter++;
      }
      if (UtilMethods.isSet(newFileName)) {
        name = newFileName;
      }
      Contentlet cont = new Contentlet();
      cont.setStructureInode(folder.getDefaultFileType());
      cont.setStringProperty(FileAssetAPI.TITLE_FIELD, UtilMethods.getFileName(name));
      cont.setFolder(folder.getInode());
      cont.setHost(host.getIdentifier());
      cont.setBinary(FileAssetAPI.BINARY_FIELD, uploadedFile);
      if (StructureCache.getStructureByInode(cont.getStructureInode()).getStructureType()
          == Structure.STRUCTURE_TYPE_FILEASSET) cont.setStringProperty("fileName", title);
      cont = APILocator.getContentletAPI().checkin(cont, user, false);
      if (APILocator.getPermissionAPI()
          .doesUserHavePermission(cont, PermissionAPI.PERMISSION_PUBLISH, user))
        APILocator.getVersionableAPI().setLive(cont);
      return APILocator.getFileAssetAPI().fromContentlet(cont);
    }

    return null;
  }
  public static FileAsset saveTempFile(
      User user, Host host, java.io.File uploadedFile, String folderPath, String title)
      throws Exception {

    Folder folder = APILocator.getFolderAPI().findFolderByPath(folderPath, host, user, false);

    byte[] bytes = FileUtil.getBytes(uploadedFile);

    if (bytes != null) {

      String name = UtilMethods.getFileName(title);
      int counter = 1;
      while (APILocator.getFileAPI().fileNameExists(folder, name)) {
        name = name + counter;
        counter++;
      }

      Contentlet cont = new Contentlet();
      cont.setStructureInode(folder.getDefaultFileType());
      cont.setStringProperty(FileAssetAPI.TITLE_FIELD, UtilMethods.getFileName(name));
      cont.setFolder(folder.getInode());
      cont.setHost(host.getIdentifier());
      cont.setBinary(FileAssetAPI.BINARY_FIELD, uploadedFile);
      APILocator.getContentletAPI().checkin(cont, user, false);
      APILocator.getVersionableAPI().setLive(cont);
      return APILocator.getFileAssetAPI().fromContentlet(cont);
    }

    return null;
  }
  @SuppressWarnings({"unchecked", "deprecation"})
  public boolean renameFile(File file, String newName)
      throws DotStateException, DotDataException, DotSecurityException {

    // getting old file properties
    String oldFileName = file.getFileName();
    String ext = UtilMethods.getFileExtension(oldFileName);
    Folder folder =
        APILocator.getFolderAPI()
            .findParentFolder(file, APILocator.getUserAPI().getSystemUser(), false);

    Identifier ident = APILocator.getIdentifierAPI().find(file);

    String newFileName = newName;
    if (UtilMethods.isSet(ext)) {
      newFileName = newFileName + "." + ext;
    }

    if (fileNameExists(folder, newFileName) || file.isLocked()) return false;

    List<Versionable> versions = APILocator.getVersionableAPI().findAllVersions(ident);

    boolean islive = false;

    for (Versionable version : versions) {
      File f = (File) version;

      // sets filename for this new file
      f.setFileName(newFileName);

      HibernateUtil.saveOrUpdate(f);

      if (f.isLive()) islive = true;
    }

    LiveCache.removeAssetFromCache(file);
    WorkingCache.removeAssetFromCache(file);
    CacheLocator.getIdentifierCache().removeFromCacheByVersionable(file);

    ident.setURI(APILocator.getIdentifierAPI().find(folder).getPath() + newFileName);
    // HibernateUtil.saveOrUpdate(ident);
    APILocator.getIdentifierAPI().save(ident);

    if (islive) {
      LiveCache.removeAssetFromCache(file);
      LiveCache.addToLiveAssetToCache(file);
    }
    WorkingCache.removeAssetFromCache(file);
    WorkingCache.addToWorkingAssetToCache(file);
    CacheLocator.getIdentifierCache().removeFromCacheByVersionable(file);

    // RefreshMenus.deleteMenus();
    RefreshMenus.deleteMenu(file);
    CacheLocator.getNavToolCache().removeNav(folder.getHostId(), folder.getInode());

    return true;
  }
  /**
   * Moves a file into the given directory OR host
   *
   * @param file File to be moved
   * @param parent Destination Folder
   * @param host Destination Host
   * @return true if move success, false otherwise
   * @throws DotDataException
   * @throws DotStateException
   * @throws DotSecurityException
   */
  private Boolean moveFile(File file, Folder parent, Host host)
      throws DotStateException, DotDataException, DotSecurityException {

    HostAPI hostAPI = APILocator.getHostAPI();

    // Find file identifier
    Identifier identifier = com.dotmarketing.business.APILocator.getIdentifierAPI().find(file);

    // gets working container
    File workingWebAsset =
        (File)
            APILocator.getVersionableAPI()
                .findWorkingVersion(identifier, APILocator.getUserAPI().getSystemUser(), false);
    // gets live container
    File liveWebAsset =
        (File)
            APILocator.getVersionableAPI()
                .findLiveVersion(identifier, APILocator.getUserAPI().getSystemUser(), false);

    // checks if another identifer with the same name exists in the same
    Boolean fileNameExists;
    if (parent != null) {
      fileNameExists = fileNameExists(parent, file.getFileName());
    } else {
      fileNameExists =
          fileNameExists(APILocator.getFolderAPI().findSystemFolder(), file.getFileName());
    }
    if (fileNameExists) {
      return false;
    }

    // assets cache
    if ((liveWebAsset != null) && (InodeUtils.isSet(liveWebAsset.getInode()))) {
      LiveCache.removeAssetFromCache(liveWebAsset);
    }
    WorkingCache.removeAssetFromCache(workingWebAsset);

    // gets old parent
    Folder oldParent =
        APILocator.getFolderAPI()
            .findParentFolder(workingWebAsset, APILocator.getUserAPI().getSystemUser(), false);

    /*oldParent.deleteChild(workingWebAsset);
    if ((liveWebAsset != null) && (InodeUtils.isSet(liveWebAsset.getInode()))) {
        oldParent.deleteChild(liveWebAsset);
    }
    //add new Parent
    parent.addChild(workingWebAsset);
    if ((liveWebAsset != null) && (InodeUtils.isSet(liveWebAsset.getInode()))) {
        parent.addChild(liveWebAsset);
    }*/

    // gets identifier for this webasset and changes the uri and persists it
    User systemUser;
    try {
      systemUser = APILocator.getUserAPI().getSystemUser();
      if (host == null) {
        host = hostAPI.findParentHost(parent, systemUser, false);
      }
    } catch (DotDataException e) {
      Logger.error(FileFactory.class, e.getMessage(), e);
      throw new DotRuntimeException(e.getMessage(), e);

    } catch (DotSecurityException e) {
      Logger.error(FileFactory.class, e.getMessage(), e);
      throw new DotRuntimeException(e.getMessage(), e);
    }
    identifier.setHostId(host.getIdentifier());
    identifier.setURI(parent != null ? workingWebAsset.getURI(parent) : workingWebAsset.getURI());
    // HibernateUtil.saveOrUpdate(identifier);
    APILocator.getIdentifierAPI().save(identifier);

    if (UtilMethods.isSet(liveWebAsset))
      CacheLocator.getIdentifierCache().removeFromCacheByVersionable(liveWebAsset);
    //		IdentifierCache.addAssetToIdentifierCache(liveWebAsset);

    // Add to Preview and Live Cache
    if ((liveWebAsset != null) && (InodeUtils.isSet(liveWebAsset.getInode()))) {
      LiveCache.removeAssetFromCache(liveWebAsset);
      LiveCache.addToLiveAssetToCache(liveWebAsset);
    }
    WorkingCache.removeAssetFromCache(workingWebAsset);
    WorkingCache.addToWorkingAssetToCache(workingWebAsset);

    if (file.isShowOnMenu()) {
      // existing folder with different show on menu ... need to regenerate menu
      if (parent != null) {
        RefreshMenus.deleteMenu(oldParent, parent);
        CacheLocator.getNavToolCache().removeNav(parent.getHostId(), parent.getInode());
      } else {
        RefreshMenus.deleteMenu(oldParent);
      }
      CacheLocator.getNavToolCache().removeNav(oldParent.getHostId(), oldParent.getInode());
    }

    return true;
  }
  public void publish(HttpServletRequest request, HttpServletResponse response)
      throws WorkflowActionFailureException {
    try {
      PublisherAPI publisherAPI = PublisherAPI.getInstance();
      String _assetId = request.getParameter("assetIdentifier");
      String _contentPushPublishDate = request.getParameter("remotePublishDate");
      String _contentPushPublishTime = request.getParameter("remotePublishTime");
      String _contentPushExpireDate = request.getParameter("remotePublishExpireDate");
      String _contentPushExpireTime = request.getParameter("remotePublishExpireTime");
      String _iWantTo = request.getParameter("iWantTo");

      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-H-m");
      Date publishDate = dateFormat.parse(_contentPushPublishDate + "-" + _contentPushPublishTime);

      List<String> ids = new ArrayList<String>();

      try {

        // check for the categories
        if (_assetId.equals("CAT")) {
          ids.add(_assetId);
        } else {
          // if the asset is a folder put the inode instead of the identifier
          Folder folder = null;
          try {
            folder = APILocator.getFolderAPI().find(_assetId, getUser(), false);
          } catch (DotDataException e) {
          }

          if (folder != null && UtilMethods.isSet(folder.getInode())) {
            ids.add(_assetId);
          } else {
            // if the asset is not a folder and has identifier, put it, if not, put the inode
            Identifier iden = APILocator.getIdentifierAPI().findFromInode(_assetId);
            ids.add(iden.getId());
          }
        }
      } catch (DotStateException e) {
        ids.add(_assetId);
      } catch (DotSecurityException e) {
        e.printStackTrace();
      }

      String bundleId = UUID.randomUUID().toString();
      if (_iWantTo.equals(RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH)
          || _iWantTo.equals(RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH_AND_EXPIRE)) {
        publisherAPI.addContentsToPublish(ids, bundleId, publishDate, getUser());
      }
      if (_iWantTo.equals(RemotePublishAjaxAction.DIALOG_ACTION_EXPIRE)
          || _iWantTo.equals(RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH_AND_EXPIRE)) {
        if ((!"".equals(_contentPushExpireDate.trim())
            && !"".equals(_contentPushExpireTime.trim()))) {
          bundleId = UUID.randomUUID().toString();
          Date expireDate = dateFormat.parse(_contentPushExpireDate + "-" + _contentPushExpireTime);
          publisherAPI.addContentsToUnpublish(ids, bundleId, expireDate, getUser());
        }
      }
    } catch (DotPublisherException e) {
      Logger.debug(PushPublishActionlet.class, e.getMessage());
      throw new WorkflowActionFailureException(e.getMessage());
    } catch (ParseException e) {
      Logger.debug(PushPublishActionlet.class, e.getMessage());
      throw new WorkflowActionFailureException(e.getMessage());
    } catch (DotDataException e) {
      Logger.error(PushPublishActionlet.class, e.getMessage(), e);
    }
  }
  /** Returns the list of ids the user is trying to remote publish. */
  private List<String> getIdsToPush(
      List<String> assetIds, String _contentFilterDate, SimpleDateFormat dateFormat)
      throws ParseException, DotDataException {

    List<String> ids = new ArrayList<String>();

    for (String _assetId : assetIds) {

      if (_assetId != null && !_assetId.trim().isEmpty()) {

        if (ids.contains(_assetId)) {
          continue;
        }

        // check for the categories
        if (_assetId.contains("user_") || _assetId.contains("users_")) { // Trying to publish users
          // If we are trying to push users a filter date must be available
          if (_assetId.contains("users_")) {
            Date filteringDate = dateFormat.parse(_contentFilterDate);
            // Get users where createdate >= ?
            List<String> usersIds =
                APILocator.getUserAPI().getUsersIdsByCreationDate(filteringDate, 0, -1);
            if (usersIds != null) {
              for (String id : usersIds) {
                ids.add("user_" + id);
              }
            }
          } else {
            ids.add(_assetId);
          }
        } else if (_assetId.equals("CAT")) {
          ids.add(_assetId);
        } else if (_assetId.contains(".jar")) { // Check for OSGI jar bundles
          ids.add(_assetId);
        } else {
          // if the asset is a folder put the inode instead of the identifier
          try {
            Folder folder = null;
            try {
              folder = APILocator.getFolderAPI().find(_assetId, getUser(), false);
            } catch (DotSecurityException e) {
              Logger.error(
                  getClass(),
                  "User: "******" does not have permission to access folder. Folder identifier: "
                      + _assetId);
            } catch (DotDataException e) {
              Logger.info(getClass(), "FolderAPI.find(): Identifier is null");
            }

            if (folder != null && UtilMethods.isSet(folder.getInode())) {
              ids.add(_assetId);
            } else {
              // if the asset is not a folder and has identifier, put it, if not, put the inode
              Identifier iden = APILocator.getIdentifierAPI().findFromInode(_assetId);
              if (!ids.contains(iden.getId())) { // Multiples languages have the same identifier
                ids.add(iden.getId());
              }
            }

          } catch (DotStateException e) {
            ids.add(_assetId);
          }
        }
      }
    }

    return ids;
  }