Sunday, November 4, 2012

G-Mail Notification application in Java

This is a Java based application which notifies the user in case he has any new unread emails in his G-Mail Inbox

It is certainly Not of production quality - this is meant for demo purposes only :-)

File : GFrame.java

import java.awt.EventQueue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.SwingConstants;


import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.SwingWorker;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseListener;
import javax.swing.JCheckBox;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import org.apache.commons.validator.routines.DomainValidator;
import org.apache.commons.validator.routines.InetAddressValidator;

public class GFrame extends JFrame implements MouseListener {

 public static Integer UNREAD_MESSAGES = 0;
 
 public static int counter = 0;

 public static GFrame frame;
 public static boolean KEEP_IT_RUNNING = false;

 private JPanel contentPane;
 public static JTextField textField;
 public static  JPasswordField passwordField;
 public static  JButton btnNewButton;
 public static  JButton btnNewButton_1;
 public static  JTextField textField_1;
 public static  JButton btnNewButton_2;

 public static  String LOGINFILE = "login.ser";
 public static  String PWDFILE = "pwd.ser";
 public static  String PROXYFILE = "proxy.ser";
 public static  String PORTFILE = "port.ser";
 
 public static  boolean WORKER_IS_RUNNING = false;
 
 public static  SwingWorker worker;
 public static  JCheckBox chckbxNewCheckBox;
 public static  JLabel lblNewLabel_2;
 public static  JLabel lblNewLabel_3;
 public static  JTextField textField_2;
 public static  JTextField textField_3;
 
 public static  boolean USE_PROXY = false;
 public static  JButton btnNewButton_3;
 public static  JLabel lblNewLabel_4;
 public static  JButton btnNewButton_4;
 public static  JButton btnNewButton_5;

 

 public static  boolean INVALID_CREDENTIALS = false;
 public static  boolean IS_CANCELLED = false;
 public static  boolean IS_RUNNING = false;
 
 public static MailChecker mailChecker = new MailChecker();
 
 public static TooltipFinalManager tooltipFinalManager = new TooltipFinalManager(1);
 
  
  
 private boolean hasDigits(String myString) {
  boolean retBool = true;
  for (char c : myString.toCharArray()) {
   if (!Character.isDigit(c)) {
    retBool = false;
   }
  }
  return retBool;
 }

 private void _displayTextMessage(String message) {
  textField_1.setText(message);
 }

 private static String doLoad(String fileName) {
  System.out.println("Loading data from the file...");
  Hashtable h = null;
  File f = new File(fileName);

  if (!f.exists()) {
   return new String("");
  }

  try {
   System.out.println("Creating file/object input stream...");
   FileInputStream fileIn = new FileInputStream(fileName);
   ObjectInputStream in = new ObjectInputStream(fileIn);
   System.out.println("Loading Hashtable Object...");
   h = (Hashtable) in.readObject();
   System.out.println("Closing all input streams...");
   in.close();
   fileIn.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
  // System.out.println("Printing out loaded data...");
  Enumeration e = h.keys();
  Object obj = e.nextElement();
  String retStr = (String) h.get(obj);
  // System.out.println("Returning:" + retStr);
  return retStr;
 }

 private static void doSave(String fileName, String value) {
  System.out.println("Saving Data...");
  Hashtable h = new Hashtable();
  FileOutputStream fos = null;
  ObjectOutputStream oos = null;
  File f = new File(fileName);
  h.put("string", value);
  try {
   System.out.println("Creating file/object output stream...");
   fos = new FileOutputStream(f);
   try {
    oos = new ObjectOutputStream(fos);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   System.out.println("Writing Hashtable Object...");
   try {
    oos.writeObject(h);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   try {
    oos.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   try {
    fos.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }


 

 /**
  * Create the frame.
  */
 public GFrame() {
  setTitle("GMail Notify (giridharmb@gmail.com)");

  this.addMouseListener(this);

  setResizable(false);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 379, 361);
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  setContentPane(contentPane);
  contentPane.setLayout(null);

  JLabel lblNewLabel = new JLabel("Username");
  lblNewLabel.setBounds(10, 11, 165, 14);
  contentPane.add(lblNewLabel);

  textField = new JTextField();
  textField.setHorizontalAlignment(SwingConstants.CENTER);
  textField.setBounds(10, 36, 353, 20);
  contentPane.add(textField);
  textField.setColumns(10);
  textField.setText(doLoad(LOGINFILE));

  JLabel lblNewLabel_1 = new JLabel("Password");
  lblNewLabel_1.setBounds(10, 67, 165, 14);
  contentPane.add(lblNewLabel_1);

  passwordField = new JPasswordField();
  passwordField.setHorizontalAlignment(SwingConstants.CENTER);
  passwordField.setBounds(10, 92, 353, 20);
  contentPane.add(passwordField);
  passwordField.setText(doLoad(PWDFILE));

  btnNewButton = new JButton("Save Settings");
  btnNewButton.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent e) {
    doSave(LOGINFILE, textField.getText());
    doSave(PWDFILE, passwordField.getText());
    doSave(PROXYFILE, textField_2.getText());
    doSave(PORTFILE, textField_3.getText());
    textField_1.setText("Credentails & Proxy Information Saved !");
   };
  });
  btnNewButton.setBounds(10, 228, 121, 23);
  contentPane.add(btnNewButton);

  btnNewButton_1 = new JButton("Exit");
  btnNewButton_1.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent e) {
    System.exit(0);
   }
  });
  btnNewButton_1.setBounds(205, 264, 78, 23);
  contentPane.add(btnNewButton_1);

  textField_1 = new JTextField();
  textField_1.setHorizontalAlignment(SwingConstants.CENTER);
  textField_1.setEditable(false);
  textField_1.setBounds(10, 197, 353, 20);
  contentPane.add(textField_1);
  textField_1.setColumns(10);

  textField_1.setText("Welcome to GMAIL Sync Tool");

  btnNewButton_2 = new JButton("Check Mail Messages");
  btnNewButton_2.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {

   }
  });

  btnNewButton_2.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent e) {

    if (USE_PROXY) {
     if (textField_2.getText().length() == 0 || textField_2.getText().isEmpty())
     {
      _displayTextMessage("Please Enter Valid Proxy Server Address");
      return;
     }
     if (textField_3.getText().length() == 0 || textField_3.getText().isEmpty()) {
      _displayTextMessage("Please Enter Valid Proxy Port Number");
      return;
     }
    }

    if (USE_PROXY) {
     boolean valid_ip_address = InetAddressValidator.getInstance().isValidInet4Address(textField_2.getText());
     boolean valid_host_name = DomainValidator.getInstance().isValid(textField_2.getText());
     if (!valid_ip_address && !valid_host_name)
     {
      _displayTextMessage("Error: Please enter valid Proxy Server Address !");
      return;
     }
    }

    if (USE_PROXY)
    {
     if (!hasDigits(textField_3.getText()))
     {
      _displayTextMessage("Please enter valid Port Number");
      return;
     }
    }

    System.out.println(">>> MOUSE CLICKED !");
    
    ///////////////////
    WORKER_IS_RUNNING = true;
    textField_1.setText("Checking for new messages...");
    String pwd = passwordField.getText();
    char[] pwdArray = pwd.toCharArray();
    
    String host = "smtp-server.address.com";
    String username = textField.getText();
    String password = passwordField.getText();
    ////////////
    MailManager.startMailCheck(username, password, "exchange-server.address.com");
    tooltipFinalManager.startTooltipMonitoring();
    //Notifier notifier = new Notifier("New Messages", "You have " + UNREAD_MESSAGES + " new messages");
    //notifier.runMe();
    
   }

   @Override
   public void mousePressed(MouseEvent e) {

   }
  });
  btnNewButton_2.setBounds(10, 264, 185, 23);
  contentPane.add(btnNewButton_2);

  chckbxNewCheckBox = new JCheckBox(
    "Enable Proxy Server (If you're not sure, Don't Enable this)");
  chckbxNewCheckBox.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent arg0) {
    if (chckbxNewCheckBox.isSelected()) {
     System.out.println("Check Box - ENABLED !");
     _displayTextMessage("Using Proxy Server...");
     USE_PROXY = true;
    }
    if (!chckbxNewCheckBox.isSelected()) {
     System.out.println("Check Box - DISABLED !");
     _displayTextMessage("Not Using Proxy Server...");
     USE_PROXY = false;
    }
   }
  });
  chckbxNewCheckBox.addChangeListener(new ChangeListener() {
   public void stateChanged(ChangeEvent arg0) {

   }
  });
  chckbxNewCheckBox.setBounds(10, 119, 353, 23);
  contentPane.add(chckbxNewCheckBox);

  lblNewLabel_2 = new JLabel("Proxy Server");
  lblNewLabel_2.setBounds(10, 149, 165, 14);
  contentPane.add(lblNewLabel_2);

  lblNewLabel_3 = new JLabel("Port");
  lblNewLabel_3.setBounds(293, 149, 52, 14);
  contentPane.add(lblNewLabel_3);

  textField_2 = new JTextField();
  textField_2.setHorizontalAlignment(SwingConstants.CENTER);
  textField_2.setBounds(10, 166, 273, 20);
  contentPane.add(textField_2);
  textField_2.setColumns(10);
  textField_2.setText(doLoad(PROXYFILE));

  textField_3 = new JTextField();
  textField_3.setHorizontalAlignment(SwingConstants.CENTER);
  textField_3.setBounds(293, 166, 70, 20);
  contentPane.add(textField_3);
  textField_3.setColumns(10);
  textField_3.setText(doLoad(PORTFILE));

  btnNewButton_3 = new JButton("Minimize to Tray");
  btnNewButton_3.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent arg0) {
    TrayMonitor.toggleWindow(frame);
   }
  });
  btnNewButton_3.setBounds(141, 228, 142, 23);
  contentPane.add(btnNewButton_3);

  lblNewLabel_4 = new JLabel("");
  lblNewLabel_4.setHorizontalAlignment(SwingConstants.CENTER);
  lblNewLabel_4.setBounds(293, 232, 70, 55);
  contentPane.add(lblNewLabel_4);
  lblNewLabel_4.setIcon(new ImageIcon(TrayMonitor.getIconizedImageFromFile("resources/_gmail_01.png", 70, 55)));

  btnNewButton_4 = new JButton("Keep Runing In Background");
  btnNewButton_4.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent arg0) {
    MailManager.startMailCheck(textField.getText(), passwordField.getText(), "exchange-server.address.com");
    tooltipFinalManager.startTooltipMonitoring();
   }
  });
  btnNewButton_4.setBounds(10, 299, 234, 23);
  contentPane.add(btnNewButton_4);

  btnNewButton_5 = new JButton("Cancel");
  btnNewButton_5.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent e) {
    TrayManager.stopMonitoring();
    MailManager.stopMailCheck();
    tooltipFinalManager.stopTooltipMonitoring();
   }
  });
  btnNewButton_5.setBounds(254, 299, 109, 23);
  contentPane.add(btnNewButton_5);

  TrayMonitor.loadDefaultIcon();
  
   
 }

 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     frame = new GFrame();
     frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 @Override
 public void mouseClicked(MouseEvent e) {
  // TODO Auto-generated method stub

 }

 @Override
 public void mousePressed(MouseEvent e) {
  // TODO Auto-generated method stub

 }

 @Override
 public void mouseReleased(MouseEvent e) {
  // TODO Auto-generated method stub

 }

 @Override
 public void mouseEntered(MouseEvent e) {
  // TODO Auto-generated method stub

 }

 @Override
 public void mouseExited(MouseEvent e) {
  // TODO Auto-generated method stub

 }
}

File : MailChecker.java


import java.util.Properties;

import javax.mail.Session;
import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Store;
import org.exjello.mail.ExchangeConstants;


public class MailChecker {
 private static String PASSWORD = "";
 private static String USERNAME = "";
 private static String MAILHOST = "exchange.server.address.com";
 public static Properties props = null;
 public static Store store = null;
 public static Session session = null;
 public static Folder inbox = null;
  
 public static Integer MESSAGECOUNT = 0;
 public static String FOLDER = "Inbox";
 
 private static String ENABLE_SSL = "mail.imap.ssl.enable";
 private static String MAIL_HOST = "mail.imap.host";
 private static String MAIL_HOST_URL = "https://exchange.server.address.com/owa";
 private static String STORE_NAME = "imap";
 
 public MailChecker() {
  PASSWORD = "";
  USERNAME = "";
  props = new Properties();
  MAILHOST = "exchange.server.address.com";
 }
 
 public MailChecker(String username, String password) {
  this.USERNAME = username;
  this.PASSWORD = password;
  props = new Properties();
 }
 
 public MailChecker(String username, String password, String mailhost) {
  this.USERNAME = username;
  this.PASSWORD = password;
  this.MAILHOST = mailhost;
  props = new Properties();
 }
 
 
 public static String getPASSWORD() {
  return PASSWORD;
 }

 public static void setPASSWORD(String pASSWORD) {
  PASSWORD = pASSWORD;
 }

 public static String getUSERNAME() {
  return USERNAME;
 }

 public static void setUSERNAME(String uSERNAME) {
  USERNAME = uSERNAME;
 }

 public static String getMAILHOST() {
  return MAILHOST;
 }

 public static void setMAILHOST(String mAILHOST) {
  MAILHOST = mAILHOST;
 }

 public Integer getMessageCountFromExchange()
 {
  try
  {
            props = System.getProperties();

            /*
             * Use UNFILTERED_PROPERTY if you want Read and Unread emails
             */
            props.setProperty(ExchangeConstants.UNFILTERED_PROPERTY, String.valueOf(true));

            /*
             * You can use other filter implemented on exJello, they are based
             * on:
             * http://blogs.msdn.com/b/andrewdelin/archive/2005/05/11/416312.aspx
             */

            /*
             * Use FILTER_FROM_PROPERTY to filter email only form certain
             * address or domain
             */
            //props.setProperty(ExchangeConstants.FILTER_FROM_PROPERTY, "@hp.com");

            /*
             * Use FILTER_TO_PROPERTY to fiter emails sent to specified address
             * (usefull with alias of mailbox)
             */
            //props.setProperty(ExchangeConstants.FILTER_TO_PROPERTY, "alias@mydomain.com");

            /*
             * You can use FILTER_LAST_CHECK to get email after certain date
             */
            //if (laskCheck != null && !laskCheck.isEmpty()) {
            //        props.setProperty(ExchangeConstants.FILTER_LAST_CHECK, laskCheck);
            //}

            // Get a Session object
            props.setProperty(ENABLE_SSL, "true");
            props.setProperty(MAIL_HOST, MAIL_HOST_URL);
            session = Session.getInstance(props, null);
            System.out.println("@@ session =>"+session.toString());
            
            store = session.getStore(STORE_NAME);
            //store = new ExchangeStore(session, null );
            System.out.println("@@ store =>"+store.toString());

            System.out.println("@@ USERNAME =>"+USERNAME);
            //System.out.println("@@ PASSWORD =>"+PASSWORD);
            System.out.println("@@ MAILHOST =>"+MAILHOST);
            
            
            // Connect
            store.connect(MAILHOST, USERNAME,PASSWORD);
            
            System.out.println("@@ store =>"+store.toString());

            Folder folder = store.getFolder(FOLDER);
            System.out.println("@@ folder =>"+folder.toString());

            if (folder == null || !folder.exists())
            {
                    System.out.println("Invalid folder");
                    // System.exit(1);
            }

            // folder.open(Folder.READ_WRITE);
            folder.open(Folder.READ_ONLY);
            //int count = 0;
            //Message[] msgs = folder.getMessages();
            //for (Message msg : msgs) {
            // if(!msg.getFlags().contains(Flags.Flag.SEEN)) {
            //  count++;
            // }
            //}
            //MESSAGECOUNT = count;
            MESSAGECOUNT = folder.getUnreadMessageCount();
            System.out.println("Got " + MESSAGECOUNT + " unread messages");
            GFrame.UNREAD_MESSAGES = MESSAGECOUNT;
  }
  catch (Exception ex)
  {
   ex.printStackTrace();
            System.err.println(ex.getMessage());
  }
  GFrame.UNREAD_MESSAGES = MESSAGECOUNT;
  return MESSAGECOUNT;
 }
 
 public static Integer getMessageCount() {
  Integer messageCount = 0;
  Session session = Session.getDefaultInstance(props);
  try {
   store = session.getStore("pop3");
  } catch (NoSuchProviderException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  String storeClass = store.getClass().getName();
  
  if(!"org.exjello.mail.ExchangeStore".equals(storeClass)) {
            System.err.println("The exJello POP3 provider is NOT installed.");
            System.err.println("Skipping POP3 test.");
            return null;
        }
  
  System.out.println("org.exjello.mail.ExchangeStore installed !");
  
  try {
   store.connect(MAILHOST, USERNAME, PASSWORD);
  } catch (MessagingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   System.out.println("Failed to Connect to Exchange !");
  }
  
  System.out.println("Successfully Connected to Exchange !");
  
  try {
   inbox = store.getFolder("INBOX");
  } catch (MessagingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   System.out.println("Failed to Get Inbox !");
  }
  
        try {
   inbox.open(Folder.READ_ONLY);
  } catch (MessagingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   System.out.println("Failed to Open Inbox !");
  }
        
        try {
   messageCount = inbox.getMessageCount();
  } catch (MessagingException e) {
   // TODO Auto-generated catch block
   System.out.println("Failed to Get Message Count from Inbox !");
   e.printStackTrace();
  }
        
        System.out.println("Connected to POP3, inbox has " + messageCount + " messages.");
        
        if(inbox != null) {
         try {
    inbox.close(false);
   } catch (MessagingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println("Failed to close Inbox !");
   }
        }
        
        if(store != null) {
         try {
    store.close();
   } catch (MessagingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println("Failed to close Store !");
   }
        }
  return messageCount;
 }
 
 public static Integer getMessageCount(String username, String password, String mailhost) {
  MAILHOST = mailhost;
  USERNAME = username;
  PASSWORD = password;
  Integer messageCount = 0;
  props = new Properties();
  Session session = Session.getDefaultInstance(props);
  try {
   store = session.getStore("pop3");
  } catch (NoSuchProviderException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  String storeClass = store.getClass().getName();
  
  if(!"org.exjello.mail.ExchangeStore".equals(storeClass)) {
            System.err.println("The exJello POP3 provider is NOT installed.");
            System.err.println("Skipping POP3 test.");
            return null;
        }
  
  System.out.println("org.exjello.mail.ExchangeStore installed !");
  
  try {
   store.connect(MAILHOST, USERNAME, PASSWORD);
  } catch (MessagingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   System.out.println("Failed to Connect to Exchange !");
  }
  
  System.out.println("Successfully Connected to Exchange !");
  
  try {
   inbox = store.getFolder("INBOX");
  } catch (MessagingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   System.out.println("Failed to Get Inbox !");
  }
  
        try {
   inbox.open(Folder.READ_ONLY);
  } catch (MessagingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   System.out.println("Failed to Open Inbox !");
  }
        
        try {
   messageCount = inbox.getMessageCount();
  } catch (MessagingException e) {
   // TODO Auto-generated catch block
   System.out.println("Failed to Get Message Count from Inbox !");
   e.printStackTrace();
  }
        
        System.out.println("Connected to POP3, inbox has " + messageCount + " messages.");
        
        if(inbox != null) {
         try {
    inbox.close(false);
   } catch (MessagingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println("Failed to close Inbox !");
   }
        }
        
        if(store != null) {
         try {
    store.close();
   } catch (MessagingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println("Failed to close Store !");
   }
        }
  return messageCount;
 }
}

File : MailManager.java

import javax.swing.SwingWorker;


public class MailManager {
 public static SwingWorker worker = null;
 public static boolean MAILMANAGER_RUNNING = false;
 
 public static void startMailCheck(String username, String password, String mailhost) {
  final MailChecker mailChecker = new MailChecker(username, password, mailhost);
  worker = new SwingWorker() {
   @Override
   public Object doInBackground() {
    System.out.println("MailManager is starting execute() ...");
    GFrame.UNREAD_MESSAGES = mailChecker.getMessageCountFromExchange();
    return true;
   }
   
   @Override
   public void done() {
    System.out.println("MailManager is done with the execute() !");
    MAILMANAGER_RUNNING = false;
    GFrame.btnNewButton_2.setEnabled(true);
    TrayMonitor.runOnce();
   }
  };
  if(!MAILMANAGER_RUNNING) {
   GFrame.btnNewButton_2.setEnabled(false);
   worker.execute();
   MAILMANAGER_RUNNING = true;
  }
 }
 
 public static void stopMailCheck() {
  if(MAILMANAGER_RUNNING) {
   if(worker != null) {
    worker.cancel(true);
   }
   worker = null;
  }
  GFrame.btnNewButton_2.setEnabled(true);
 }
}

File : SimpleTask

import java.awt.TrayIcon;
import java.util.Date;
import java.util.TimerTask;


public class SimpleTask extends TimerTask {
 
 public static TrayMonitor trayMonitor = null;
 
 public SimpleTask() {
  TrayMonitor trayMonitor = new TrayMonitor();
 }

 @Override
 public void run() {
  // TODO Auto-generated method stub
  System.out.println("## Running Simple Task @@ " + new Date());
  trayMonitor.runOnce();
  
 }

}

File : TooltipFinalManager.java

import java.util.Timer;
import java.util.TimerTask;


public class TooltipFinalManager {
 public static Timer globalTimer = null;
 public static TooltipTaskManager globalSimpleTask = null;
 public static Integer CHECK_MAIL_INTERVAL_IN_MINUTES = 1;
 public boolean TOOLTIP_MANAGER_RUNNING = false;
 public static boolean ALREADY_ENABLED = false;
 
 public TooltipFinalManager() {
  CHECK_MAIL_INTERVAL_IN_MINUTES = 1;
 }

 public TooltipFinalManager(Integer checkIntervalInMinutes) {
  globalSimpleTask = new TooltipTaskManager();
  globalTimer = new Timer();
  
  if(checkIntervalInMinutes < 1 || checkIntervalInMinutes >= 10) {
   CHECK_MAIL_INTERVAL_IN_MINUTES = 1;
  } else {
   CHECK_MAIL_INTERVAL_IN_MINUTES = checkIntervalInMinutes;
  }
 }
 
 public void startTooltipMonitoring() {
  globalSimpleTask = new TooltipTaskManager();
  globalTimer = new Timer();
  globalTimer.scheduleAtFixedRate(globalSimpleTask, 0, CHECK_MAIL_INTERVAL_IN_MINUTES * 60 * 1000);
 }
 
 public void stopTooltipMonitoring() {
  globalSimpleTask.cancel();
  globalTimer.cancel();
 }
}

File : TooltipManager.java


import javax.swing.SwingWorker;

public class TooltipManager {
 private static SwingWorker worker = null;
 private static boolean ALREADY_RUNNING=false;
 
 public TooltipManager() {
  ALREADY_RUNNING = false;
 }
 
 public static void startToolTipManager() {
  worker = new SwingWorker() {
   @Override
   protected Object doInBackground() throws Exception {
    MailManager.startMailCheck(GFrame.textField.getText(),GFrame.passwordField.getText(),"exchange.server.address.com");
    return null;
   }
   @Override
   public void done() {
    System.out.println("Done with tooltip manager !");
   }
  };
  worker.execute();
 }
 
 public static void stopToolTipManager() {
  if(worker != null) {
   worker.cancel(true);
  }
  worker = null;
 }
}

File : TooltipTaskManager.java

import java.util.Date;
import java.util.TimerTask;

public class TooltipTaskManager extends TimerTask {

 @Override
 public void run() {
  // TODO Auto-generated method stub
  TooltipManager.startToolTipManager();
 }

}

File : TrayManager.java

import java.util.Timer;
import java.util.TimerTask;


public class TrayManager {
 
 public static  Timer globalTimer = null;
 public static SimpleTask globalSimpleTask = null;
 public static  Integer CHECK_MAIL_INTERVAL_IN_MINUTES = 2;
 public static boolean TRAY_MANAGER_RUNNING = false;
 
 public TrayManager() {
  CHECK_MAIL_INTERVAL_IN_MINUTES = 2;
  globalSimpleTask = new SimpleTask();
 }
 
 public TrayManager(Integer checkIntervalInMinutes) {
  if(checkIntervalInMinutes < 1 || checkIntervalInMinutes >= 10) {
   CHECK_MAIL_INTERVAL_IN_MINUTES = 2;
  } else {
   CHECK_MAIL_INTERVAL_IN_MINUTES = checkIntervalInMinutes;
  }
  globalSimpleTask = new SimpleTask();
 }
 
 public static void startMonitoring() {
  if(!TRAY_MANAGER_RUNNING) {
   globalSimpleTask = new SimpleTask();
   globalTimer = new Timer();
   globalTimer.scheduleAtFixedRate(globalSimpleTask, 0, CHECK_MAIL_INTERVAL_IN_MINUTES * 60 * 1000);
   TRAY_MANAGER_RUNNING = true;
  }
 }
 
 public static void stopMonitoring() {
  if(TRAY_MANAGER_RUNNING) {
   globalSimpleTask.cancel();
   globalTimer.cancel();
   TRAY_MANAGER_RUNNING = false;
  }
 }
}

File : TrayMonitor.java

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.SwingWorker;



public class TrayMonitor {
 private static SwingWorker worker = null;
 public static  SystemTray sysTray = null;
 public static  List imageList = new LinkedList();
 public static  TrayIcon unreadIcon = null;
 public static  TrayIcon readIcon = null;
 public static  Image trayIconImage = null;
 public static  TrayIcon trayIcon = null;
 public static  Image noUnreadEmailsImage = null;
 public static  Image unreadEmailsImage = null;
 public static  boolean TRAY_MONITOR_RUNNING = false;
 public static  boolean ICONIFIED = false;
 public static TrayIcon SHARED_ICON = null;
 public static TrayIcon ikon = null;
  
 
 
 public static SystemTray getSysTray() {
  return sysTray;
 }

 public static void setSysTray(SystemTray sysTray) {
  TrayMonitor.sysTray = sysTray;
 }

 public static TrayIcon getUnreadIcon() {
  return unreadIcon;
 }

 public static void setUnreadIcon(TrayIcon unreadIcon) {
  TrayMonitor.unreadIcon = unreadIcon;
 }

 public static TrayIcon getReadIcon() {
  return readIcon;
 }

 public static void setReadIcon(TrayIcon readIcon) {
  TrayMonitor.readIcon = readIcon;
 }

 public TrayMonitor() {
  sysTray = SystemTray.getSystemTray();
  List images = loadImages();
  noUnreadEmailsImage = images.get(0);
  unreadEmailsImage = images.get(1);
  TRAY_MONITOR_RUNNING = false;
  
 }
 
 public static void initialize() {
  sysTray = SystemTray.getSystemTray();
  List images = loadImages();
  noUnreadEmailsImage = images.get(0);
  unreadEmailsImage = images.get(1);
  TRAY_MONITOR_RUNNING = false;
 }
 
 public static void loadDefaultIcon() {
  initialize();
  List images = loadImages();
  removeAllTrayIcons();
  noUnreadEmailsImage = images.get(0);
  setTrayIconImage(noUnreadEmailsImage);
 }
 
 public static Image getIconizedImageFromFile(String pathToImage) {
  Image retImage = null;
  ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  InputStream input = classLoader.getResourceAsStream(pathToImage);
  Image logo = null;
  try {
   logo = ImageIO.read(input);
   retImage = logo.getScaledInstance(16, 16, Image.SCALE_SMOOTH);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return retImage;
 }

 public static Image getIconizedImageFromFile(String pathToImage, int width,int height) {
  Image retImage = null;
  ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  InputStream input = classLoader.getResourceAsStream(pathToImage);
  Image logo = null;
  try {
   logo = ImageIO.read(input);
   retImage = logo
     .getScaledInstance(width, height, Image.SCALE_SMOOTH);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return retImage;
 }
 
 
 public static void toggleWindow(JFrame jframe) {
  
  if (!ICONIFIED) {
   jframe.setState(jframe.ICONIFIED);
   jframe.setVisible(false);
   ICONIFIED = !ICONIFIED;
  } else {
   jframe.setState(jframe.NORMAL);
   jframe.setVisible(true);
   ICONIFIED = !ICONIFIED;
  }
 }
 public static List loadImages() {
  Image img1 = null;
  Image img2 = null;
  try {
   img1 = getIconizedImageFromFile("resources/gmail-01-bw.png");
   img2 = getIconizedImageFromFile("resources/gmail-01.png");

   imageList.add(img1);
   imageList.add(img2);
  } catch (Exception e) {
   System.out.println("Could not load the image, " + e.getMessage());
  }

  readIcon = new TrayIcon(img1, "No New Mails");
  unreadIcon = new TrayIcon(img2, "New Mails");
  
  readIcon.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent e) {
    toggleWindow(GFrame.frame);
   }
  });

  unreadIcon.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent e) {
    toggleWindow(GFrame.frame);
   }
  });

  return imageList;
 }
 
 public static void removeAllTrayIcons() {
  TrayIcon[] allIcons = sysTray.getTrayIcons();
  if(allIcons.length >0 ) {
   for (TrayIcon icon : allIcons) {
    sysTray.remove(icon);
   }
  }
 }

 public static void setTrayIconImage(Image myImage) {
  if (SystemTray.isSupported()) {
   System.out.println("System Tray is supported !");
   sysTray = SystemTray.getSystemTray();
   trayIcon = new TrayIcon(myImage, "Mail");

   try {
    System.out.println("Adding Icon to System Tray...");
    sysTray.add(trayIcon);
   } catch (AWTException e) {
    System.out.println(e.getMessage());
   }
  }

 }
  

 public static void runOnce() {
  worker = new SwingWorker() {
   @Override
   public Object doInBackground() {
    removeAllTrayIcons();
    if (GFrame.UNREAD_MESSAGES > 0) {
     try {
      sysTray.add(unreadIcon);
      unreadIcon.displayMessage("New Messages", "You have " + GFrame.UNREAD_MESSAGES + " unread messages",TrayIcon.MessageType.INFO);
     } catch (AWTException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    } else {
     try {
      sysTray.add(readIcon);
      readIcon.displayMessage("No New Messages", "You have " + GFrame.UNREAD_MESSAGES + " unread messages",TrayIcon.MessageType.INFO);
     } catch (AWTException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    return true;
   }
   
   @Override
   public void done() {
    System.out.println("Done with runOnce() job.");
   }
  };
  
  if(!TRAY_MONITOR_RUNNING) {
   List images = loadImages();
   worker.execute();
   /*
   ikon = getUnreadMailNumberIcon();
   if(ikon != null) {
    try {
     sysTray.add(ikon);
    } catch (AWTException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   */
   if(unreadIcon != null) {
    unreadIcon.setToolTip("You have " + GFrame.UNREAD_MESSAGES + " unread messages.");
   }
   TRAY_MONITOR_RUNNING = false;
  }
 }
 
 public static void stopRunOnce() {
  if(worker != null) {
   worker.cancel(true);
  }
  worker = null;
  TRAY_MONITOR_RUNNING = false;
 }
}

No comments :

Post a Comment