1   /**
2    * This program is free software: you can redistribute it and/or modify
3    * it under the terms of the GNU General Public License as published by
4    * the Free Software Foundation, version 3.
5    *
6    * This program is distributed in the hope that it will be useful,
7    * but WITHOUT ANY WARRANTY; without even the implied warranty of
8    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9    * GNU General Public License for more details.
10   *
11   * You should have received a copy of the GNU General Public License
12   * along with this program. If not, see <http://www.gnu.org/licenses/>.
13   */
14  
15  package net.curre.prefcount.event;
16  
17  import java.awt.*;
18  import java.awt.event.ActionEvent;
19  import java.awt.event.ItemEvent;
20  import java.awt.event.KeyEvent;
21  import java.io.File;
22  import java.util.ArrayList;
23  import java.util.Calendar;
24  import java.util.List;
25  import java.util.logging.Logger;
26  import javax.swing.*;
27  
28  import net.curre.prefcount.PrefCountRegistry;
29  import static net.curre.prefcount.PrefCountRegistry.AVAILABLE_LOCALES;
30  import static net.curre.prefcount.PrefCountRegistry.DEFAULT_LOCALE_ID;
31  import net.curre.prefcount.bean.PlayerStatistics;
32  import net.curre.prefcount.gui.DialogInnerPanel;
33  import net.curre.prefcount.gui.GuiPackageHelper;
34  import net.curre.prefcount.gui.LastInputPanel;
35  import net.curre.prefcount.gui.MainWindow;
36  import net.curre.prefcount.gui.PlayerDataPanel;
37  import net.curre.prefcount.gui.PlayersNamesPanel;
38  import net.curre.prefcount.gui.PlayerDialogBasePanel;
39  import net.curre.prefcount.gui.aa.AAJButton;
40  import net.curre.prefcount.service.ResultService;
41  import net.curre.prefcount.test.BaseTestCase;
42  import net.curre.prefcount.util.LocaleExt;
43  
44  /**
45   * This is a junit test for testing event classes.
46   * <p/>
47   * Created date: Dec 15, 2007
48   *
49   * @author Yevgeny Nyden
50   */
51  public class AllEventsTest extends BaseTestCase {
52  
53    /** Private class logger. */
54    private static Logger log = Logger.getLogger(AllEventsTest.class.getName());
55  
56    /** Reference to the main window. */
57    private static MainWindow window = null;
58  
59    /**
60     * Creates and sets the main window (class variable)
61     * ans also initializes the result bean with a 3-player game data.
62     */
63    public void setUp() throws Exception {
64      super.setUp();
65      synchronized (this) {
66        if (window == null) {
67          log.info("Initializing main window.");
68          PrefCountRegistry.getInstance().setCurrentLocale(DEFAULT_LOCALE_ID);
69          window = new MainWindow(false);
70        }
71        PrefCountRegistry.getInstance().setMainWindow(window);
72      }
73    }
74  
75    /** Tests the ChangeLanguageActionListener class. */
76    public void testChangeLanguageActionListener() {
77  
78      log.info("Running testChangeLanguageActionListener()...");
79  
80      for (LocaleExt locale : AVAILABLE_LOCALES) {
81        ChangeLanguageActionListener event = new ChangeLanguageActionListener(locale.getLocale().getLanguage());
82        CheckboxMenuItem item = new CheckboxMenuItem("box");
83        ItemEvent itEvent = new ItemEvent(item, ItemEvent.ITEM_FIRST, item, ItemEvent.SELECTED);
84        event.itemStateChanged(itEvent);
85        LocaleExt currLocale = PrefCountRegistry.getCurrentLocale();
86        assertNotNull("Current locale is null");
87        assertEquals("Current locale is wrong;", locale, currLocale);
88      }
89    }
90  
91    /** Tests the ComputeButtonActionListener class. */
92    public void testComputeButtonActionListener() {
93  
94      log.info("Running testComputeButtonActionListener()...");
95  
96      try {
97        initializeResultBean();
98        PlayerDialogBasePanel dialogFrame = new PlayerDialogBasePanel(3, window);
99        LastInputPanel lastPanel = new LastInputPanel(dialogFrame);
100       lastPanel.setTargetBulletText("10");
101       PrefCountRegistry.getInstance().setLastInputPanel(lastPanel);
102 
103       // sanity check
104       assertFalse("Final scores should not be ready yet", window.playerResults.isFinalScoresReady());
105 
106       ComputeButtonActionListener action = new ComputeButtonActionListener();
107       action.keyTyped(null);   // show do nothing
108       action.keyPressed(null); // show do nothing
109 
110       assertFalse("Final scores should not be ready yet", window.playerResults.isFinalScoresReady());
111       action.actionPerformed(null); // should perform/trigger action
112       assertTrue("Final scores should be ready", window.playerResults.isFinalScoresReady());
113 
114       // resetting the result bean
115       ResultService.clearFinalResults(window.playerResults);
116       initializeResultBean();
117       assertFalse("Final scores should not be ready yet", window.playerResults.isFinalScoresReady());
118 
119       // expect only 'enter' to trigger action
120       KeyEvent event = createKeyEventHelper(0, KeyEvent.VK_S, 's');
121       action.keyReleased(event); // should NOT perform/trigger action
122       assertFalse("Final scores should not be ready yet", window.playerResults.isFinalScoresReady());
123 
124       event = createKeyEventHelper(0, KeyEvent.VK_ENTER, '\n');
125       action.keyReleased(event); // should perform/trigger action
126       assertTrue("Final scores should be ready", window.playerResults.isFinalScoresReady());
127     } finally {
128       ResultService.clearFinalResults(window.playerResults);
129       PrefCountRegistry.getInstance().setLastInputPanel(null);
130       window.playerDialogFrame = null;
131     }
132   }
133 
134   /** Tests the DialogButtonNavigationListener class. */
135   public void testDialogButtonNavigationListener() {
136 
137     log.info("Running testDialogButtonNavigationListener()...");
138     try {
139       // starting player dialog and populating the names
140       window.startPlayerDialog(3);
141       initializeResultBean();
142       DialogInnerPanel prevPanel = window.playerDialogFrame.getCurrentInnerPanel();
143       assertNotNull("Current DialogInnerPanel is null", prevPanel);
144       assertTrue("Wrong current DialogInnerPanel", prevPanel instanceof PlayersNamesPanel);
145       List<JTextField> fields = GuiPackageHelper.getPlayerFields((PlayersNamesPanel) prevPanel);
146       setTextFields(fields, "A", "B", "C");
147 
148       // testing moving forward via actionPerformed()
149       DialogButtonNavigationListener actionForward =
150           new DialogButtonNavigationListener(true, window.playerDialogFrame);
151       actionForward.keyTyped(null);   // should have no effect
152       actionForward.keyPressed(null); // should have no effect
153       actionForward.focusGained(null); // should have no effect
154       actionForward.focusLost(null);
155       checkCurrentPanel(PlayersNamesPanel.class);
156 
157       actionForward.actionPerformed(null);
158       checkCurrentPanel(PlayerDataPanel.class);
159       actionForward.actionPerformed(null);
160       checkCurrentPanel(PlayerDataPanel.class);
161       actionForward.actionPerformed(null);
162       checkCurrentPanel(PlayerDataPanel.class);
163       actionForward.actionPerformed(null);
164       checkCurrentPanel(LastInputPanel.class);
165 
166       // testing moving back via actionPerformed()
167       DialogButtonNavigationListener actionBackward =
168           new DialogButtonNavigationListener(false, window.playerDialogFrame);
169       actionBackward.keyTyped(null);   // should have no effect
170       actionBackward.keyPressed(null); // should have no effect
171       actionBackward.focusGained(null); // should have no effect
172       actionBackward.focusLost(null);
173       checkCurrentPanel(LastInputPanel.class);
174 
175       LastInputPanel lastPanel = (LastInputPanel) window.playerDialogFrame.getCurrentInnerPanel();
176       lastPanel.setTargetBulletText("10");
177       actionBackward.actionPerformed(null);
178       checkCurrentPanel(PlayerDataPanel.class);
179       actionBackward.actionPerformed(null);
180       checkCurrentPanel(PlayerDataPanel.class);
181       actionBackward.actionPerformed(null);
182       checkCurrentPanel(PlayerDataPanel.class);
183       actionBackward.actionPerformed(null);
184       checkCurrentPanel(PlayersNamesPanel.class);
185 
186       // testing moving forward via keyReleased()
187       KeyEvent bEvent = createKeyEventHelper(0, KeyEvent.VK_ENTER, 'm');
188       actionForward.keyReleased(bEvent); // should have no effect
189       checkCurrentPanel(PlayersNamesPanel.class);
190       ActionEvent event = new ActionEvent(new AAJButton(), 0, "");
191       actionForward.actionPerformed(event);
192       checkCurrentPanel(PlayerDataPanel.class);
193       actionForward.actionPerformed(event);
194       checkCurrentPanel(PlayerDataPanel.class);
195       actionForward.actionPerformed(event);
196       checkCurrentPanel(PlayerDataPanel.class);
197       actionForward.actionPerformed(event);
198       checkCurrentPanel(LastInputPanel.class);
199 
200       // testing moving back via keyReleased()
201       actionBackward.keyReleased(bEvent);
202       checkCurrentPanel(LastInputPanel.class); // should have no effect
203       actionBackward.actionPerformed(event);
204       checkCurrentPanel(PlayerDataPanel.class);
205       actionBackward.actionPerformed(event);
206       checkCurrentPanel(PlayerDataPanel.class);
207       actionBackward.actionPerformed(event);
208       checkCurrentPanel(PlayerDataPanel.class);
209       actionBackward.actionPerformed(event);
210       checkCurrentPanel(PlayersNamesPanel.class);
211 
212     } finally {
213       ResultService.clearFinalResults(window.playerResults);
214     }
215   }
216 
217   /** Tests the SaveResetSettingsActionListener class. */
218   public void testSaveResetSettingsActionListener() {
219 
220     log.info("Running testSaveResetSettingsActionListener()...");
221     try {
222       PrefCountRegistry.getInstance().setSettingsFilePath(SETTINGS_FILE);
223       deleteTestSettingsFile();
224       File file = new File(SETTINGS_FILE);
225       assertFalse("Settings file must not have been created", file.exists());
226 
227       // trying to trigger save action
228       SaveResetSettingsActionListener action = new SaveResetSettingsActionListener(true);
229       action.actionPerformed(null);
230       assertTrue("Action didn't trigger event - settings file hasn't been created", file.exists());
231 
232       // removing the settings file and trying to reset settings
233       deleteTestSettingsFile();
234       assertFalse("Settings file should be removed", file.exists());
235       action = new SaveResetSettingsActionListener(false);
236       action.actionPerformed(null);
237       assertTrue("Action didn't trigger event - settings file hasn't been created", file.exists());
238 
239       // testing errors
240       assertTrue("Internal error - unable to set file read only", file.setReadOnly());
241       try {
242         action.actionPerformed(null);
243       } catch (Exception e) {
244         fail("SaveResetSettingsActionListener should not throw exceptions!");
245       }
246 
247     } finally {
248       deleteTestSettingsFile();
249     }
250   }
251 
252   /** Tests the StartAskingQuestionsListener class. */
253   public void testStartAskingQuestionsListener() {
254 
255     log.info("Running testStartAskingQuestionsListener()...");
256 
257     // creating a new window
258     window = new MainWindow(false);
259     PrefCountRegistry.getInstance().setMainWindow(window);
260     JButton but3 = GuiPackageHelper.getButton3(window);
261     assertFalse("Button 3 should not be selected", but3.isSelected());
262 
263     StartAskingQuestionsListener listener = new StartAskingQuestionsListener(3);
264 
265     listener.keyTyped(null);   // expect no effect
266     listener.keyPressed(null); // expect no effect
267     assertFalse("The action should not has been triggered yet", but3.isSelected());
268 
269     listener.actionPerformed(null);
270     assertTrue("actionPerformed() didn't seem to perform action", but3.isSelected());
271 
272 
273     window = new MainWindow(false);
274     PrefCountRegistry.getInstance().setMainWindow(window);
275     listener = new StartAskingQuestionsListener(3);
276     KeyEvent event = createKeyEventHelper(0, KeyEvent.VK_P, 'p');
277     listener.keyReleased(event);  // should have no effect
278     but3 = GuiPackageHelper.getButton3(window);
279     assertFalse("The action should not has been triggered yet", but3.isSelected());
280 
281     event = createKeyEventHelper(0, KeyEvent.VK_ENTER, '\n');
282     listener.keyReleased(event);
283     assertTrue("actionPerformed() didn't seem to perform action", but3.isSelected());
284   }
285 
286   /** Private methods ***********************/
287 
288   /**
289    * Initializes the result bean with a
290    * 3-player game data.
291    */
292   private static void initializeResultBean() {
293     // creating game data for 3 players
294     window.playerResults.setTargetBullet(56);
295     List<PlayerStatistics> stats = new ArrayList<PlayerStatistics>(3);
296     stats.add(createPlayerStatHelper(window.playerResults, 0, "dariya", 56, 22, "24", "32"));
297     stats.add(createPlayerStatHelper(window.playerResults, 1, "kolya", 22, 22, "100", "32"));
298     stats.add(createPlayerStatHelper(window.playerResults, 2, "fedya", 12, 34, "72", "56"));
299     window.playerResults.setPlayerStats(stats);
300   }
301 
302   /**
303    * Checks the current player dialog inner panel.
304    *
305    * @param clazz Expected panel class.
306    */
307   private static <T extends DialogInnerPanel> void checkCurrentPanel(Class<T> clazz) {
308     DialogInnerPanel currPanel = window.playerDialogFrame.getCurrentInnerPanel();
309     assertNotNull("Current DialogInnerPanel is null", currPanel);
310     if (!clazz.isInstance(currPanel)) {
311       fail("Wrong current DialogInnerPanel; expected: " +
312            clazz.getName() + ", but was: " + currPanel.getClass().getName());
313     }
314   }
315 
316   /**
317    * Helper method to create a <code>KeyEvent</code> object.
318    *
319    * @param modifiers Modifiers to specify.
320    * @param code      Code to set.
321    * @param character Character to set.
322    * @return Newly created <code>KeyEvent</code> object.
323    */
324   private static KeyEvent createKeyEventHelper(int modifiers, int code, char character) {
325     return new KeyEvent(new AAJButton("DUMMY"), KeyEvent.KEY_LAST,
326                         Calendar.getInstance().getTimeInMillis(),
327                         modifiers, code, character, KeyEvent.KEY_LOCATION_STANDARD);
328   }
329 
330 }