/** Start OpenKM and possible repository and database initialization */
  public static synchronized void start() throws ServletException {
    SystemAuthentication systemAuth = new SystemAuthentication();

    if (running) {
      throw new IllegalStateException("OpenKM already started");
    }

    try {
      log.info("*** Repository initializing... ***");

      if (Config.REPOSITORY_NATIVE) {
        systemAuth.enable();
        DbRepositoryModule.initialize();
        systemAuth.disable();
      } else {
        JcrRepositoryModule.initialize();
      }

      log.info("*** Repository initialized ***");
    } catch (Exception e) {
      throw new ServletException(e.getMessage(), e);
    }

    if (Config.USER_ITEM_CACHE) {
      // Deserialize
      try {
        log.info("*** Cache deserialization ***");
        UserItemsManager.deserialize();
        UserNodeKeywordsManager.deserialize();
      } catch (DatabaseException e) {
        log.warn(e.getMessage(), e);
      }
    }

    log.info("*** User database initialized ***");

    if (!Config.REPOSITORY_NATIVE) {
      // Test for datastore
      SessionImpl si = (SessionImpl) JcrRepositoryModule.getSystemSession();

      if (((RepositoryImpl) si.getRepository()).getDataStore() == null) {
        hasConfiguredDataStore = false;
      } else {
        hasConfiguredDataStore = true;
      }
    }

    // Create timers
    uiTimer = new Timer("Update Info");
    wdTimer = new Timer("Session Watchdog");
    cronTimer = new Timer("Crontab Manager");
    uinTimer = new Timer("User Interface Notification");
    riTimer = new Timer("Repository Info", true);
    umiTimer = new Timer("User Mail Importer");
    dsgcTimer = new Timer("Datastore Garbage Collector");
    tewTimer = new Timer("Text Extractor Worker", true);

    // Workflow
    log.info("*** Initializing workflow engine... ***");
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    jbpmContext.setSessionFactory(HibernateUtil.getSessionFactory());
    jbpmContext.getGraphSession();
    jbpmContext.getJbpmConfiguration().getJobExecutor().start(); // startJobExecutor();
    jbpmContext.close();

    // Mime types
    log.info("*** Initializing MIME types... ***");
    MimeTypeConfig.loadMimeTypes();

    if (Config.UPDATE_INFO) {
      log.info("*** Activating update info ***");
      ui = new UpdateInfo();
      uiTimer.schedule(ui, 1000, 24 * 60 * 60 * 1000); // First in 1 seg, next each 24 hours
    }

    log.info("*** Activating watchdog ***");
    wd = new Watchdog();
    wdTimer.schedule(wd, 60 * 1000, 5 * 60 * 1000); // First in 1 min, next each 5 mins

    log.info("*** Activating cron ***");
    cron = new Cron();
    Calendar calCron = Calendar.getInstance();
    calCron.add(Calendar.MINUTE, 1);
    calCron.set(Calendar.SECOND, 0);
    calCron.set(Calendar.MILLISECOND, 0);

    // Round begin to next minute, 0 seconds, 0 miliseconds
    cronTimer.scheduleAtFixedRate(
        cron, calCron.getTime(), 60 * 1000); // First in 1 min, next each 1 min

    log.info("*** Activating UI Notification ***");
    uin = new UINotification();

    // First in 1 second next in x minutes
    uinTimer.scheduleAtFixedRate(
        uin, 1000, TimeUnit.MINUTES.toMillis(Config.SCHEDULE_UI_NOTIFICATION));

    log.info("*** Activating repository info ***");
    ri = new RepositoryInfo();

    // First in 1 min, next each X minutes
    riTimer.schedule(ri, 60 * 1000, TimeUnit.MINUTES.toMillis(Config.SCHEDULE_REPOSITORY_INFO));

    if (Config.MANAGED_TEXT_EXTRACTION_SCHEDULE > 0) {
      log.info("*** Activating text extractor worker ***");
      tew = new TextExtractorWorker();

      // First in 1 min, next each x minutes
      tewTimer.schedule(
          tew, 60 * 1000, TimeUnit.MINUTES.toMillis(Config.MANAGED_TEXT_EXTRACTION_SCHEDULE));
    }

    if (Config.SCHEDULE_MAIL_IMPORTER > 0) {
      log.info("*** Activating user mail importer ***");
      umi = new UserMailImporter();

      // First in 5 mins, next each x minutes
      umiTimer.schedule(
          umi, 5 * 60 * 1000, TimeUnit.MINUTES.toMillis(Config.SCHEDULE_MAIL_IMPORTER));
    } else {
      log.info("*** User mail importer disabled ***");
    }

    // Datastore garbage collection
    if (!Config.REPOSITORY_NATIVE && hasConfiguredDataStore) {
      log.info("*** Activating datastore garbage collection ***");
      dsgc = new DataStoreGarbageCollector();
      Calendar calGc = Calendar.getInstance();
      calGc.add(Calendar.DAY_OF_YEAR, 1);
      calGc.set(Calendar.HOUR_OF_DAY, 0);
      calGc.set(Calendar.MINUTE, 0);
      calGc.set(Calendar.SECOND, 0);
      calGc.set(Calendar.MILLISECOND, 0);
      dsgcTimer.scheduleAtFixedRate(
          dsgc, calGc.getTime(), 24 * 60 * 60 * 1000); // First tomorrow at 00:00, next
      // each 24 hours
    }

    try {
      log.info("*** Activating thesaurus repository ***");
      RDFREpository.getInstance();
    } catch (Exception e) {
      log.warn(e.getMessage(), e);
    }

    try {
      if (!Config.SYSTEM_OPENOFFICE_PATH.equals("")) {
        log.info("*** Start OpenOffice manager ***");
        DocConverter.getInstance().start();
      } else {
        log.warn("*** No OpenOffice manager configured ***");
      }
    } catch (Throwable e) {
      log.warn(e.getMessage(), e);
    }

    // Initialize plugin framework
    ExtensionManager.getInstance();

    try {
      log.info("*** Ejecute start script ***");
      File script = new File(Config.HOME_DIR + File.separatorChar + Config.START_SCRIPT);
      ExecutionUtils.runScript(script);
      File jar = new File(Config.HOME_DIR + File.separatorChar + Config.START_JAR);
      ExecutionUtils.getInstance().runJar(jar);
    } catch (Throwable e) {
      log.warn(e.getMessage(), e);
    }

    // OpenKM is started
    running = true;
  }
  /** Close OpenKM and free resources */
  public static synchronized void stop(GenericServlet gs) {
    if (!running) {
      throw new IllegalStateException("OpenKM not started");
    }

    // Shutdown plugin framework
    ExtensionManager.getInstance().shutdown();

    try {
      if (!Config.SYSTEM_OPENOFFICE_PATH.equals("")) {
        if (log == null && gs != null) {
          gs.log("*** Shutting down OpenOffice manager ***");
        } else {
          log.info("*** Shutting down OpenOffice manager ***");
        }

        DocConverter.getInstance().stop();
      }
    } catch (Throwable e) {
      log.warn(e.getMessage(), e);
    }

    if (hasConfiguredDataStore) {
      if (log == null && gs != null)
        gs.log("*** Shutting down datastore garbage collection... ***");
      else log.info("*** Shutting down datastore garbage collection... ***");
      dsgc.cancel();
    }

    if (Config.SCHEDULE_MAIL_IMPORTER > 0) {
      if (log == null && gs != null) gs.log("*** Shutting down user mail importer ***");
      else log.info("*** Shutting down user mail importer ***");
      umi.cancel();
    }

    if (Config.MANAGED_TEXT_EXTRACTION_SCHEDULE > 0) {
      if (log == null && gs != null) gs.log("*** Shutting down text extractor worker ***");
      else log.info("*** Shutting down text extractor worker ***");
      tew.cancel();
    }

    if (log == null && gs != null) gs.log("*** Shutting down repository info... ***");
    else log.info("*** Shutting down repository info... ***");
    ri.cancel();

    if (log == null && gs != null) gs.log("*** Shutting down UI Notification... ***");
    else log.info("*** Shutting down UI Notification... ***");
    uin.cancel();

    if (log == null && gs != null) gs.log("*** Shutting down cron... ***");
    else log.info("*** Shutting down cron... ***");
    cron.cancel();

    if (log == null && gs != null) gs.log("*** Shutting down watchdog... ***");
    else log.info("*** Shutting down watchdog... ***");
    wd.cancel();

    if (Config.UPDATE_INFO) {
      if (log == null && gs != null) gs.log("*** Shutting down update info... ***");
      else log.info("*** Shutting down update info... ***");
      ui.cancel();
    }

    // Cancel timers
    dsgcTimer.cancel();
    umiTimer.cancel();
    riTimer.cancel();
    cronTimer.cancel();
    uinTimer.cancel();
    wdTimer.cancel();
    uiTimer.cancel();
    tewTimer.cancel();

    if (log == null && gs != null) gs.log("*** Shutting down repository... ***");
    else log.info("*** Shutting down repository... ***");

    if (Config.USER_ITEM_CACHE) {
      // Serialize
      try {
        log.info("*** Cache serialization ***");
        UserItemsManager.serialize();
        UserNodeKeywordsManager.serialize();
      } catch (DatabaseException e) {
        log.warn(e.getMessage(), e);
      }
    }

    try {
      // Preserve system user config
      if (!Config.REPOSITORY_NATIVE) {
        JcrRepositoryModule.shutdown();
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }

    if (log == null && gs != null) gs.log("*** Repository shutted down ***");
    else log.info("*** Repository shutted down ***");

    try {
      if (log == null && gs != null) gs.log("*** Ejecute stop script ***");
      else log.info("*** Ejecute stop script ***");
      File script = new File(Config.HOME_DIR + File.separatorChar + Config.STOP_SCRIPT);
      ExecutionUtils.runScript(script);
      File jar = new File(Config.HOME_DIR + File.separatorChar + Config.STOP_JAR);
      ExecutionUtils.getInstance().runJar(jar);
    } catch (Throwable e) {
      log.warn(e.getMessage(), e);
    }

    if (log == null && gs != null) gs.log("*** Shutting down workflow engine... ***");
    else log.info("*** Shutting down workflow engine... ***");
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    jbpmContext.getJbpmConfiguration().getJobExecutor().stop();
    jbpmContext.getJbpmConfiguration().close();
    jbpmContext.close();

    // OpenKM is stopped
    running = false;
  }
  @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();
    }
  }