/**
   * Constructs a new MultipartRequest to handle the specified request, saving any uploaded files to
   * the given directory, and limiting the upload size to the specified length. If the content is
   * too large, an IOException is thrown. This constructor actually parses the
   * <tt>multipart/form-data</tt> and throws an IOException if there's any problem reading or
   * parsing the request.
   *
   * <p>To avoid file collisions, this constructor takes an implementation of the FileRenamePolicy
   * interface to allow a pluggable rename policy.
   *
   * @param request the servlet request.
   * @param saveDirectory the directory in which to save any uploaded files.
   * @param maxPostSize the maximum size of the POST content.
   * @param encoding the encoding of the response, such as ISO-8859-1
   * @param policy a pluggable file rename policy
   * @exception IOException if the uploaded content is larger than <tt>maxPostSize</tt> or there's a
   *     problem reading or parsing the request.
   */
  public CosMultipartRequest(
      HttpServletRequest request,
      String saveDirectory,
      int maxPostSize,
      String encoding,
      FileRenamePolicy policy)
      throws IOException {
    // Sanity check values
    if (request == null) throw new IllegalArgumentException("request cannot be null");
    if (saveDirectory == null) throw new IllegalArgumentException("saveDirectory cannot be null");
    if (maxPostSize <= 0) {
      throw new IllegalArgumentException("maxPostSize must be positive");
    }

    // Save the dir
    File dir = new File(saveDirectory);

    // Check saveDirectory is truly a directory
    if (!dir.isDirectory()) throw new IllegalArgumentException("Not a directory: " + saveDirectory);

    // Check saveDirectory is writable
    if (!dir.canWrite()) throw new IllegalArgumentException("Not writable: " + saveDirectory);

    // Parse the incoming multipart, storing files in the dir provided,
    // and populate the meta objects which describe what we found
    MultipartParser parser = new MultipartParser(request, maxPostSize, true, true, encoding);

    // Some people like to fetch query string parameters from
    // MultipartRequest, so here we make that possible.  Thanks to
    // Ben Johnson, [email protected], for the idea.
    if (request.getQueryString() != null) {
      // Let HttpUtils create a name->String[] structure
      Map<String, String[]> queryParameters =
          RequestUtils.parseQueryString(request.getQueryString());
      // For our own use, name it a name->Vector structure
      for (Entry<String, String[]> entry : queryParameters.entrySet()) {
        parameters.put(entry.getKey(), Arrays.asList(entry.getValue()));
      }
    }

    Part part;
    while ((part = parser.readNextPart()) != null) {
      String name = part.getName();
      if (name == null) {
        throw new IOException("Malformed input: parameter name missing (known Opera 7 bug)");
      }
      if (part.isParam()) {
        // It's a parameter part, add it to the vector of values
        ParamPart paramPart = (ParamPart) part;
        String value = paramPart.getStringValue();
        List<String> existingValues = parameters.get(name);
        if (existingValues == null) {
          existingValues = new ArrayList<String>();
          parameters.put(name, existingValues);
        }
        existingValues.add(value);
      } else if (part.isFile()) {
        // It's a file part
        FilePart filePart = (FilePart) part;
        String fileName = filePart.getFileName();
        if (fileName != null) {
          filePart.setRenamePolicy(policy); // null policy is OK
          // The part actually contained a file
          filePart.writeTo(dir);
          files.put(
              name,
              new UploadedFile(
                  dir.toString(), filePart.getFileName(), fileName, filePart.getContentType()));
        } else {
          // The field did not contain a file
          files.put(name, new UploadedFile(null, null, null, null));
        }
      }
    }
  }
  /**
   * Displays the Create Discussion page for a HTTP Get, or creates a Discussion Thread for a HTTP
   * Post
   *
   * <p>- Requires a cookie for the session user - Requires a groupId request parameter for a GET -
   * Requires a groupId and threadName request parameter for a POST - Requires a document request
   * part for a POST
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void createDiscussionAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    Map<String, Object> viewData = new HashMap<>();

    if (req.getMethod() == HttpMethod.Get) {
      viewData.put("title", "Create Discussion");
      viewData.put("groupId", req.getParameter("groupId"));

      view(req, res, "/views/group/CreateDiscussion.jsp", viewData);
      return;
    } else if (req.getMethod() == HttpMethod.Post) {
      // save discussion
      GroupManager groupMan = new GroupManager();
      DiscussionThread thread = new DiscussionThread();
      int groupId = Integer.parseInt(req.getParameter("groupId"));
      thread.setGroupId(groupId);
      thread.setGroup(groupMan.get(groupId));
      thread.setThreadName(req.getParameter("threadName"));

      DiscussionManager dm = new DiscussionManager();
      dm.createDiscussion(thread);

      try {
        Part documentPart = req.getPart("document");

        // if we have a document to upload
        if (documentPart.getSize() > 0) {
          String uuid = DocumentController.saveDocument(this.getServletContext(), documentPart);
          Document doc = new Document();
          doc.setDocumentName(getFileName(documentPart));
          doc.setDocumentPath(uuid);
          doc.setVersionNumber(1);
          doc.setThreadId(thread.getId());
          doc.setGroupId(thread.getGroupId());

          DocumentManager docMan = new DocumentManager();
          docMan.createDocument(doc);

          // Get uploading User
          HttpSession session = req.getSession();
          Session userSession = (Session) session.getAttribute("userSession");
          User uploader = userSession.getUser();

          // Create a notification to all in the group
          NotificationManager notificationMan = new NotificationManager();
          groupMan = new GroupManager();
          List<User> groupUsers = groupMan.getGroupUsers(groupId);

          for (User u : groupUsers) {
            Notification notification =
                new Notification(
                    u.getId(),
                    u,
                    groupId,
                    null,
                    "User " + uploader.getFullName() + " has uploaded a document",
                    "/document/document?documentId=" + doc.getId());

            notificationMan.createNotification(notification);
          }
        }
      } catch (Exception e) {
        logger.log(Level.SEVERE, "Document save error", e);
      }

      redirectToLocal(req, res, "/group/discussion/?threadId=" + thread.getId());
      return;
    }
    httpNotFound(req, res);
  }