Пример #1
0
 @Override
 public List<GWTUser> getLoggedUsers() throws OKMException {
   List<GWTUser> users = new ArrayList<GWTUser>();
   updateSessionManager();
   try {
     for (String userId : manager.getLoggedUsers()) {
       GWTUser user = new GWTUser();
       user.setId(userId);
       user.setUsername(OKMAuth.getInstance().getName(null, userId));
       users.add(user);
     }
   } catch (PrincipalAdapterException e) {
     log.error(e.getMessage(), e);
     throw new OKMException(
         ErrorCode.get(ErrorCode.ORIGIN_OKMChatService, ErrorCode.CAUSE_PrincipalAdapter),
         e.getMessage());
   }
   return users;
 }
Пример #2
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();
    }
  }