/**
   * Subscribes this provider as interested in receiving notifications for new mail messages from
   * Google mail services such as Gmail or Google Apps.
   */
  private void subscribeForGmailNotifications() {
    // first check support for the notification service
    String accountIDService = jabberProvider.getAccountID().getService();
    boolean notificationsAreSupported =
        jabberProvider.isFeatureSupported(accountIDService, NewMailNotificationIQ.NAMESPACE);

    if (!notificationsAreSupported) {
      if (logger.isDebugEnabled())
        logger.debug(
            accountIDService
                + " does not seem to provide a Gmail notification "
                + " service so we won't be trying to subscribe for it");
      return;
    }

    if (logger.isDebugEnabled())
      logger.debug(
          accountIDService
              + " seems to provide a Gmail notification "
              + " service so we will try to subscribe for it");

    ProviderManager providerManager = ProviderManager.getInstance();

    providerManager.addIQProvider(
        MailboxIQ.ELEMENT_NAME, MailboxIQ.NAMESPACE, new MailboxIQProvider());
    providerManager.addIQProvider(
        NewMailNotificationIQ.ELEMENT_NAME,
        NewMailNotificationIQ.NAMESPACE,
        new NewMailNotificationProvider());

    Connection connection = jabberProvider.getConnection();

    connection.addPacketListener(new MailboxIQListener(), new PacketTypeFilter(MailboxIQ.class));
    connection.addPacketListener(
        new NewMailNotificationListener(), new PacketTypeFilter(NewMailNotificationIQ.class));

    if (opSetPersPresence.getCurrentStatusMessage().equals(JabberStatusEnum.OFFLINE)) return;

    // create a query with -1 values for newer-than-tid and
    // newer-than-time attributes
    MailboxQueryIQ mailboxQuery = new MailboxQueryIQ();

    if (logger.isTraceEnabled())
      logger.trace(
          "sending mailNotification for acc: "
              + jabberProvider.getAccountID().getAccountUniqueID());
    jabberProvider.getConnection().sendPacket(mailboxQuery);
  }
    /** Thread entry point. */
    @Override
    public void run() {
      int status;
      long progress;
      String statusReason = "";

      while (true) {
        try {
          Thread.sleep(10);

          status = parseJabberStatus(jabberTransfer.getStatus());
          progress = fileTransfer.getTransferedBytes();

          if (status == FileTransferStatusChangeEvent.FAILED
              || status == FileTransferStatusChangeEvent.COMPLETED
              || status == FileTransferStatusChangeEvent.CANCELED
              || status == FileTransferStatusChangeEvent.REFUSED) {
            if (fileTransfer instanceof OutgoingFileTransferJabberImpl) {
              ((OutgoingFileTransferJabberImpl) fileTransfer).removeThumbnailRequestListener();
            }

            // sometimes a filetransfer can be preparing
            // and than completed :
            // transfered in one iteration of current thread
            // so it won't go through intermediate state - inProgress
            // make sure this won't happen
            if (status == FileTransferStatusChangeEvent.COMPLETED
                && fileTransfer.getStatus() == FileTransferStatusChangeEvent.PREPARING) {
              fileTransfer.fireStatusChangeEvent(
                  FileTransferStatusChangeEvent.IN_PROGRESS, "Status changed");
              fileTransfer.fireProgressChangeEvent(System.currentTimeMillis(), progress);
            }

            break;
          }

          fileTransfer.fireStatusChangeEvent(status, "Status changed");
          fileTransfer.fireProgressChangeEvent(System.currentTimeMillis(), progress);
        } catch (InterruptedException e) {
          if (logger.isDebugEnabled()) logger.debug("Unable to sleep thread.", e);
        }
      }

      if (jabberTransfer.getError() != null) {
        logger.error(
            "An error occured while transfering file: " + jabberTransfer.getError().getMessage());
      }

      if (jabberTransfer.getException() != null) {
        logger.error(
            "An exception occured while transfering file: ", jabberTransfer.getException());

        if (jabberTransfer.getException() instanceof XMPPException) {
          XMPPError error = ((XMPPException) jabberTransfer.getException()).getXMPPError();
          if (error != null)
            if (error.getCode() == 406 || error.getCode() == 403)
              status = FileTransferStatusChangeEvent.REFUSED;
        }

        statusReason = jabberTransfer.getException().getMessage();
      }

      if (initialFileSize > 0
          && status == FileTransferStatusChangeEvent.COMPLETED
          && fileTransfer.getTransferedBytes() < initialFileSize) {
        status = FileTransferStatusChangeEvent.CANCELED;
      }

      fileTransfer.fireStatusChangeEvent(status, statusReason);
      fileTransfer.fireProgressChangeEvent(System.currentTimeMillis(), progress);
    }
  /**
   * Creates an html description of the specified mailbox.
   *
   * @param mailboxIQ the mailboxIQ that we are to describe.
   * @return an html description of <tt>mailboxIQ</tt>
   */
  private String createMailboxDescription(MailboxIQ mailboxIQ) {
    int threadCount = mailboxIQ.getThreadCount();

    String resourceHeaderKey =
        threadCount > 1 ? "service.gui.NEW_GMAIL_MANY_HEADER" : "service.gui.NEW_GMAIL_HEADER";

    String resourceFooterKey =
        threadCount > 1 ? "service.gui.NEW_GMAIL_MANY_FOOTER" : "service.gui.NEW_GMAIL_FOOTER";

    // FIXME Escape HTML!
    String newMailHeader =
        JabberActivator.getResources()
            .getI18NString(
                resourceHeaderKey,
                new String[] {
                  jabberProvider.getAccountID().getService(), // {0} - service name
                  mailboxIQ.getUrl(), // {1} - inbox URI
                  Integer.toString(threadCount) // {2} - thread count
                });

    StringBuilder message = new StringBuilder(newMailHeader);

    // we now start an html table for the threads.
    message.append("<table width=100% cellpadding=2 cellspacing=0 ");
    message.append("border=0 bgcolor=#e8eef7>");

    Iterator<MailThreadInfo> threads = mailboxIQ.threads();

    String maxThreadsStr =
        (String)
            JabberActivator.getConfigurationService()
                .getProperty(PNAME_MAX_GMAIL_THREADS_PER_NOTIFICATION);

    int maxThreads = 5;

    try {
      if (maxThreadsStr != null) maxThreads = Integer.parseInt(maxThreadsStr);
    } catch (NumberFormatException e) {
      if (logger.isDebugEnabled())
        logger.debug("Failed to parse max threads count: " + maxThreads + ". Going for default.");
    }

    // print a maximum of MAX_THREADS
    for (int i = 0; i < maxThreads && threads.hasNext(); i++) {
      message.append(threads.next().createHtmlDescription());
    }
    message.append("</table><br/>");

    if (threadCount > maxThreads) {
      String messageFooter =
          JabberActivator.getResources()
              .getI18NString(
                  resourceFooterKey,
                  new String[] {
                    mailboxIQ.getUrl(), // {0} - inbox URI
                    Integer.toString(threadCount - maxThreads) // {1} - thread count
                  });
      message.append(messageFooter);
    }

    return message.toString();
  }