View Javadoc
1   package com.nilhcem.fakesmtp.gui.info;
2   
3   import java.awt.Font;
4   import java.util.Observable;
5   import java.util.Observer;
6   
7   import javax.swing.JLabel;
8   
9   import com.nilhcem.fakesmtp.model.UIModel;
10  import com.nilhcem.fakesmtp.server.MailSaver;
11  
12  import com.apple.eawt.Application;
13  import org.slf4j.Logger;
14  import org.slf4j.LoggerFactory;
15  
16  /**
17   * Label class to display the number of received emails.
18   *
19   * @author Nilhcem
20   * @since 1.0
21   */
22  public final class NbReceivedLabel implements Observer {
23  
24  	private static final Logger LOGGER = LoggerFactory.getLogger(NbReceivedLabel.class);
25  
26  	private final JLabel nbReceived = new JLabel("0");
27  
28  	/**
29  	 * Creates the label class (with a bold font).
30  	 */
31  	public NbReceivedLabel() {
32  		Font boldFont = new Font(nbReceived.getFont().getName(), Font.BOLD, nbReceived.getFont().getSize());
33  		nbReceived.setFont(boldFont);
34  	}
35  
36  	/**
37  	 * Returns the JLabel object.
38  	 *
39  	 * @return the JLabel object.
40  	 */
41  	public JLabel get() {
42  		return nbReceived;
43  	}
44  
45  	/**
46  	 * Actions which will be done when the component will be notified by an Observable object.
47  	 * <ul>
48  	 *   <li>If the observable element is a {@link MailSaver} object, the method will increment
49  	 *   the number of received messages and update the {@link UIModel};</li>
50  	 *   <li>If the observable element is a {@link ClearAllButton}, the method will reinitialize
51  	 *   the number of received messages and update the {@link UIModel};</li>
52  	 *   <li>When running on OS X the method will also update the Dock Icon with the number of
53  	 *   received messages.</li>
54  	 * </ul>
55  	 *
56  	 * @param o the observable element which will notify this class.
57  	 * @param arg optional parameters (not used).
58  	 */
59  	@Override
60  	public void update(Observable o, Object arg) {
61  		if (o instanceof MailSaver) {
62  			UIModel model = UIModel.INSTANCE;
63  			int countMsg = model.getNbMessageReceived() + 1;
64  			String countMsgStr = Integer.toString(countMsg);
65  
66  			model.setNbMessageReceived(countMsg);
67  			updateDockIconBadge(countMsgStr);
68  			nbReceived.setText(countMsgStr);
69  		} else if (o instanceof ClearAllButton) {
70  			UIModel.INSTANCE.setNbMessageReceived(0);
71  			updateDockIconBadge("");
72  			nbReceived.setText("0");
73  		}
74  	}
75  
76  	private void updateDockIconBadge(String badgeValue) {
77  		try {
78  			Application.getApplication().setDockIconBadge(badgeValue);
79  		} catch (RuntimeException e) {
80  			LOGGER.debug("Error: {} - This is probably because we run on a non-Mac platform and these components are not implemented", e.getMessage());
81  		} catch (Exception e) {
82  			LOGGER.error("", e);
83  		}
84  	}
85  }