Exemplo n.º 1
0
  /**
   * Cleans the WAR file of all files relating to the currently installed version of the the AMP.
   *
   * @param warFileLocatio the war file location
   * @param moduleId the module id
   * @param preview indicates whether this is a preview installation
   */
  private void cleanWAR(String warFileLocation, String moduleId, boolean preview) {
    InstalledFiles installedFiles = new InstalledFiles(warFileLocation, moduleId);
    installedFiles.load();

    for (String add : installedFiles.getAdds()) {
      // Remove file
      removeFile(warFileLocation, add, preview);
    }
    for (String mkdir : installedFiles.getMkdirs()) {
      // Remove folder
      removeFile(warFileLocation, mkdir, preview);
    }
    for (Map.Entry<String, String> update : installedFiles.getUpdates().entrySet()) {
      if (preview == false) {
        // Recover updated file and delete backups
        File modified = new File(warFileLocation + update.getKey(), DETECTOR_AMP_AND_WAR);
        File backup = new File(warFileLocation + update.getValue(), DETECTOR_AMP_AND_WAR);
        modified.copyFrom(backup);
        backup.delete();
      }

      outputMessage(
          "Recovering file '" + update.getKey() + "' from backup '" + update.getValue() + "'",
          true);
    }
    // Now remove the installed files list
    String installedFilesPathInWar = installedFiles.getFilePathInWar();
    removeFile(warFileLocation, installedFilesPathInWar, preview);
    // Remove the module properties
    String modulePropertiesFileLocationInWar =
        ModuleDetailsHelper.getModulePropertiesFilePathInWar(moduleId);
    removeFile(warFileLocation, modulePropertiesFileLocationInWar, preview);
  }
Exemplo n.º 2
0
 /** @return Returns the custom file mapping properties or null if they weren't overwritten */
 private Properties getCustomFileMappings(String ampFileLocation) {
   File file =
       new File(
           ampFileLocation + "/" + FILE_MAPPING_PROPERTIES,
           ModuleManagementTool.DETECTOR_AMP_AND_WAR);
   if (!file.exists()) {
     // Nothing there
     return null;
   }
   Properties mappingProperties = new Properties();
   InputStream is = null;
   try {
     is = new BufferedInputStream(new FileInputStream(file));
     mappingProperties.load(is);
   } catch (IOException exception) {
     throw new ModuleManagementToolException(
         "Unable to load default extension file mapping properties.", exception);
   } finally {
     if (is != null) {
       try {
         is.close();
       } catch (Throwable e) {
       }
     }
   }
   return mappingProperties;
 }
Exemplo n.º 3
0
 @NotNull
 @Override
 public Value getLastUpdate() {
   return valueTableDirectory.exists()
       ? DateTimeType.get().valueOf(new Date(valueTableDirectory.lastModified()))
       : DateTimeType.get().nullValue();
 }
Exemplo n.º 4
0
  /**
   * Search in plugin folder in .metadata and zip all files
   *
   * @throws ArchiveException
   */
  private static File createZip() throws ArchiveException {
    // Get all log xml files
    IPath pluginSaveFolder = FeedbackUtils.getFeedbackSaveFolder();
    java.io.File source = pluginSaveFolder.toFile();
    List<java.io.File> fileList = FileHelper.listAll(source);

    List<File> logFiles = new ArrayList<File>();
    for (java.io.File f : fileList) {
      if (f.getName().endsWith(FeedbackUtils.END_FILE_NAME)) {
        logFiles.add(new File(f));
      }
    }

    // Zip creation
    File zipFile = new File(source, FeedbackActivator.ZIP_FILE_NAME);
    zipFile.mkdir();
    // Add them to the zip
    for (File f : logFiles) {
      File zipEntry = new File(zipFile, f.getName(), ArchiveDetector.NULL);
      f.copyTo(zipEntry);
      if (zipFile.archiveCopyAllFrom(f)) {
        System.err.println("Copied " + f.getName());
      } else {
        System.err.println("Error in copy " + f.getName());
      }
    }
    File.update();
    return zipFile;
  }
Exemplo n.º 5
0
 /**
  * Removes a file from the given location in the war file.
  *
  * @param warLocation the war file location
  * @param filePath the path to the file that is to be deleted
  * @param preview indicates whether this is a preview install
  */
 private void removeFile(String warLocation, String filePath, boolean preview) {
   File removeFile = new File(warLocation + filePath, DETECTOR_AMP_AND_WAR);
   if (removeFile.exists() == true) {
     outputMessage("Removing file '" + filePath + "' from war", true);
     if (preview == false) {
       removeFile.delete();
     }
   } else {
     outputMessage(
         "The file '" + filePath + "' was expected for removal but was not present in the war",
         true);
   }
 }
Exemplo n.º 6
0
  /**
   * Import zipped documents
   *
   * @param path Where import into the repository.
   * @param is The zip file to import.
   */
  private synchronized String importZip(String path, InputStream is)
      throws PathNotFoundException, ItemExistsException, AccessDeniedException, RepositoryException,
          IOException, DatabaseException, ExtensionException, AutomationException {
    log.debug("importZip({}, {})", path, is);
    java.io.File tmpIn = null;
    java.io.File tmpOut = null;
    String errorMsg = null;

    try {
      // Create temporal
      tmpIn = File.createTempFile("okm", ".zip");
      tmpOut = FileUtils.createTempDir();
      FileOutputStream fos = new FileOutputStream(tmpIn);
      IOUtils.copy(is, fos);
      fos.close();

      // Unzip files
      File fileTmpIn = new File(tmpIn);
      fileTmpIn.archiveCopyAllTo(tmpOut);
      File.umount();

      // Import files
      StringWriter out = new StringWriter();
      ImpExpStats stats =
          RepositoryImporter.importDocuments(
              null, tmpOut, path, false, false, false, out, new TextInfoDecorator(tmpOut));

      if (!stats.isOk()) {
        errorMsg = out.toString();
      }

      out.close();
    } catch (IOException e) {
      log.error("Error importing zip", e);
      throw e;
    } finally {
      IOUtils.closeQuietly(is);

      if (tmpIn != null) {
        org.apache.commons.io.FileUtils.deleteQuietly(tmpIn);
      }

      if (tmpOut != null) {
        org.apache.commons.io.FileUtils.deleteQuietly(tmpOut);
      }
    }

    log.debug("importZip: {}", errorMsg);
    return errorMsg;
  }
Exemplo n.º 7
0
  /**
   * Remove xml files and zipFile.
   *
   * @param zipFile
   */
  private static void removeSendedFiles(File zipFile) {
    IPath pluginSaveFolder = FeedbackUtils.getFeedbackSaveFolder();
    java.io.File source = pluginSaveFolder.toFile();
    List<java.io.File> fileList = FileHelper.listAll(source);
    for (java.io.File f : fileList) {
      if (f.getName().endsWith(FeedbackUtils.END_FILE_NAME)) {
        f.delete();
      }
    }

    try {
      File.umount(true);
    } catch (ArchiveException e) {
      e.printStackTrace();
    }

    // Delete with trueZip function doesn't work
    java.io.File testFile = new java.io.File(source, FeedbackActivator.ZIP_FILE_NAME);
    if (testFile.exists()) {
      try {
        testFile.delete();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 8
0
  /** Send all *-log.xml files to blueXml server. */
  protected static boolean send() {
    File zipFile = null;
    boolean noError = true;
    // Zip creation
    try {
      zipFile = createZip();
    } catch (ArchiveException e) {
      e.printStackTrace();
      noError = false;
    }

    if (zipFile != null && zipFile.list() != null && zipFile.list().length > 0) {
      // Send it
      try {
        sendFile(zipFile);
        // Remove all files send previously
        removeSendedFiles(zipFile);
      } catch (Exception e) {
        e.printStackTrace();
        noError = false;
      }
    }
    return noError;
  }
Exemplo n.º 9
0
  /**
   * Lists all the currently installed modules in the WAR
   *
   * @param warLocation the war location
   */
  public void listModules(String warLocation) {
    ModuleDetails moduleDetails = null;
    boolean previous = this.verbose;
    this.verbose = true;
    try {
      File moduleDir = new File(warLocation + MODULE_DIR, DETECTOR_AMP_AND_WAR);
      if (moduleDir.exists() == false) {
        outputMessage("No modules are installed in this WAR file");
      }

      java.io.File[] dirs = moduleDir.listFiles();
      if (dirs != null && dirs.length != 0) {
        for (java.io.File dir : dirs) {
          if (dir.isDirectory() == true) {
            File moduleProperties =
                new File(dir.getPath() + "/module.properties", DETECTOR_AMP_AND_WAR);
            if (moduleProperties.exists() == true) {
              try {
                InputStream is = new FileInputStream(moduleProperties);
                moduleDetails = ModuleDetailsHelper.createModuleDetailsFromPropertiesStream(is);
              } catch (IOException exception) {
                throw new ModuleManagementToolException(
                    "Unable to open module properties file '" + moduleProperties.getPath() + "'",
                    exception);
              }

              outputMessage(
                  "Module '" + moduleDetails.getId() + "' installed in '" + warLocation + "'");
              outputMessage("   Title:        " + moduleDetails.getTitle(), true);
              outputMessage("   Version:      " + moduleDetails.getVersion(), true);
              outputMessage("   Install Date: " + moduleDetails.getInstallDate(), true);
              outputMessage("   Description:   " + moduleDetails.getDescription(), true);
            }
          }
        }
      } else {
        outputMessage("No modules are installed in this WAR file");
      }
    } finally {
      this.verbose = previous;
    }
  }
Exemplo n.º 10
0
  /**
   * Copies a file from the AMP location to the correct location in the WAR, interating on
   * directories where appropraite.
   *
   * @param ampFileLocation the AMP file location
   * @param warFileLocation the WAR file location
   * @param sourceDir the directory in the AMP to copy from. It must start with "/".
   * @param destinationDir the directory in the WAR to copy to. It must start with "/".
   * @param installedFiles a list of the currently installed files
   * @param preview indicates whether this is a preview install or not
   * @throws IOException throws any IOExpceptions thar are raised
   */
  private void copyToWar(
      String ampFileLocation,
      String warFileLocation,
      String sourceDir,
      String destinationDir,
      InstalledFiles installedFiles,
      boolean preview)
      throws IOException {
    if (sourceDir.length() == 0 || !sourceDir.startsWith("/")) {
      throw new IllegalArgumentException("sourceDir must start with '/'");
    }
    if (destinationDir.length() == 0 || !destinationDir.startsWith("/")) {
      throw new IllegalArgumentException("destinationDir must start with '/'");
    }

    // Handle source and destination if they are just the root '/'
    if (sourceDir.equals("/")) {
      sourceDir = "";
    }
    if (destinationDir.equals("/")) {
      destinationDir = "";
    }

    String sourceLocation = ampFileLocation + sourceDir;
    File ampConfig = new File(sourceLocation, DETECTOR_AMP_AND_WAR);

    java.io.File[] files = ampConfig.listFiles();
    if (files != null) {
      for (java.io.File sourceChild : files) {
        String destinationFileLocation =
            warFileLocation + destinationDir + "/" + sourceChild.getName();
        File destinationChild = new File(destinationFileLocation, DETECTOR_AMP_AND_WAR);
        if (sourceChild.isFile() == true) {
          String backupLocation = null;
          boolean createFile = false;
          if (destinationChild.exists() == false) {
            createFile = true;
          } else {
            // Backup file about to be updated
            backupLocation = BACKUP_DIR + "/" + generateGuid() + ".bin";
            if (preview == false) {
              File backupFile = new File(warFileLocation + backupLocation, DETECTOR_AMP_AND_WAR);
              backupFile.copyFrom(destinationChild);
            }
          }

          if (createFile == true) {
            installedFiles.addAdd(destinationDir + "/" + sourceChild.getName());
            this.outputMessage(
                "File '" + destinationDir + "/" + sourceChild.getName() + "' added to war from amp",
                true);
          } else {
            installedFiles.addUpdate(destinationDir + "/" + sourceChild.getName(), backupLocation);
            this.outputMessage(
                "WARNING: The file '"
                    + destinationDir
                    + "/"
                    + sourceChild.getName()
                    + "' is being updated by this module and has been backed-up to '"
                    + backupLocation
                    + "'",
                true);
          }
        } else {
          boolean mkdir = false;
          if (destinationChild.exists() == false) {
            mkdir = true;
          }

          copyToWar(
              ampFileLocation,
              warFileLocation,
              sourceDir + "/" + sourceChild.getName(),
              destinationDir + "/" + sourceChild.getName(),
              installedFiles,
              preview);
          if (mkdir == true) {
            installedFiles.addMkdir(destinationDir + "/" + sourceChild.getName());
            this.outputMessage(
                "Directory '" + destinationDir + "/" + sourceChild.getName() + "' added to war",
                true);
          }
        }
      }
    }
  }
Exemplo n.º 11
0
  /**
   * Installs a given AMP file into a given WAR file.
   *
   * @param ampFileLocation the location of the AMP file to be installed
   * @param warFileLocation the location of the WAR file into which the AMP file is to be installed.
   * @param preview indicates whether this should be a preview install. This means that the process
   *     of installation will be followed and reported, but the WAR file will not be modified.
   * @param forceInstall indicates whether the installed files will be replaces reguarless of the
   *     currently installed version of the AMP. Generally used during development of the AMP.
   * @param backupWAR indicates whether we should backup the war we are modifying or not
   */
  public void installModule(
      String ampFileLocation,
      String warFileLocation,
      boolean preview,
      boolean forceInstall,
      boolean backupWAR) {
    try {
      outputMessage("Installing AMP '" + ampFileLocation + "' into WAR '" + warFileLocation + "'");

      if (preview == false) {
        // Make sure the module and backup directory exisits in the WAR file
        File moduleDir = new File(warFileLocation + MODULE_DIR, DETECTOR_AMP_AND_WAR);
        if (moduleDir.exists() == false) {
          moduleDir.mkdir();
        }
        File backUpDir = new File(warFileLocation + BACKUP_DIR, DETECTOR_AMP_AND_WAR);
        if (backUpDir.exists() == false) {
          backUpDir.mkdir();
        }

        // Make a backup of the war we are going to modify
        if (backupWAR == true) {
          java.io.File warFile = new java.io.File(warFileLocation);
          if (warFile.exists() == false) {
            throw new ModuleManagementToolException(
                "The war file '" + warFileLocation + "' does not exist.");
          }
          String backupLocation = warFileLocation + "-" + System.currentTimeMillis() + ".bak";
          java.io.File backup = new java.io.File(backupLocation);
          copyFile(warFile, backup);

          outputMessage("WAR has been backed up to '" + backupLocation + "'");
        }
      }

      // Get the details of the installing module
      String propertiesLocation = ampFileLocation + "/module.properties";
      ModuleDetails installingModuleDetails =
          ModuleDetailsHelper.createModuleDetailsFromPropertyLocation(propertiesLocation);
      if (installingModuleDetails == null) {
        throw new ModuleManagementToolException(
            "No module.properties file has been found in the installing .amp file '"
                + ampFileLocation
                + "'");
      }
      String installingId = installingModuleDetails.getId();
      VersionNumber installingVersion = installingModuleDetails.getVersion();

      // Check that the target war has the necessary dependencies for this install
      List<ModuleDependency> installingModuleDependencies =
          installingModuleDetails.getDependencies();
      List<ModuleDependency> missingDependencies = new ArrayList<ModuleDependency>(0);
      for (ModuleDependency dependency : installingModuleDependencies) {
        String dependencyId = dependency.getDependencyId();
        ModuleDetails dependencyModuleDetails =
            ModuleDetailsHelper.createModuleDetailsFromWarAndId(warFileLocation, dependencyId);
        // Check the dependency.  The API specifies that a null returns false, so no null check is
        // required
        if (!dependency.isValidDependency(dependencyModuleDetails)) {
          missingDependencies.add(dependency);
          continue;
        }
      }
      if (missingDependencies.size() > 0) {
        throw new ModuleManagementToolException(
            "The following modules must first be installed: " + missingDependencies);
      }

      // Try to find an installed module by the ID
      ModuleDetails installedModuleDetails =
          ModuleDetailsHelper.createModuleDetailsFromWarAndId(warFileLocation, installingId);
      if (installedModuleDetails == null) {
        // It might be there as one of the aliases
        List<String> installingAliases = installingModuleDetails.getAliases();
        for (String installingAlias : installingAliases) {
          ModuleDetails installedAliasModuleDetails =
              ModuleDetailsHelper.createModuleDetailsFromWarAndId(warFileLocation, installingAlias);
          if (installedAliasModuleDetails == null) {
            // There is nothing by that alias
            continue;
          }
          // We found an alias and will treat it as the same module
          installedModuleDetails = installedAliasModuleDetails;
          outputMessage(
              "Module '"
                  + installingAlias
                  + "' is installed and is an alias of '"
                  + installingId
                  + "'");
          break;
        }
      }

      // Now clean up the old instance
      if (installedModuleDetails != null) {
        String installedId = installedModuleDetails.getId();
        VersionNumber installedVersion = installedModuleDetails.getVersion();

        int compareValue = installedVersion.compareTo(installingVersion);
        if (forceInstall == true || compareValue == -1) {
          if (forceInstall == true) {
            // Warn of forced install
            outputMessage(
                "WARNING: The installation of this module is being forced.  All files will be removed and replaced regardless of exiting versions present.");
          }

          // Trying to update the extension, old files need to cleaned before we proceed
          outputMessage(
              "Clearing out files relating to version '"
                  + installedVersion
                  + "' of module '"
                  + installedId
                  + "'");
          cleanWAR(warFileLocation, installedId, preview);
        } else if (compareValue == 0) {
          // Trying to install the same extension version again
          outputMessage(
              "WARNING: This version of this module is already installed in the WAR. Installation skipped.");
          return;
        } else if (compareValue == 1) {
          // Trying to install an earlier version of the extension
          outputMessage(
              "WARNING: A later version of this module is already installed in the WAR. Installation skipped.");
          return;
        }
      }

      // Check if a custom mapping file has been defined
      Properties fileMappingProperties = null;
      Properties customFileMappingProperties = getCustomFileMappings(ampFileLocation);
      if (customFileMappingProperties == null) {
        fileMappingProperties = defaultFileMappingProperties;
      } else {
        fileMappingProperties = new Properties();
        // A custom mapping file was present.  Check if it must inherit the default mappings.
        String inheritDefaultStr =
            customFileMappingProperties.getProperty(PROP_INHERIT_DEFAULT, "true");
        if (inheritDefaultStr.equalsIgnoreCase("true")) {
          fileMappingProperties.putAll(defaultFileMappingProperties);
        }
        fileMappingProperties.putAll(customFileMappingProperties);
        fileMappingProperties.remove(PROP_INHERIT_DEFAULT);
      }

      // Copy the files from the AMP file into the WAR file
      outputMessage(
          "Adding files relating to version '"
              + installingVersion
              + "' of module '"
              + installingId
              + "'");
      InstalledFiles installedFiles = new InstalledFiles(warFileLocation, installingId);
      for (Map.Entry<Object, Object> entry : fileMappingProperties.entrySet()) {
        // The file mappings are expected to start with "/"
        String mappingSource = (String) entry.getKey();
        if (mappingSource.length() == 0 || !mappingSource.startsWith("/")) {
          throw new AlfrescoRuntimeException(
              "File mapping sources must start with '/', but was: " + mappingSource);
        }
        String mappingTarget = (String) entry.getValue();
        if (mappingTarget.length() == 0 || !mappingTarget.startsWith("/")) {
          throw new AlfrescoRuntimeException(
              "File mapping targets must start with '/' but was '" + mappingTarget + "'");
        }

        // Run throught the files one by one figuring out what we are going to do during the copy
        copyToWar(
            ampFileLocation,
            warFileLocation,
            mappingSource,
            mappingTarget,
            installedFiles,
            preview);

        if (preview == false) {
          // Get a reference to the source folder (if it isn't present don't do anything)
          File source = new File(ampFileLocation + "/" + mappingSource, DETECTOR_AMP_AND_WAR);
          if (source != null && source.list() != null) {
            // Get a reference to the destination folder
            File destination =
                new File(warFileLocation + "/" + mappingTarget, DETECTOR_AMP_AND_WAR);
            if (destination == null) {
              throw new ModuleManagementToolException(
                  "The destination folder '"
                      + mappingTarget
                      + "' as specified in mapping properties does not exist in the war");
            }
            // Do the bulk copy since this is quicker than copying files one by one
            destination.copyAllFrom(source);
          }
        }
      }

      if (preview == false) {
        // Save the installed file list
        installedFiles.save();

        // Update the installed module details
        installingModuleDetails.setInstallState(ModuleInstallState.INSTALLED);
        installingModuleDetails.setInstallDate(new Date());
        ModuleDetailsHelper.saveModuleDetails(warFileLocation, installingModuleDetails);

        // Update the zip files
        File.update();

        // Set the modified date
        java.io.File warFile = new java.io.File(warFileLocation);
        if (warFile.exists()) {
          warFile.setLastModified(System.currentTimeMillis());
        }
      }
    } catch (ZipWarningException ignore) {
      // Only instances of the class ZipWarningException exist in the chain of
      // exceptions. We choose to ignore this.
    } catch (ZipControllerException exception) {
      // At least one exception occured which is not just a ZipWarningException.
      // This is a severe situation that needs to be handled.
      throw new ModuleManagementToolException(
          "A Zip error was encountered during deployment of the AEP into the WAR", exception);
    } catch (IOException exception) {
      throw new ModuleManagementToolException(
          "An IO error was encountered during deployment of the AEP into the WAR", exception);
    }
  }
Exemplo n.º 12
0
  @SuppressWarnings("unchecked")
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    log.debug("doPost({}, {})", request, response);
    String fileName = null;
    InputStream is = null;
    String path = null;
    int action = 0;
    long size = 0;
    boolean notify = false;
    boolean importZip = false;
    boolean autoCheckOut = false;
    String users = null;
    String roles = null;
    String message = null;
    String comment = null;
    String folder = null;
    String rename = null;
    PrintWriter out = null;
    String uploadedUuid = null;
    java.io.File tmp = null;
    boolean redirect = false;
    boolean convertToPdf = false;
    String redirectURL = "";
    updateSessionManager(request);

    // JSON Stuff
    Ref<FileUploadResponse> fuResponse = new Ref<FileUploadResponse>(new FileUploadResponse());

    try {
      boolean isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType(MimeTypeConfig.MIME_TEXT);
      out = response.getWriter();
      log.debug("isMultipart: {}", isMultipart);

      // Create a factory for disk-based file items
      if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        String contentLength = request.getHeader("Content-Length");
        FileUploadListener listener = new FileUploadListener(Long.parseLong(contentLength));

        // Saving listener to session
        request.getSession().setAttribute(FILE_UPLOAD_STATUS, listener);
        upload.setHeaderEncoding("UTF-8");

        // upload servlet allows to set upload listener
        upload.setProgressListener(listener);
        List<FileItem> items = upload.parseRequest(request);

        // Parse the request and get all parameters and the uploaded file
        for (Iterator<FileItem> it = items.iterator(); it.hasNext(); ) {
          FileItem item = it.next();

          if (item.isFormField()) {
            if (item.getFieldName().equals("path")) {
              path = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("action")) {
              action = Integer.parseInt(item.getString("UTF-8"));
            }

            if (item.getFieldName().equals("users")) {
              users = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("roles")) {
              roles = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("notify")) {
              notify = true;
            }

            if (item.getFieldName().equals("importZip")) {
              importZip = true;
            }

            if (item.getFieldName().equals("autoCheckOut")) {
              autoCheckOut = true;
            }

            if (item.getFieldName().equals("message")) {
              message = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("comment")) {
              comment = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("folder")) {
              folder = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("rename")) {
              rename = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("redirect")) {
              redirect = true;
              redirectURL = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("convertToPdf")) {
              convertToPdf = true;
            }
          } else {
            fileName = item.getName();
            is = item.getInputStream();
            size = item.getSize();
          }
        }

        // Save document with different name than uploaded
        log.debug("Filename: '{}'", fileName);
        if (rename != null && !rename.equals("")) {
          log.debug("Rename: '{}'", rename);

          if (FilenameUtils.indexOfExtension(rename) > -1) {
            // The rename contains filename + extension
            fileName = rename;
          } else {
            // The rename only contains filename, so get extension from uploaded file
            String ext = FilenameUtils.getExtension(fileName);

            if (ext.equals("")) {
              fileName = rename;
            } else {
              fileName = rename + "." + ext;
            }
          }

          log.debug("Filename: '{}'", fileName);
        }

        // Now, we have read all parameters and the uploaded file
        if (action == UIFileUploadConstants.ACTION_INSERT) {
          if (fileName != null && !fileName.equals("")) {
            if (importZip && FilenameUtils.getExtension(fileName).equalsIgnoreCase("zip")) {
              log.debug("Import ZIP file '{}' into '{}'", fileName, path);
              String erroMsg = importZip(path, is);

              if (erroMsg == null) {
                sendResponse(out, action, fuResponse.get());
              } else {
                log.warn("erroMsg: {}", erroMsg);
                fuResponse.get().setError(erroMsg);
                sendResponse(out, action, fuResponse.get());
              }
            } else if (importZip && FilenameUtils.getExtension(fileName).equalsIgnoreCase("jar")) {
              log.debug("Import JAR file '{}' into '{}'", fileName, path);
              String erroMsg = importJar(path, is);

              if (erroMsg == null) {
                sendResponse(out, action, fuResponse.get());
              } else {
                fuResponse.get().setError(erroMsg);
                sendResponse(out, action, fuResponse.get());
              }
            } else if (FilenameUtils.getExtension(fileName).equalsIgnoreCase("eml")) {
              log.debug("import EML file '{}' into '{}'", fileName, path);
              String erroMsg = importEml(path, is);

              if (erroMsg == null) {
                sendResponse(out, action, fuResponse.get());
              } else {
                log.warn("erroMsg: {}", erroMsg);
                fuResponse.get().setError(erroMsg);
                sendResponse(out, action, fuResponse.get());
              }
            } else if (FilenameUtils.getExtension(fileName).equalsIgnoreCase("msg")) {
              log.debug("import MSG file '{}' into '{}'", fileName, path);
              String erroMsg = importMsg(path, is);

              if (erroMsg == null) {
                sendResponse(out, action, fuResponse.get());
              } else {
                log.warn("erroMsg: {}", erroMsg);
                fuResponse.get().setError(erroMsg);
                sendResponse(out, action, fuResponse.get());
              }
            } else {
              fileName = FilenameUtils.getName(fileName);
              log.debug(
                  "Upload file '{}' into '{} ({})'",
                  new Object[] {fileName, path, FormatUtil.formatSize(size)});
              String mimeType = MimeTypeConfig.mimeTypes.getContentType(fileName.toLowerCase());
              Document doc = new Document();
              doc.setPath(path + "/" + fileName);

              if (convertToPdf && !mimeType.equals(MimeTypeConfig.MIME_PDF)) {
                DocConverter converter = DocConverter.getInstance();

                if (converter.convertibleToPdf(mimeType)) {
                  // Changing path name
                  if (fileName.contains(".")) {
                    fileName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + "pdf";
                  } else {
                    fileName += ".pdf";
                  }

                  doc.setPath(path + "/" + fileName);
                  tmp = File.createTempFile("okm", ".tmp");
                  java.io.File tmpPdf = File.createTempFile("okm", ".pdf");
                  FileOutputStream fos = new FileOutputStream(tmp);
                  IOUtils.copy(is, fos);
                  converter.doc2pdf(tmp, mimeType, tmpPdf);
                  is = new FileInputStream(tmpPdf);
                  doc = OKMDocument.getInstance().create(null, doc, is);
                  fuResponse.get().setPath(doc.getPath());
                  uploadedUuid = doc.getUuid();
                  tmp.delete();
                  tmpPdf.delete();
                  tmp = null;
                } else {
                  throw new ConversionException("Not convertible to pdf");
                }
              } else {
                log.debug("Wizard: {}", fuResponse);

                if (Config.REPOSITORY_NATIVE) {
                  doc = new DbDocumentModule().create(null, doc, is, size, null, fuResponse);
                  fuResponse.get().setPath(doc.getPath());
                  uploadedUuid = doc.getUuid();
                } else {
                  doc = new JcrDocumentModule().create(null, doc, is);
                  fuResponse.get().setPath(doc.getPath());
                  uploadedUuid = doc.getUuid();
                }

                log.debug("Wizard: {}", fuResponse);
              }

              // Return the path of the inserted document in response
              sendResponse(out, action, fuResponse.get());
            }
          }
        } else if (action == UIFileUploadConstants.ACTION_UPDATE) {
          log.debug("File updated: {}", path);

          // http://en.wikipedia.org/wiki/Truth_table#Applications => ¬p ∨ q
          if (!Config.SYSTEM_DOCUMENT_NAME_MISMATCH_CHECK
              || PathUtils.getName(path).equals(fileName)) {
            Document doc = OKMDocument.getInstance().getProperties(null, path);

            if (autoCheckOut) {
              // This is set from the Uploader applet
              OKMDocument.getInstance().checkout(null, path);
            }

            if (Config.REPOSITORY_NATIVE) {
              new DbDocumentModule().checkin(null, path, is, size, comment, null);
              fuResponse.get().setPath(path);
              uploadedUuid = doc.getUuid();
            } else {
              new JcrDocumentModule().checkin(null, path, is, comment);
              fuResponse.get().setPath(path);
              uploadedUuid = doc.getUuid();
            }

            // Return the path of the inserted document in response
            sendResponse(out, action, fuResponse.get());
          } else {
            fuResponse
                .get()
                .setError(
                    ErrorCode.get(
                        ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_DocumentNameMismatch));
            sendResponse(out, action, fuResponse.get());
          }
        } else if (action == UIFileUploadConstants.ACTION_FOLDER) {
          log.debug("Folder create: {}", path);
          Folder fld = new Folder();
          fld.setPath(path + "/" + folder);
          fld = OKMFolder.getInstance().create(null, fld);
          fuResponse.get().setPath(fld.getPath());
          sendResponse(out, action, fuResponse.get());
        }

        listener.setUploadFinish(true); // Mark uploading operation has finished

        // If the document have been added to the repository, perform user notification
        if ((action == UIFileUploadConstants.ACTION_INSERT
                || action == UIFileUploadConstants.ACTION_UPDATE)
            & notify) {
          List<String> userNames =
              new ArrayList<String>(
                  Arrays.asList(users.isEmpty() ? new String[0] : users.split(",")));
          List<String> roleNames =
              new ArrayList<String>(
                  Arrays.asList(roles.isEmpty() ? new String[0] : roles.split(",")));

          for (String role : roleNames) {
            List<String> usersInRole = OKMAuth.getInstance().getUsersByRole(null, role);

            for (String user : usersInRole) {
              if (!userNames.contains(user)) {
                userNames.add(user);
              }
            }
          }

          String notifyPath = URLDecoder.decode(fuResponse.get().getPath(), "UTF-8");
          OKMNotification.getInstance().notify(null, notifyPath, userNames, message, false);
        }

        // After uploading redirects to some URL
        if (redirect) {
          ServletContext sc = getServletContext();
          request.setAttribute("docPath", fuResponse.get().getPath());
          request.setAttribute("uuid", uploadedUuid);
          sc.setAttribute("docPath", fuResponse.get().getPath());
          sc.setAttribute("uuid", uploadedUuid);
          sc.getRequestDispatcher(redirectURL).forward(request, response);
        }
      }
    } catch (AccessDeniedException e) {
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_AccessDenied));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (PathNotFoundException e) {
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_PathNotFound));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (ItemExistsException e) {
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_ItemExists));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (UnsupportedMimeTypeException e) {
      fuResponse
          .get()
          .setError(
              ErrorCode.get(
                  ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_UnsupportedMimeType));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (FileSizeExceededException e) {
      fuResponse
          .get()
          .setError(
              ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_FileSizeExceeded));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (LockException e) {
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Lock));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (VirusDetectedException e) {
      fuResponse
          .get()
          .setError(VirusDetectedException.class.getSimpleName() + " : " + e.getMessage());
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (VersionException e) {
      log.error(e.getMessage(), e);
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Version));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (RepositoryException e) {
      log.error(e.getMessage(), e);
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Repository));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (DatabaseException e) {
      log.error(e.getMessage(), e);
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Database));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (ExtensionException e) {
      log.error(e.getMessage(), e);
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Extension));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (IOException e) {
      log.error(e.getMessage(), e);
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_IO));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (ConversionException e) {
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Conversion));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      fuResponse.get().setError(e.toString());
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } finally {
      if (tmp != null) {
        tmp.delete();
      }

      IOUtils.closeQuietly(is);
      out.flush();
      IOUtils.closeQuietly(out);
      System.gc();
    }
  }