/**
   * Creates a notification to a Group coordinator signaling that a user wants to join their group
   *
   * <p>- Requires a groupId request parameter for the GET
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void inviteAction(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<String, Object>();

    int groupId = Integer.parseInt(req.getParameter("groupId"));

    try {

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

      // Get the coordinator for the group
      GroupManager groupMan = new GroupManager();
      Group group = groupMan.get(groupId);
      User coordinator = groupMan.getCoordinator(groupId);

      // Send a notification to the coordinator for them to permit access to the group
      NotificationManager notificationMan = new NotificationManager();
      Notification notification =
          new Notification(
              coordinator.getId(),
              coordinator,
              groupId,
              group,
              user.getFullName() + " wants to join your group " + group.getGroupName(),
              "/home/notifications?addUserId=" + user.getId() + "&groupId=" + group.getId());
      notificationMan.createNotification(notification);

      redirectToLocal(req, res, "/home/dashboard");
      return;

    } catch (Exception e) {
      redirectToLocal(req, res, "/home/dashboard");
    }
  }
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    javax.servlet.jsp.PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;

    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html;charset=ISO-8859-1");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");

      User user = null;
      UserFactory userFactory = UserFactory.getInstance();
      String userID = request.getParameter("userID");
      try {
        UserFactory.init();
        user = userFactory.getUser(userID);
      } catch (Exception e) {
        throw new ServletException("Could not find user " + userID + " in user factory.", e);
      }

      out.write("\n");
      out.write("<html>\n");
      out.write("<head>\n    ");
      out.write("<title>WebTelemetry -  | User Management | User Detail");
      out.write("</title>\n    ");
      out.write("<base HREF=\"");
      out.print(org.opennms.web.Util.calculateUrlBase(request));
      out.write("\" />\n    ");
      out.write(
          "<link rel=\"stylesheet\" type=\"text/css\" href=\"/wt-portal/css/default.css\" />\n\t");
      out.write("<script type=\"text/javascript\" src=\"/wt-portal/javascript/WTtools.js\">");
      out.write("</script>\n");
      out.write("</head>\n");
      out.write("<body>\n");
      String title = " User Management  - Detail Summary for: " + userID;
      out.write("\n");
      /* ----  c:if ---- */
      org.apache.taglibs.standard.tag.el.core.IfTag _jspx_th_c_if_0 =
          (org.apache.taglibs.standard.tag.el.core.IfTag)
              _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.el.core.IfTag.class);
      _jspx_th_c_if_0.setPageContext(pageContext);
      _jspx_th_c_if_0.setParent(null);
      _jspx_th_c_if_0.setTest("${not param.orgAdminPopup}");
      int _jspx_eval_c_if_0 = _jspx_th_c_if_0.doStartTag();
      if (_jspx_eval_c_if_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
        do {
          out.write("\n    ");
          JspRuntimeLibrary.include(
              request,
              response,
              "/includes/header.jsp"
                  + "?"
                  + "title="
                  + java.net.URLEncoder.encode("" + title)
                  + "&"
                  + "help="
                  + "monitoringadmin%2Fusers%2FWTHelp_User.html",
              out,
              false);
          out.write("\n");
          int evalDoAfterBody = _jspx_th_c_if_0.doAfterBody();
          if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break;
        } while (true);
      }
      if (_jspx_th_c_if_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) return;
      _jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_0);
      out.write("\n");
      if (_jspx_meth_c_if_1(pageContext)) return;
      out.write("\n\n");
      out.write("<!-- BEGIN FRAMING TABLE:open tags, keep at 100%-->\n");
      out.write("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n\t");
      out.write("<tr>\n\t\t");
      out.write("<td width=\"10\">");
      out.write(
          "<img src=\"/wt-portal/images/spacers/spacer.gif\" height=\"1\" width=\"10\" border=\"0\" alt=\"WebTelemetry\">");
      out.write("</td>\n\t\t");
      out.write("<td>\n");
      out.write("<!-- END FRAMING TABLE:open tags, keep at 100%-->\n");
      out.write("<table width=\"98%\"border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n    ");
      out.write("<tr class=\"tableHeader\">\n        ");
      out.write("<td class=\"tableHeader\" colspan=\"2\">User Information");
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\" width=\"25%\">");
      out.write("<b>Full Name:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\" width=\"75%\">");
      out.print(user.getFullName());
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowDark\">\n        ");
      out.write("<td class=\"tableText\">");
      out.write("<b>Comments:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\">");
      out.print(user.getUserComments());
      out.write("</td>\n     ");
      out.write("</tr>\n");
      out.write("</table>\n");
      out.write("<br>\n");
      out.write("<table width=\"98%\"border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n    ");
      out.write("<tr class=\"tableHeader\">\n        ");
      out.write("<td class=\"tableHeader\" colspan=\"2\">Notification Information");
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\" width=\"25%\">");
      out.write("<b>Email:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\" width=\"75%\">");
      out.print(userFactory.getEmail(userID));
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowDark\">\n        ");
      out.write("<td class=\"tableText\">");
      out.write("<b>Pager Email:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\">");
      out.print(userFactory.getPagerEmail(userID));
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\">");
      out.write("<b>Numerical Service:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\">");
      out.print(userFactory.getNumericPage(userID));
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowDark\">\n        ");
      out.write("<td class=\"tableText\">");
      out.write("<b>Numerical Pin:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\">");
      out.print(userFactory.getNumericPin(userID));
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\">");
      out.write("<b>Text Service:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\">");
      out.print(userFactory.getTextPage(userID));
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowDark\">\n        ");
      out.write("<td class=\"tableText\">");
      out.write("<b>Text Pin:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\">");
      out.print(userFactory.getTextPin(userID));
      out.write("</td>\n     ");
      out.write("</tr>\n");
      out.write("</table>\n");
      out.write("<br>\n");
      out.write("<table width=\"98%\"border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n    ");
      out.write("<tr class=\"tableHeader\">\n        ");
      out.write("<td class=\"tableHeader\" colspan=\"2\">Duty Schedules");
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\" colspan=\"2\">");
      out.write("<br />\n        ");
      out.write("<!-- weekly schedule -->\n                ");
      out.write(
          "<table width=\"50%\" border=\"1\" bordercolor=\"#999999\" cellspacing=\"0\" cellpadding=\"2\" >\n\t\t\t");
      Collection dutySchedules = user.getDutyScheduleCollection();
      out.write("\n                        ");

      int i = 0;
      Iterator iter = dutySchedules.iterator();
      while (iter.hasNext()) {
        DutySchedule tmp = new DutySchedule((String) iter.next());
        Vector curSched = tmp.getAsVector();
        i++;

        out.write("\n                        ");
        out.write("<tr>\n                           ");
        ChoiceFormat days = new ChoiceFormat("0#Mo|1#Tu|2#We|3#Th|4#Fr|5#Sa|6#Su");
        for (int j = 0; j < 7; j++) {
          Boolean curDay = (Boolean) curSched.get(j);

          out.write("\n                          ");
          out.write("<td width=\"5%\">\n                           ");
          out.print((curDay.booleanValue() ? days.format(j) : "X"));
          out.write("\n                          ");
          out.write("</td>\n                          ");
        }
        out.write("\n                          ");
        out.write("<td width=\"5%\">\n                            ");
        out.print(curSched.get(7));
        out.write("\n                          ");
        out.write("</td>\n                          ");
        out.write("<td width=\"5%\">\n                            ");
        out.print(curSched.get(8));
        out.write("\n                          ");
        out.write("</td>\n                        ");
        out.write("</tr>\n                        ");
      }
      out.write("\n                      ");
      out.write("</table>\n        ");
      out.write("<!-- end weekly schedule -->   \n        ");
      out.write("</td>\n    ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\" colspan=\"2\">");
      out.write(
          "<img src=\"/wt-portal/images/spacers/spacer.gif\" height=\"4\" width=\"10\" border=\"0\" alt=\"WebTelemetry\">");
      out.write("</td>\n    ");
      out.write("</tr> \n");
      out.write("</table>\n");
      out.write("<br>");
      out.write("<br>\n");
      out.write("<b>Member of the Following Organizations &amp; Groups:");
      out.write("</b>\n");
      out.write("<!-- BEGIN: NEW ASSIGNED GROUPS TABLE -->\n");
      out.write("<table width=\"98%\"border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n\n    ");

      // Get the user's orgs
      WTOrganizationDAO orgDAO = DAOImpl.OrgDAO;
      WTOrganization[] orgs = orgDAO.getWTOrganization();

      if (orgs != null) {
        // Loop thru orgs
        for (int idx = 0; idx < orgs.length; idx++) {

          out.write("\n\n    ");
          out.write("<tr class=\"tableHeader\">\n        ");
          out.write("<td class=\"tableHeader\" colspan=\"2\">Organization Name: ");
          out.print(orgs[idx].getName());
          out.write("</td>\n\t");
          out.write("</tr>\n    ");
          out.write("<tr class=\"tableRowLight\">\n        ");
          out.write("<td class=\"tableText\" width=\"25%\">");
          out.write("<b>Assigned Groups:");
          out.write("</b>");
          out.write("</td>\n        ");
          out.write("<td class=\"tableText\" width=\"75%\">\n            ");

          // Get the orgs groups
          WTGroupManager grpMgr = ManagersImpl.GroupManager;
          int[] orgids = {orgs[idx].getID()};
          List groups = grpMgr.getUserGroups(user.getUserId(), orgids);

          if (groups != null) {
            // Loop thru the groups
            for (Iterator iterGrps = groups.iterator(); iterGrps.hasNext(); ) {
              WTGroup group = (WTGroup) iterGrps.next();
              WTRole role = (group.getRoles() == null ? null : (WTRole) group.getRoles().get(0));

              out.write("\n                    ");
              out.print(group.getName());
              out.write(" (");
              out.print((role == null ? "" : role.getName()));
              out.write(")");
              out.write("<br/>\n            ");
            }
          }

          out.write("\n\n        ");
          out.write("</td>\n\t");
          out.write("</tr>\n\n    ");
        }
      }

      out.write("\n\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\" colspan=\"2\">");
      out.write(
          "<img src=\"/wt-portal/images/spacers/spacer.gif\" height=\"4\" width=\"10\" border=\"0\" alt=\"WebTelemetry\">");
      out.write("</td>\n    ");
      out.write("</tr> \n");
      out.write("</table>\n");
      out.write("<!-- END: NEW ASSIGNED GROUPS TABLE -->\n\n\n");
      out.write("<!-- BEGIN FRAMING TABLE:close tags-->\n\t\t");
      out.write("</td>\n\t");
      out.write("</tr>\n");
      out.write("</table>\n");
      out.write("<!-- END FRAMING TABLE:close tags-->\n");
      out.write("<br>\n\n");
      JspRuntimeLibrary.include(request, response, "/includes/footer.jsp", out, false);
      out.write("\n");
      out.write("</body>\n");
      out.write("</html>\n\n");
    } catch (Throwable t) {
      out = _jspx_out;
      if (out != null && out.getBufferSize() != 0) out.clearBuffer();
      if (pageContext != null) pageContext.handlePageException(t);
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);
    }
  }
  /**
   * 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);
  }
  /**
   * Displays a given Meeting page for a HTTP Get, or creates a new Meeting for a HTTP Post
   *
   * <p>- Requires a cookie for the session user - Requires a meetingId request parameter for a GET
   * - Requires description, createdByUserId, datepicker, meetingTime, groupId request parameters
   * for a POST
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void meetingAction(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<String, Object>();
    viewData.put("title", "Meeting");

    // Initialise Manager connections
    MeetingManager meetingMan = new MeetingManager();
    GroupManager groupMan = new GroupManager();

    if (req.getMethod() == HttpMethod.Get) {
      // Get request parameter
      int meetingId = Integer.parseInt(req.getParameter("meetingId"));
      Meeting meeting = meetingMan.get(meetingId);

      if (meeting != null) {

        List<User> meetingUsers = groupMan.getGroupUsers(meeting.getGroupId());
        viewData.put("meetingUsers", meetingUsers);
        viewData.put("meeting", meeting);
        view(req, res, "/views/group/Meeting.jsp", viewData);

      } else {
        httpNotFound(req, res);
      }
    } else if (req.getMethod() == HttpMethod.Post) {

      // Get details from request
      String description = req.getParameter("description");
      int createdByUserId = Integer.parseInt(req.getParameter("createdByUserId"));
      Date dateCreated = new Date();

      String meetingDate = req.getParameter("datepicker");
      String meetingTime = req.getParameter("meetingTime");

      // Parse meeting date time details
      DateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm");
      Date dateDue = new Date();
      try {
        dateDue = format.parse(meetingDate + " " + meetingTime);
      } catch (ParseException e) {
        // Unable to parse date. This shouldn't happen since we are
        // performing javascript validation.
      }

      int groupId = Integer.parseInt(req.getParameter("groupId"));

      // Create a Meeting
      Meeting meeting = new Meeting();
      meeting.setDescription(description);
      meeting.setCreatedByUserId(createdByUserId);
      meeting.setDateCreated(dateCreated);
      meeting.setDateDue(dateDue);
      meeting.setGroupId(groupId);

      meetingMan.createMeeting(meeting);
      int meetingId = meetingMan.getIdFor(meeting);
      meeting.setId(meetingId);

      UserManager userMan = new UserManager();
      User createdByUser = userMan.get(createdByUserId);

      // Create a notification for all users in group
      NotificationManager notificationMan = new NotificationManager();
      List<User> users = groupMan.getGroupUsers(groupId);

      for (User u : users) {
        Notification notification =
            new Notification(
                u.getId(),
                u,
                groupId,
                null,
                "Meeting " + description + " was created by " + createdByUser.getFullName(),
                "/group/meeting?meetingId=" + meetingId);
        notificationMan.createNotification(notification);
      }

      // Update the User Session to show new meeting
      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");
      User admin = userSession.getUser();
      admin.getMeetings().add(meeting);

      // Show meeting page
      viewData.put("meetingUsers", users);
      viewData.put("meeting", meeting);
      view(req, res, "/views/group/Meeting.jsp", viewData);
    }
  }