/**
   * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's
   * multipart classes (see class description).
   *
   * @param saveDir the directory to save off the file
   * @param servletRequest the request containing the multipart
   * @throws java.io.IOException is thrown if encoding fails.
   */
  @SuppressWarnings("unchecked")
  @Override
  public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    // Make sure that the data is written to file
    fac.setSizeThreshold(0);
    if (saveDir != null) {
      fac.setRepository(new File(saveDir));
    }

    ProgressMonitor monitor = null;
    // Parse the request
    try {
      ServletFileUpload upload = new ServletFileUpload(fac);
      upload.setSizeMax(maxSize);

      monitor = new ProgressMonitor();
      upload.setProgressListener(monitor);
      servletRequest.getSession().setAttribute(ProgressMonitor.SESSION_PROGRESS_MONITOR, monitor);

      List<FileItem> items = upload.parseRequest(createRequestContext(servletRequest));

      for (FileItem item1 : items) {
        FileItem item = item1;

        if (log.isDebugEnabled()) {
          log.debug("Found item " + item.getFieldName());
        }
        if (item.isFormField()) {
          if (log.isDebugEnabled()) {
            log.debug("Item is a normal form field");
          }
          List<String> values;
          if (params.get(item.getFieldName()) != null) {
            values = params.get(item.getFieldName());
          } else {
            values = new ArrayList<String>();
          }

          // note: see http://jira.opensymphony.com/browse/WW-633
          // basically, in some cases the charset may be null, so
          // we're just going to try to "other" method (no idea if this
          // will work)
          String charset = servletRequest.getCharacterEncoding();
          if (charset != null) {
            values.add(item.getString(charset));
          } else {
            values.add(item.getString());
          }
          params.put(item.getFieldName(), values);
        } else {
          if (log.isDebugEnabled()) {
            log.debug("Item is a file upload");
          }
          List<FileItem> values;
          if (files.get(item.getFieldName()) != null) {
            values = files.get(item.getFieldName());
          } else {
            values = new ArrayList<FileItem>();
          }

          values.add(item);
          files.put(item.getFieldName(), values);
        }
      }
    } catch (FileUploadException e) {
      e.printStackTrace();
      if (monitor != null) monitor.abort();
      log.error(e);
      errors.add(e.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
      if (monitor != null) monitor.abort();
    }
  }
Пример #2
0
 private ServletFileUpload createUpload() {
   ServletFileUpload upload = new ServletFileUpload();
   upload.setFileSizeMax(handler.getMaxFileSize());
   upload.setProgressListener(createProgressListener());
   return upload;
 }
Пример #3
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String saveFilename = null;
    String realSavePath = null;
    String filename = null;

    Users users = (Users) request.getSession().getAttribute("loginuser");
    int sid = users.getIdusers();

    // 得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
    String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
    // 上传时生成的临时文件保存目录
    String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
    File tmpFile = new File(tempPath);
    if (!tmpFile.exists()) {
      // 创建临时目录
      tmpFile.mkdir();
    }

    // 消息提示
    String message = "";
    try {
      // 使用Apache文件上传组件处理文件上传步骤:
      // 1、创建一个DiskFileItemFactory工厂
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // 设置工厂的缓冲区的大小,当上传的文件大小超过缓冲区的大小时,就会生成一个临时文件存放到指定的临时目录当中。
      factory.setSizeThreshold(1024 * 100); // 设置缓冲区的大小为100KB,如果不指定,那么缓冲区的大小默认是10KB
      // 设置上传时生成的临时文件的保存目录
      factory.setRepository(tmpFile);
      // 2、创建一个文件上传解析器
      ServletFileUpload upload = new ServletFileUpload(factory);
      // 监听文件上传进度
      upload.setProgressListener(
          new ProgressListener() {
            public void update(long pBytesRead, long pContentLength, int arg2) {
              System.out.println("文件大小为:" + pContentLength + ",当前已处理:" + pBytesRead);
              /**
               * 文件大小为:14608,当前已处理:4096 文件大小为:14608,当前已处理:7367 文件大小为:14608,当前已处理:11419
               * 文件大小为:14608,当前已处理:14608
               */
            }
          });
      // 解决上传文件名的中文乱码
      upload.setHeaderEncoding("gb2312");
      // 3、判断提交上来的数据是否是上传表单的数据
      if (!ServletFileUpload.isMultipartContent(request)) {
        // 按照传统方式获取数据
        return;
      }

      // 设置上传单个文件的大小的最大值,目前是设置为1024*1024字节,也就是1MB
      upload.setFileSizeMax(1024 * 1024);
      // 设置上传文件总量的最大值,最大值=同时上传的多个文件的大小的最大值的和,目前设置为10MB
      upload.setSizeMax(1024 * 1024 * 10);
      // 4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
      List<FileItem> list = upload.parseRequest(request);
      for (FileItem item : list) {
        // 如果fileitem中封装的是普通输入项的数据
        if (item.isFormField()) {
          String name = item.getFieldName();
          // 解决普通输入项的数据的中文乱码问题
          String value = item.getString("gb2312");
          // value = new String(value.getBytes("iso8859-1"),"UTF-8");
          System.out.println(name + "=" + value);
        } else { // 如果fileitem中封装的是上传文件
          // 得到上传的文件名称,
          filename = item.getName();
          System.out.println(filename);
          if (filename == null || filename.trim().equals("")) {
            continue;
          }
          // 注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如:  c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt
          // 处理获取到的上传文件的文件名的路径部分,只保留文件名部分
          filename = filename.substring(filename.lastIndexOf("\\") + 1);
          // 得到上传文件的扩展名
          String fileExtName = filename.substring(filename.lastIndexOf(".") + 1);
          // 如果需要限制上传的文件类型,那么可以通过文件的扩展名来判断上传的文件类型是否合法
          System.out.println("上传的文件的扩展名是:" + fileExtName);
          // 获取item中的上传文件的输入流
          InputStream in = item.getInputStream();
          // 得到文件保存的名称
          saveFilename = makeFileName(filename);
          // 得到文件的保存目录
          realSavePath = makePath(saveFilename, savePath);
          // 创建一个文件输出流
          FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename);
          // 创建一个缓冲区
          byte buffer[] = new byte[1024];
          // 判断输入流中的数据是否已经读完的标识
          int len = 0;
          // 循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
          while ((len = in.read(buffer)) > 0) {
            // 使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
            out.write(buffer, 0, len);
          }
          // 关闭输入流
          in.close();
          // 关闭输出流
          out.close();
          // 删除处理文件上传时生成的临时文件
          // item.delete();
          message = "文件上传成功!";

          Files files = new Files();
          files.setFilename(filename);
          files.setFileonlyname(saveFilename);
          files.setFilesroute(realSavePath);

          FileDao fileDao = new FileDao();
          fileDao.addOne(files, sid);
        }
      }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
      e.printStackTrace();
      request.setAttribute("message", "单个文件超出最大值!!!");
      request.getRequestDispatcher("user_view/file/file_message.jsp").forward(request, response);
      return;
    } catch (FileUploadBase.SizeLimitExceededException e) {
      e.printStackTrace();
      request.setAttribute("message", "上传文件的总的大小超出限制的最大值!!!");
      request.getRequestDispatcher("user_view/file/file_message.jsp").forward(request, response);
      return;
    } catch (Exception e) {
      message = "文件上传失败!";
      e.printStackTrace();
    }

    request.setAttribute("message", message);
    request.getRequestDispatcher("/user_view/file/file_message.jsp").forward(request, response);
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("application/octet-stream");
    try {
      if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory fif = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(fif);
        List items = sfu.parseRequest(request);
        Iterator itr = items.iterator();
        FileItem image1 = null, image2 = null;
        if (itr.hasNext()) image1 = (FileItem) itr.next();
        if (itr.hasNext()) image2 = (FileItem) itr.next();
        byte[] bimage1 = new byte[(int) image1.getSize()];
        byte[] bimage2 = new byte[(int) image2.getSize()];

        InputStream in = image1.getInputStream();
        in.read(bimage1);
        in.close();
        in = image2.getInputStream();
        in.read(bimage2);
        byte[] img1 = new byte[bimage1.length];
        for (int i = 0; i < bimage1.length; ++i) img1[i] = bimage1[i];
        ByteArrayInputStream bais = new ByteArrayInputStream(img1);
        BufferedImage bufimg1 = ImageIO.read(bais);
        byte[] img2 = new byte[bimage2.length];
        for (int i = 0; i < bimage2.length; ++i) img2[i] = bimage2[i];
        ByteArrayInputStream bais1 = new ByteArrayInputStream(img2);
        BufferedImage bufimg2 = ImageIO.read(bais1);
        ProgressListener progressListener =
            new ProgressListener() {
              public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("We are currently reading item " + pItems);
                if (pContentLength == -1) {
                  System.out.println("So far, " + pBytesRead + " bytes have been read.");
                } else {
                  System.out.println(
                      "So far, " + pBytesRead + " of " + pContentLength + " bytes have been read.");
                }
              }
            };
        sfu.setProgressListener(progressListener);
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection wsdircon =
            DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:XE", "system", "imbagaming");
        PreparedStatement st =
            wsdircon.prepareStatement(
                "SELECT wsdl,count FROM WEBSERVICEDATABASE WHERE panorama='yes' and status='up' ORDER BY count");
        ResultSet rs = st.executeQuery();
        String wsdlString = "";
        int count = 0;
        if (rs.next()) {
          System.out.println(wsdlString = rs.getString(1));
          count = rs.getInt(2);
        } else {
          response.sendRedirect("effectchoosere.htm");
        }
        PreparedStatement st1 =
            wsdircon.prepareStatement(
                "UPDATE WEBSERVICEDATABASE SET count="
                    + (count
                        + (bufimg1.getWidth() * bufimg1.getHeight()
                            + bufimg2.getWidth() * bufimg2.getHeight()))
                    + "WHERE wsdl=\'"
                    + wsdlString
                    + "\'");
        System.out.println(count);
        st1.execute();

        // parse the wsdl and get the details from it

        URL wsdl = new URL(wsdlString);
        // URL wsdl=new URL("http://localhost:8084/IPWebServices/ImageProcess?wsdl");
        URLConnection conn = wsdl.openConnection();
        InputStream wsdlin = conn.getInputStream();
        BufferedReader bin = new BufferedReader(new InputStreamReader(wsdlin));
        char[] asdf = new char[1024 * 100];
        bin.read(asdf);
        String ss = new String(asdf);
        bin.close();
        wsdlin.close();
        String[] info = new String[6];
        info[0] = ss.substring(ss.indexOf("targetNamespace=\"") + 17, ss.indexOf("\" name"));
        System.out.println(info[0]);
        info[1] = ss.substring(ss.indexOf("name=\"") + 6, ss.indexOf("\">"));
        System.out.println(info[1]);
        info[2] = ss.substring(ss.indexOf("port name=\"") + 11, ss.indexOf("\" binding=\""));
        System.out.println(info[2]);
        info[3] = ss.substring(ss.indexOf("<message name=\"") + 15, ss.indexOf("\">\n<part"));

        // DII

        String svcName = info[1];
        String ns = info[0];
        QName svcQname = new QName(ns, svcName);
        String portName = info[2];
        QName portQname = new QName(ns, portName);
        Service service = Service.create(wsdl, svcQname);
        Dispatch<SOAPMessage> dispatch =
            service.createDispatch(portQname, SOAPMessage.class, Service.Mode.MESSAGE);
        SOAPMessage soapMsg = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMsg.getSOAPPart();
        SOAPEnvelope soapEnv = soapPart.getEnvelope();
        SOAPBody soapBody = soapEnv.getBody();
        Name bodyName = SOAPFactory.newInstance().createName("gogogo_1", "m", ns);
        SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName);
        Name param1 = SOAPFactory.newInstance().createName("image1");
        Name param2 = SOAPFactory.newInstance().createName("image2");
        Name param3 = SOAPFactory.newInstance().createName("effect");
        SOAPElement seimage1 = bodyElement.addChildElement(param1);
        SOAPElement seimage2 = bodyElement.addChildElement(param2);
        SOAPElement effect = bodyElement.addChildElement(param3);
        seimage1.addTextNode(Base64.encode(bimage1));
        seimage2.addTextNode(Base64.encode(bimage2));
        effect.addTextNode("panorama");
        SOAPMessage resp = dispatch.invoke(soapMsg);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // handle the response from web service to obtain the processed image

        resp.writeTo(baos);
        String saveImg = new String(baos.toByteArray());
        int lastI = saveImg.lastIndexOf("<return>") + 8;
        int firstI = saveImg.indexOf("</return>");
        saveImg = saveImg.substring(lastI, firstI);
        byte[] dwnld = new byte[saveImg.length()];
        dwnld = Base64.decode(saveImg);
        // decrease the count in the service directory

        PreparedStatement stc =
            wsdircon.prepareStatement(
                "SELECT count FROM WEBSERVICEDATABASE WHERE wsdl='" + wsdlString + "'");
        rs = stc.executeQuery();
        if (rs.next()) count = rs.getInt(1);
        count -=
            (bufimg1.getWidth() * bufimg1.getHeight() + bufimg2.getWidth() * bufimg2.getHeight());
        if (count < 0) count = 0;
        PreparedStatement st2 =
            wsdircon.prepareStatement(
                "UPDATE WEBSERVICEDATABASE SET count="
                    + (count)
                    + "WHERE wsdl=\'"
                    + wsdlString
                    + "\'");
        System.out.println(count);
        st2.execute();
        wsdircon.close();
        // redirect user to the download page

        ServletOutputStream op = response.getOutputStream();
        ServletContext context = getServletConfig().getServletContext();
        String mimetype = context.getMimeType("application/octet-stream");
        response.setContentLength(dwnld.length);
        response.setHeader(
            "Content-Disposition", "attachment; filename=\"" + "processedImage.jpg" + "\"");
        int length = 0;
        byte[] bbuf = new byte[1000];
        ByteArrayInputStream iin = new ByteArrayInputStream(dwnld);
        while ((iin != null) && ((length = iin.read(bbuf)) != -1)) {
          op.write(bbuf, 0, length);
        }
        // in.close();
        iin.close();
        op.flush();
        op.close();
      }
    } catch (Exception e) {
      System.out.println(e);
    } finally {

    }
  }
Пример #5
0
  /**
   * This method parses the submit action, puts in session a listener where the progress status is
   * updated, and eventually stores the received data in the user session.
   *
   * <p>returns null in the case of success or a string with the error
   */
  @SuppressWarnings("unchecked")
  protected String parsePostRequest(HttpServletRequest request, HttpServletResponse response) {

    try {
      String delay = request.getParameter("delay");
      uploadDelay = Integer.parseInt(delay);
    } catch (Exception e) {
    }

    HttpSession session = request.getSession();

    logger.debug("UPLOAD-SERVLET (" + session.getId() + ") new upload request received.");

    AbstractUploadListener listener = getCurrentListener(request);
    if (listener != null) {
      if (listener.isFrozen() || listener.isCanceled() || listener.getPercent() >= 100) {
        removeCurrentListener(request);
      } else {
        String error = getMessage("busy");
        logger.error("UPLOAD-SERVLET (" + session.getId() + ") " + error);
        return error;
      }
    }
    // Create a file upload progress listener, and put it in the user session,
    // so the browser can use ajax to query status of the upload process
    listener = createNewListener(request);

    List<FileItem> uploadedItems;
    try {

      // Call to a method which the user can override
      checkRequest(request);

      // Create the factory used for uploading files,
      FileItemFactory factory = getFileItemFactory(request.getContentLength());
      ServletFileUpload uploader = new ServletFileUpload(factory);
      uploader.setSizeMax(maxSize);
      uploader.setProgressListener(listener);

      // Receive the files
      logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsing HTTP POST request ");
      uploadedItems = uploader.parseRequest(request);
      logger.debug(
          "UPLOAD-SERVLET ("
              + session.getId()
              + ") parsed request, "
              + uploadedItems.size()
              + " items received.");

      // Received files are put in session
      Vector<FileItem> sessionFiles = (Vector<FileItem>) getSessionFileItems(request);
      if (sessionFiles == null) {
        sessionFiles = new Vector<FileItem>();
      }

      String error = "";
      session.setAttribute(ATTR_LAST_FILES, uploadedItems);

      if (uploadedItems.size() > 0) {
        sessionFiles.addAll(uploadedItems);
        String msg = "";
        for (FileItem i : sessionFiles) {
          msg += i.getFieldName() + " => " + i.getName() + "(" + i.getSize() + " bytes),";
        }
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") puting items in session: " + msg);
        session.setAttribute(ATTR_FILES, sessionFiles);
      } else {
        logger.error("UPLOAD-SERVLET (" + session.getId() + ") error NO DATA received ");
        error += getMessage("no_data");
      }

      return error.length() > 0 ? error : null;

    } catch (SizeLimitExceededException e) {
      RuntimeException ex = new UploadSizeLimitException(e.getPermittedSize(), e.getActualSize());
      listener.setException(ex);
      throw ex;
    } catch (UploadSizeLimitException e) {
      listener.setException(e);
      throw e;
    } catch (UploadCanceledException e) {
      listener.setException(e);
      throw e;
    } catch (UploadTimeoutException e) {
      listener.setException(e);
      throw e;
    } catch (Exception e) {
      logger.error(
          "UPLOAD-SERVLET ("
              + request.getSession().getId()
              + ") Unexpected Exception -> "
              + e.getMessage()
              + "\n"
              + stackTraceToString(e));
      e.printStackTrace();
      RuntimeException ex = new UploadException(e);
      listener.setException(ex);
      throw ex;
    }
  }
Пример #6
0
  /**
   * 接收文件数据。
   *
   * @param name
   * @param request
   */
  public void receive(String name, HttpServletRequest request) {
    ServletFileUpload upload = new ServletFileUpload(this.factory);
    upload.setSizeMax(this.fileSizeMax);
    upload.setHeaderEncoding("UTF-8");

    // 设置文件上传进度监听器
    FileProgressListener pl = new FileProgressListener(name, request.getSession());
    upload.setProgressListener(pl);

    try {
      List<FileItem> items = upload.parseRequest(request);

      for (FileItem item : items) {
        if (!item.isFormField()) {
          // 原始文件名
          String originFileName = item.getName();

          // 文件后缀名
          String extension = FileUtils.extractFileExtension(originFileName);

          // 文件别名
          String aliasFileName = Utils.randomString(32) + "." + extension;

          FileType fileType = FileType.parseType(extension);

          if (FileType.UNKNOWN != fileType) {
            // 存储路径
            String strFilePath = this.storePath + name + "/";

            // 创建工作目录
            File filePath = new File(this.workPath + name + "/");
            if (!filePath.exists()) {
              filePath.mkdirs();
            }
            // 创建存储目录
            filePath = new File(strFilePath);
            if (!filePath.exists()) {
              filePath.mkdirs();
            }
            filePath = null;

            // 删除相同文件
            SharedFile sf = this.existSharedFile(originFileName);
            if (null != sf) {
              sf.delete();
              this.removeSharedFile(sf);
            }

            // 原文件
            File originFile = new File(strFilePath, originFileName);
            // 别名文件
            File aliasFile = new File(this.workPath + name + "/", aliasFileName);

            sf = new SharedFile(name, originFile, aliasFile, fileType, request.getSession());

            // 添加分享文件
            this.addSharedFile(sf);

            synchronized (pl.files) {
              pl.files.add(sf);
            }

            // 写文件
            item.write(originFile);

            request.getSession().setAttribute("name", name);
            request.getSession().setAttribute("filename", originFileName);
          } else {
            // 不支持的类型
            Logger.w(this.getClass(), "不支持的文件类型: " + originFileName);

            request.getSession().setAttribute("name", name);
            request.getSession().setAttribute("filename", originFileName);
            request.getSession().setAttribute("state", 300);
          }
        }
      }

      // 结束
      pl.finish();
    } catch (FileUploadException e) {
      Logger.log(this.getClass(), e, LogLevel.ERROR);
    } catch (Exception e) {
      Logger.log(this.getClass(), e, LogLevel.ERROR);
    }
  }
Пример #7
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();
    }
  }