Example #1
0
 /** @param newName */
 public void renameFolder(String newName) throws Exception {
   Folder fOld = getFolder();
   Folder fNew = handler.getStore().getFolder(profile.getFolderNameSpace() + newName);
   closeFolder(fOld);
   fOld.renameTo(fNew);
   fNew.setSubscribed(true);
 }
Example #2
0
  /**
   * @param profile
   * @param auth
   * @param handler
   */
  ImapProtocolImpl(
      ConnectionProfile profile, AuthProfile auth, ConnectionMetaHandler handler, String folder) {
    this.profile = profile;
    this.auth = auth;
    this.handler = handler;
    this.folder = folder;

    if (imapFolders.get(auth.getUsername()) == null) {
      HashMap imapUserFolders = new HashMap();
      imapFolders.put(auth.getUsername(), imapUserFolders);
    }

    if (this.folder == null
        || this.folder.trim().equals("")
        || this.folder.toLowerCase(loc).equals(Constants.FOLDER_INBOX(profile).toLowerCase(loc))) {
      this.folder = Constants.FOLDER_INBOX(profile);
    } else {
      if (!this.folder.startsWith(profile.getFolderNameSpace())) {
        this.folder = profile.getFolderNameSpace() + this.folder;
      }
    }
  }
  /**
   * The doPost method of the servlet. <br>
   * This method is called when a form has its tag value method equals to post.
   *
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setHeader("Expires", "-1");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-control", "no-cache");
    response.setHeader("Content-Type", "text/html; charset=utf-8");

    PrintWriter out = response.getWriter();

    AuthProfile auth = getAuthProfile(request);
    // get folder and set it into sesssion
    String sFolder = URLDecoder.decode((String) getVariable(request, "folder"), "UTF-8");

    // prepare variables
    List headers = null;
    ConnectionMetaHandler handler = getConnectionHandler(request);
    ConnectionProfile profile = getConnectionProfile(request);

    FolderControllerFactory foldFact = null;
    FolderController folderCont = null;
    String currFolder = org.claros.commons.mail.utility.Constants.FOLDER_INBOX(profile);

    try {
      if (auth == null) {
        throw new org.claros.commons.exception.NoPermissionException();
      }
      // if folder name is empty or it is inbox then do mail filtering. It is done by inbox
      // controller
      if (sFolder == null || sFolder.equals("") || sFolder.equals(currFolder)) {
        try {
          InboxControllerFactory inFact = new InboxControllerFactory(auth, profile, handler);
          InboxController inCont = inFact.getInboxController();
          handler = inCont.checkEmail();
          request.getSession().setAttribute("handler", handler);
          foldFact = new FolderControllerFactory(auth, profile, handler);
          folderCont = foldFact.getFolderController();
        } catch (Exception e) {
          log.debug("minor error while checking new mail", e);
        }

        // get the id(pop3) or the mail folder name (imap)
        if (profile.getProtocol().equals(org.claros.commons.mail.utility.Constants.POP3)) {
          currFolder = folderCont.getInboxFolder().getId().toString();
        } else {
          currFolder = folderCont.getInboxFolder().getFolderName();
        }
      } else {
        currFolder = sFolder;
        handler = (ConnectionMetaHandler) request.getSession().getAttribute("handler");
        foldFact = new FolderControllerFactory(auth, profile, handler);
        folderCont = foldFact.getFolderController();
      }
      request.getSession().setAttribute("folder", currFolder);

      // get info about the current folder
      FolderDbObject myFolder = folderCont.getFolder(currFolder);

      // time to fetch the headers
      if (profile.getProtocol().equals(org.claros.commons.mail.utility.Constants.POP3)
          && myFolder
              .getFolderType()
              .equals(org.claros.intouch.common.utility.Constants.FOLDER_TYPE_INBOX)) {
        currFolder = org.claros.commons.mail.utility.Constants.FOLDER_INBOX(null);
      }

      // get and set sort parameters
      String mailSort = (String) getVariable(request, "mailSort");
      if (null == mailSort) mailSort = "date";
      String mailSortDirection = (String) getVariable(request, "mailSortDirection");
      if (null == mailSortDirection) mailSortDirection = "desc";
      request.getSession().setAttribute("mailSort", mailSort);
      request.getSession().setAttribute("mailSortDirection", mailSortDirection);

      // first check to see if the server supports server side sorting or not.
      // if it supports server side sorting it is a big performance enhancement.
      ArrayList sortedHeaders = null;
      boolean supportsServerSorting = false;
      try {
        // if the user doesn't want server side sorting for any reason(????) do not to server
        // side imap sorting.
        String disableImapSort =
            PropertyFile.getConfiguration("/config/config.xml")
                .getString("common-params.disable-imap-sort");
        if (disableImapSort != null
            && (disableImapSort.toLowerCase().equals("yes")
                || disableImapSort.toLowerCase().equals("true"))) {
          sortedHeaders = null;
          supportsServerSorting = false;
        } else {
          // the user agrees on the performance enhancement imap sort offers. So go on.
          // let's give a try if the user supports it or not.
          ProtocolFactory pFact = new ProtocolFactory(profile, auth, handler);
          Protocol protocol = pFact.getProtocol(currFolder);

          sortedHeaders = protocol.getHeadersSortedList(mailSort, mailSortDirection);

          // profile has the boolean variable of it supports server side sorting or not!!!
          // so set it to the session for future references.
          profile = protocol.getProfile();
          request.getSession().setAttribute("profile", profile);

          supportsServerSorting = true;
        }
      } catch (ProtocolNotAvailableException p) {
        sortedHeaders = null;
        supportsServerSorting = false;
      }

      // it is pop3 mode or the imap server doesn't support server side sorting.
      if (!supportsServerSorting) {
        headers = folderCont.getHeadersByFolder(currFolder);
      }
      // if server side sorting is supported, do not fetch the messages yet. they will be fetched
      // when paging variables are set below.

      // get and set pageNo
      int pageNo = 1;
      try {
        pageNo = Integer.parseInt(getVariable(request, "pageNo").toString());
      } catch (Exception e) {
      }
      request.getSession().setAttribute("pageNo", new Integer(pageNo));

      Cookie c1 = new Cookie("mailSort", mailSort);
      c1.setMaxAge(Integer.MAX_VALUE);
      Cookie c2 = new Cookie("mailSortDirection", mailSortDirection);
      c2.setMaxAge(Integer.MAX_VALUE);
      Cookie c3 = new Cookie("pageNo", String.valueOf(pageNo));
      c3.setMaxAge(Integer.MAX_VALUE);
      response.addCookie(c1);
      response.addCookie(c2);
      response.addCookie(c3);

      boolean isAscending = false;
      if (mailSortDirection != null && mailSortDirection.equals("asc")) {
        isAscending = true;
      }

      // organize em
      String fromSort = "";
      String dateSort = "";
      String sizeSort = "";
      String subjectSort = "";

      if (mailSort == null || mailSort.equals("date")) {
        if (isAscending) dateSort = "asc";
        else dateSort = "desc";
      } else if (mailSort.equals("from")) {
        if (isAscending) fromSort = "asc";
        else fromSort = "desc";
      } else if (mailSort.equals("subject")) {
        if (isAscending) subjectSort = "asc";
        else subjectSort = "desc";
      } else if (mailSort.equals("to")) {
        if (isAscending) fromSort = "asc";
        else fromSort = "desc";
      } else if (mailSort.equals("size")) {
        if (isAscending) sizeSort = "asc";
        else sizeSort = "desc";
      }

      out.print(
          "<div id=\"ieHolder\" class=\"ieHolder\"><div class=\"ie7Holder\" id=\"ie7Holder\">");

      // at least show the title bar also with sort arrows
      if (profile.getProtocol().equals(Constants.IMAP)) {
        out.print(
            "<p class='title' id='mailtitle' displayName='"
                + myFolder.getFolderName()
                + "' folderid='"
                + myFolder.getId()
                + "' foldername='mailFolder"
                + myFolder.getFolderName()
                + "' type='"
                + myFolder.getFolderType()
                + "'>"
                + "	<span class='flag' style='background-image:url(images/unchecked.gif);background-repeat:no-repeat;' onclick='clickAll();'><a href='javascript:;'>&nbsp;</a></span>");
      } else {
        out.print(
            "<p class='title' id='mailtitle' displayName='"
                + myFolder.getFolderName()
                + "' folderid='"
                + myFolder.getId()
                + "' foldername='mailFolder"
                + myFolder.getId()
                + "' type='"
                + myFolder.getFolderType()
                + "'>"
                + "	<span class='flag' style='background-image:url(images/unchecked.gif);background-repeat:no-repeat;' onclick='clickAll();'><a href='javascript:;'>&nbsp;</a></span>");
      }
      out.print(
          "<span class='attributes'><a href='javascript:;'><span style='cursor:hand'><img alt='' src='images/priority-title.gif' align='absmiddle'><img alt='' src='images/sensitivity-title.gif' align='absmiddle'></span></a></span>");

      if (myFolder
          .getFolderType()
          .equals(org.claros.intouch.common.utility.Constants.FOLDER_TYPE_SENT)) {
        out.print(
            "  <span class='from "
                + fromSort
                + "' onclick=\"sortColumn(this, 'to');\" sort='"
                + fromSort
                + "'><a href='javascript:;'><span style='cursor:hand'>"
                + getText(request, "to")
                + "</span></a></span>");
        if (mailSort != null && mailSort.equals("from")) {
          mailSort = "to";
        }
      } else {
        out.print(
            "  <span class='from "
                + fromSort
                + "' onclick=\"sortColumn(this, 'from');\" sort='"
                + fromSort
                + "'><a href='javascript:;'><span style='cursor:hand'>"
                + getText(request, "from")
                + "</span></a></span>");
        if (mailSort != null && mailSort.equals("to")) {
          mailSort = "from";
        }
      }
      out.print(
          "	<span class='subject "
              + subjectSort
              + "' onclick=\"sortColumn(this, 'subject');\" sort='"
              + subjectSort
              + "'><a href='javascript:;'><span style='cursor:hand'>"
              + getText(request, "subject")
              + "</span></a></span>"
              + "	<span class='date "
              + dateSort
              + "' onclick=\"sortColumn(this, 'date');\" sort='"
              + dateSort
              + "'><a href='javascript:;'><span style='cursor:hand'>"
              + getText(request, "date")
              + "</span></a></span>"
              + "	<span class='size "
              + sizeSort
              + "' onclick=\"sortColumn(this, 'size');\" sort='"
              + sizeSort
              + "'><a href='javascript:;'><span style='cursor:hand'>"
              + getText(request, "size")
              + "</span></a></span>"
              + "	<span class='attach'><a href='javascript:;'>&nbsp;</a></span>"
              + "</p>");

      if (!supportsServerSorting) {
        // sort the headers
        if (mailSort == null || mailSort.equals("date")) {
          Collections.sort(headers, new ComparatorDate(isAscending));
        } else if (mailSort.equals("from")) {
          Collections.sort(headers, new ComparatorFrom(isAscending, loc));
        } else if (mailSort.equals("subject")) {
          Collections.sort(headers, new ComparatorSubject(isAscending, loc));
        } else if (mailSort.equals("to")) {
          Collections.sort(headers, new ComparatorTo(isAscending, loc));
        } else if (mailSort.equals("size")) {
          Collections.sort(headers, new ComparatorSize(isAscending));
        }
      }

      // organize and generate XML from the headers.
      if (headers != null || supportsServerSorting) {
        EmailHeader tmp = null;
        int pageSize = 25;
        String strPageSize =
            PropertyFile.getConfiguration("/config/config.xml")
                .getString("common-params.mailbox-page-size");
        if (strPageSize != null) {
          try {
            pageSize = Integer.parseInt(strPageSize);
          } catch (Exception e) {
            pageSize = 25;
          }
        }

        // determine the message count. the method varies if server side or client side
        // sorting is used.
        int messageCount = -1;
        if (!supportsServerSorting) {
          messageCount = headers.size();
        } else {
          messageCount = sortedHeaders.size();
        }
        int pageCount = messageCount / pageSize;
        if ((messageCount % pageSize) > 0) pageCount++;
        if (pageNo > pageCount) pageNo = pageCount;
        int startIdx = (pageNo - 1) * pageSize;
        if (startIdx < 0) startIdx = 0;
        int endIdx = startIdx + pageSize;
        if (endIdx > messageCount) endIdx = messageCount;

        out.print(
            "<span id=\"pagerParams\" style=\"display:none\">"
                + pageNo
                + ":"
                + pageCount
                + ":"
                + messageCount
                + ":"
                + pageSize
                + "</span>");

        // If server side sorting is supported, it is time to fetch the message headers.
        // not all of the headers are fetched.
        if (supportsServerSorting) {
          int msgs[] = new int[endIdx - startIdx];
          int counter = 0;
          for (int y = startIdx; y < endIdx; y++) {
            msgs[counter] = ((Integer) sortedHeaders.get(y)).intValue();
            counter++;
          }
          headers = folderCont.getHeadersByFolder(currFolder, msgs);

          // we only have the headers to be displayed in the headers arraylist.
          for (int i = 0; i < headers.size(); i++) {
            tmp = (EmailHeader) headers.get(i);
            writeHeaderInfoToOut(tmp, out, request, myFolder);
          }
        } else {
          // with the client side sorting method the headers array has all the message headers
          // so with a for statement display them.
          for (int i = startIdx; i < endIdx; i++) {
            tmp = (EmailHeader) headers.get(i);
            writeHeaderInfoToOut(tmp, out, request, myFolder);
          }
        }
      }
      out.print("</div></div>");
    } catch (Exception e) {
      out.print(
          "<p class='title'>"
              + "<span class='flag' style='background-image:url(images/unchecked.gif);background-repeat:no-repeat;' onclick='clickAll();'><a href='javascript:;'>&nbsp;</a></span>"
              + "<span class='attributes'><a href='javascript:;'><span>&nbsp;</span></a></span>"
              + "<span class='from asc'><a href='javascript:;'><span>"
              + getText(request, "from")
              + "</span></a></span>"
              + "<span class='subject'><a href='javascript:;'><span>"
              + getText(request, "subject")
              + "</span></a></span>"
              + "<span class='date'><a href='javascript:;'><span>"
              + getText(request, "date")
              + "</span></a></span>"
              + "<span class='size'><a href='javascript:;'><span>"
              + getText(request, "size")
              + "</span></a></span>"
              + "<span class='attach'><a href='javascript:;'>&nbsp;</a></span>"
              + "</p>");
    }
  }
  /* (non-Javadoc)
   * @see org.claros.commons.mail.protocols.FetchProtocol#connect(int)
   */
  public ConnectionMetaHandler connect(int connectType)
      throws SystemException, ConnectionException, ServerDownException {
    try {
      try {
        disconnect();
        try {
          Thread.sleep(2000);
        } catch (Exception k) {
        }
      } catch (Exception k) {
      }

      if (handler == null || !handler.getStore().isConnected()) {
        Properties props = new Properties();

        if (profile.getFetchSSL() != null && profile.getFetchSSL().toLowerCase().equals("true")) {
          Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

          Security.setProperty(
              "ssl.SocketFactory.provider",
              "org.claros.commons.mail.protocols.DummySSLSocketFactory");
          props.setProperty("mail.store.protocol", "pop3");
          props.setProperty("mail.pop3.host", profile.getFetchServer());
          props.setProperty("mail.pop3.port", profile.getFetchPort());

          props.setProperty(
              "mail.pop3.socketFactory.class",
              "org.claros.commons.mail.protocols.DummySSLSocketFactory");
          props.setProperty("mail.pop3.socketFactory.fallback", "false");
          props.setProperty("mail.pop3.port", profile.getFetchPort());
          props.setProperty("mail.pop3.socketFactory.port", profile.getFetchPort());
        }

        Session session = Session.getInstance(props);
        handler = new ConnectionMetaHandler();
        handler.setStore(session.getStore(profile.getProtocol()));
        handler
            .getStore()
            .connect(
                profile.getFetchServer(),
                profile.getIFetchPort(),
                auth.getUsername(),
                auth.getPassword());
        handler.setMbox(handler.getStore().getDefaultFolder());
        handler.setMbox(handler.getMbox().getFolder(Constants.FOLDER_INBOX(profile)));
        handler.getMbox().open(connectType);

        // storing the folder in map
        pop3Folders.put(auth.getUsername(), handler.getMbox());

        handler.setTotalMessagesCount(handler.getMbox().getMessageCount());
      }
    } catch (AuthenticationFailedException e) {
      System.out.println(
          "Pop3 Mailbox was busy with another session and there is a read write lock. A few minutes later when the lock is released everything will be fine.");
    } catch (NoSuchProviderException e) {
      System.out.println(profile.getProtocol() + " provider could not be found.");
      throw new SystemException(e);
    } catch (MessagingException e) {
      System.out.println("Connection could not be established.");
      throw new ConnectionException(e);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return handler;
  }
 public ArrayList getHeadersSortedList(String sortCriteriaRaw, String sortDirectionRaw)
     throws ProtocolNotAvailableException {
   profile.setSupportSort(false);
   throw new ProtocolNotAvailableException();
 }
Example #6
0
  /**
   * Fetches all e-mail headers from the server, with appropriate fields already set.
   *
   * @param handler
   * @return ArrayList of MessageHeaders
   * @throws ConnectionException
   */
  public ArrayList fetchAllHeaders() throws SystemException, ConnectionException {
    ArrayList headers = new ArrayList();
    Folder fold = null;
    try {
      fold = getFolder();
      EmailHeader header = null;

      Message[] msgs = fold.getMessages();
      FetchProfile fp = new FetchProfile();
      fp.add(FetchProfile.Item.ENVELOPE);
      fp.add(FetchProfile.Item.FLAGS);
      fp.add(FetchProfile.Item.CONTENT_INFO);
      fp.add("Size");
      fp.add("Date");
      fp.add("Disposition-Notification-To");
      fp.add("X-Priority");
      fp.add("X-MSMail-Priority");
      fp.add("Sensitivity");
      fold.fetch(msgs, fp);

      Message msg = null;
      for (int i = 0; i < msgs.length; i++) {
        try {
          header = new EmailHeader();
          msg = msgs[i];

          header.setMultipart((msg.isMimeType("multipart/*")) ? true : false);
          header.setMessageId(i + 1);
          header.setFrom(msg.getFrom());
          header.setTo(msg.getRecipients(Message.RecipientType.TO));
          header.setCc(msg.getRecipients(Message.RecipientType.CC));
          header.setBcc(msg.getRecipients(Message.RecipientType.BCC));
          header.setDate(msg.getSentDate());
          header.setReplyTo(msg.getReplyTo());
          header.setSize(msg.getSize());
          header.setSubject(org.claros.commons.utility.Utility.updateTRChars(msg.getSubject()));

          // now set the human readables.
          header.setDateShown(Formatter.formatDate(header.getDate(), "dd.MM.yyyy HH:mm"));
          header.setFromShown(
              org.claros.commons.utility.Utility.updateTRChars(
                  Utility.addressArrToStringShort(header.getFrom())));
          header.setToShown(Utility.addressArrToStringShort(header.getTo()));
          header.setCcShown(Utility.addressArrToStringShort(header.getCc()));
          header.setSizeShown(Utility.sizeToHumanReadable(header.getSize()));

          org.claros.commons.mail.parser.MessageParser.setHeaders(msg, header);

          boolean deleted = false;
          if (profile.getProtocol().equals(Constants.IMAP)) {
            Flags.Flag flags[] = msg.getFlags().getSystemFlags();
            if (flags != null) {
              Flags.Flag flag = null;
              for (int m = 0; m < flags.length; m++) {
                flag = flags[m];
                if (flag.equals(Flags.Flag.SEEN)) {
                  header.setUnread(new Boolean(false));
                }

                if (flag.equals(Flags.Flag.DELETED)) {
                  deleted = true;
                }
              }
            }
          }
          if (header.getUnread() == null) {
            header.setUnread(new Boolean(true));
          }

          // it is time to add it to the arraylist
          if (!deleted) {
            headers.add(header);
          }
        } catch (MessagingException e1) {
          log.error(
              "Could not parse headers of e-mail. Message might be defuncted or illegal formatted.",
              e1);
        }
      }
    } catch (MessagingException e) {
      log.error("Could not fetch message headers. Is mbox connection still alive???", e);
      //			throw new ConnectionException(e);
    } catch (Exception e) {
      log.error("Could not fetch message headers. Is mbox connection still alive???", e);
      //			throw new ConnectionException(e);
    }
    return headers;
  }
Example #7
0
  /* (non-Javadoc)
   * @see org.claros.commons.mail.protocols.Protocol#connect(int)
   */
  public ConnectionMetaHandler connect(int connectType)
      throws SystemException, ConnectionException, ServerDownException {
    Folder fold = null;
    try {
      if (handler == null || handler.getStore() == null || !handler.getStore().isConnected()) {
        Properties props = new Properties();
        //				props.setProperty("mail.imap.separatestoreconnection", "true");
        //				props.setProperty("mail.imap.connectionpoolsize", "0");
        //				props.setProperty("mail.imap.connectionpooltimeout", "100");

        //				props.setProperty("mail.debug", "true");
        Session session = Session.getDefaultInstance(props);
        log.debug("session instance initiated");
        handler = new ConnectionMetaHandler();
        handler.setStore(session.getStore(profile.getProtocol()));
        log.debug("session store set. protocol is: " + profile.getProtocol());
        handler
            .getStore()
            .connect(
                profile.getFetchServer(),
                profile.getIFetchPort(),
                auth.getUsername(),
                auth.getPassword());
        if (handler.getStore().isConnected()) {
          log.debug("Store has been connected... Successful");
        } else {
          log.warn("Connection unsuccessfull...!!");
        }
      }
      fold = handler.getStore().getFolder(Constants.FOLDER_INBOX(profile));

      HashMap imapUserFolders = (HashMap) imapFolders.get(auth.getUsername());
      imapUserFolders.put("INBOX", fold);
      imapFolders.put(auth.getUsername(), imapUserFolders);

      handler.setMbox(fold);
      log.debug("Got mailbox folder. Folder is: " + fold.getFullName());
      handler.setTotalMessagesCount(fold.getMessageCount());
      log.debug("Message Count:" + handler.getTotalMessagesCount());
    } catch (FolderNotFoundException e) {
      log.fatal(
          profile.getProtocol()
              + " cannot identify the INBOX folder. Please check your folder-namespace variable at config.xml.");
      throw new SystemException(e);
    } catch (NoSuchProviderException e) {
      log.fatal(profile.getProtocol() + " provider could not be found.");
      throw new SystemException(e);
    } catch (MessagingException e) {
      Exception ne = e.getNextException();
      if (ne != null) {
        if (ne instanceof ConnectException || ne instanceof IOException) {
          throw new ServerDownException("Server is unreachable.");
        }
      }
      log.error("Connection could not be established." + e.getMessage());
      //			throw new ConnectionException(e);
    } catch (Exception e) {
      log.error("An unknown exception while connect.", e);
    }
    return handler;
  }