source: trunk/EventBenchConsole/src/de/ugoe/cs/eventbench/swing/DlgInsert.java @ 213

Last change on this file since 213 was 213, checked in by jhall, 13 years ago

Some refactoring, added comments and new functionality to be able to easily insert new assertion types.

  • Property svn:mime-type set to text/plain
File size: 17.2 KB
Line 
1package de.ugoe.cs.eventbench.swing;
2
3import java.awt.BorderLayout;
4import java.util.Enumeration;
5import java.util.List;
6import java.util.SortedSet;
7import java.util.TreeSet;
8
9import de.ugoe.cs.eventbench.assertions.AssertEvent;
10import de.ugoe.cs.eventbench.assertions.FileEqualsReplay;
11import de.ugoe.cs.eventbench.assertions.TextEqualsReplay;
12import de.ugoe.cs.eventbench.data.Event;
13import de.ugoe.cs.eventbench.data.GlobalDataContainer;
14import de.ugoe.cs.util.console.Console;
15
16import javax.swing.JButton;
17import javax.swing.JDialog;
18import javax.swing.JPanel;
19import javax.swing.border.EmptyBorder;
20import javax.swing.JComboBox;
21import javax.swing.JLabel;
22import javax.swing.JTextField;
23import javax.swing.JOptionPane;
24import javax.swing.JFileChooser;
25import java.awt.event.MouseAdapter;
26import java.awt.event.MouseEvent;
27import java.io.File;
28import java.awt.event.ActionListener;
29import java.awt.event.ActionEvent;
30import javax.swing.JScrollPane;
31import javax.swing.border.EtchedBorder;
32import javax.swing.JTree;
33import javax.swing.tree.DefaultTreeModel;
34import javax.swing.tree.DefaultMutableTreeNode;
35import javax.swing.tree.TreeNode;
36import javax.swing.tree.TreePath;
37import javax.swing.tree.TreeSelectionModel;
38
39/**
40 * <p>
41 * This class provides the dialog to insert one of the available assertion
42 * types.
43 * </p>
44 *
45 * @author Jeffrey Hall
46 * @version 1.0
47 */
48public class DlgInsert extends JDialog {
49
50        /**
51         * Id for object serialization.
52         */
53        private static final long serialVersionUID = 1L;
54
55        private final JPanel contentPanel = new JPanel();
56        private JTextField textFieldExpectedValue;
57        private JTextField textFieldActualFile;
58        private JTextField textFieldExpectedFile;
59
60        /**
61         * <p>
62         * Launch the dialog
63         * </p>
64         *
65         * @param sequences
66         *            A list of the events where an assertion will be inserted.
67         * @param selectedIndex
68         *            The position for inserting an assertion.
69         * @param insertBefore
70         *            To decide if the user clicked 'insert before' or 'insert
71         *            after'.
72         */
73        public static void showDialog(List<Event<?>> sequences, int selectedIndex,
74                        final boolean insertBefore) {
75                try {
76                        DlgInsert dialog = new DlgInsert(sequences, selectedIndex,
77                                        insertBefore);
78                        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
79                        dialog.setVisible(true);
80                } catch (Exception e) {
81                        e.printStackTrace();
82                }
83        }
84
85        /**
86         * <p>
87         * Create the dialog.
88         * </p>
89         *
90         * @param sequences
91         *            A list of the events where an assertion will be inserted.
92         * @param selectedIndex
93         *            The position for inserting an assertion.
94         * @param insertBefore
95         *            To decide if the user clicked 'insert before' or 'insert
96         *            after'.
97         */
98        public DlgInsert(final List<Event<?>> sequences, final int selectedIndex,
99                        final boolean insertBefore) {
100                initialize(sequences, selectedIndex, insertBefore);
101        }
102
103        /**
104         * <p>
105         * Initialize the contents of the frame.
106         * </p>
107         *
108         * @param sequences
109         *            A list of the events where an assertion will be inserted.
110         * @param selectedIndex
111         *            The position for inserting an assertion.
112         * @param insertBefore
113         *            To decide if the user clicked 'insert before' or 'insert
114         *            after'.
115         */
116        private void initialize(final List<Event<?>> sequences,
117                        final int selectedIndex, final boolean insertBefore) {
118
119                setResizable(false);
120
121                setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
122                setTitle("Insert testcase");
123
124                setModal(true);
125                setBounds(100, 100, 676, 673);
126                getContentPane().setLayout(new BorderLayout());
127                contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
128                getContentPane().add(contentPanel, BorderLayout.CENTER);
129                contentPanel.setLayout(null);
130                final JComboBox comboBoxAssertionType = new JComboBox();
131                final JPanel panelTextEquals = new JPanel();
132                panelTextEquals.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null,
133                                null));
134                final JPanel panelFileEquals = new JPanel();
135                panelFileEquals.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null,
136                                null));
137
138                // *****
139                // define your assertion types here
140                final int numberOfAssertionTypes = 2;
141                final JPanel[] panels = new JPanel[numberOfAssertionTypes];
142                String[] assertionTypes = new String[numberOfAssertionTypes];
143
144                panels[0] = panelTextEquals;
145                assertionTypes[0] = "TextEquals";
146                panels[1] = panelFileEquals;
147                assertionTypes[1] = "OutputFileEquals";
148                // *****
149
150                // add assertion types to comboBox
151                for (int i = 0; i < numberOfAssertionTypes; i++) {
152                        comboBoxAssertionType.addItem(assertionTypes[i]);
153                }
154
155                comboBoxAssertionType.setSelectedIndex(0);
156                comboBoxAssertionType.setBounds(90, 11, 180, 20);
157                contentPanel.add(comboBoxAssertionType);
158
159                final JPanel buttonPane = new JPanel();
160                final JButton okButton = new JButton("Insert");
161
162                // selecting of another assertion type
163                comboBoxAssertionType.addActionListener(new ActionListener() {
164                        public void actionPerformed(ActionEvent arg0) {
165                                if ("comboBoxChanged".equals(arg0.getActionCommand())) {
166
167                                        selectAssertionType(numberOfAssertionTypes, panels,
168                                                        comboBoxAssertionType.getSelectedIndex(),
169                                                        buttonPane, okButton);
170                                }
171                        }
172                });
173
174                JLabel label = new JLabel("Testcase:");
175                label.setBounds(12, 14, 86, 14);
176                contentPanel.add(label);
177
178                JLabel label_1 = new JLabel("Expected value:");
179                label_1.setBounds(10, 11, 96, 14);
180
181                JLabel label_2 = new JLabel("Target:");
182                label_2.setBounds(10, 38, 86, 14);
183
184                textFieldExpectedValue = new JTextField();
185                textFieldExpectedValue.setColumns(10);
186                textFieldExpectedValue.setBounds(116, 8, 524, 20);
187
188                panelTextEquals.setLayout(null);
189                panelTextEquals.setBounds(10, 40, 650, 401);
190                contentPanel.add(panelTextEquals);
191                panelTextEquals.add(label_1);
192                panelTextEquals.add(label_2);
193                panelTextEquals.add(textFieldExpectedValue);
194
195                JScrollPane scrollPane_1 = new JScrollPane();
196                scrollPane_1.setBounds(10, 58, 630, 291);
197                panelTextEquals.add(scrollPane_1);
198
199                final JTree tree = new JTree();
200                DefaultTreeModel treeModel = new DefaultTreeModel(null);
201                final DefaultMutableTreeNode root = new DefaultMutableTreeNode(
202                                "Targets");
203                treeModel.setRoot(root);
204                tree.setModel(treeModel);
205
206                tree.getSelectionModel().setSelectionMode(
207                                TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
208                buildTargetTree(root);
209
210                scrollPane_1.setViewportView(tree);
211
212                // expand all targets
213                JButton btnExpandAll = new JButton("Expand all");
214                btnExpandAll.addMouseListener(new MouseAdapter() {
215                        public void mouseClicked(MouseEvent arg0) {
216
217                                expandAll(tree, new TreePath(root), true);
218                        }
219                });
220                btnExpandAll.setBounds(10, 360, 112, 30);
221                panelTextEquals.add(btnExpandAll);
222
223                // collapse all targets
224                JButton btnCollapseAll = new JButton("Collapse all");
225                btnCollapseAll.addMouseListener(new MouseAdapter() {
226                        public void mouseClicked(MouseEvent arg0) {
227                                expandAll(tree, new TreePath(root), false);
228                        }
229                });
230                btnCollapseAll.setBounds(132, 360, 112, 30);
231                panelTextEquals.add(btnCollapseAll);
232
233                panelFileEquals.setBounds(34, 452, 607, 120);
234                contentPanel.add(panelFileEquals);
235                panelFileEquals.setLayout(null);
236                panelFileEquals.setVisible(false);
237
238                JLabel lblNewLabel = new JLabel("Actual file:");
239                lblNewLabel.setBounds(10, 11, 89, 14);
240                panelFileEquals.add(lblNewLabel);
241
242                textFieldActualFile = new JTextField();
243                textFieldActualFile.setBounds(10, 30, 587, 20);
244                panelFileEquals.add(textFieldActualFile);
245                textFieldActualFile.setColumns(10);
246
247                // open search file dialog
248                JButton btnSearchFile = new JButton("Search file");
249                btnSearchFile.addMouseListener(new MouseAdapter() {
250                        public void mouseClicked(MouseEvent arg0) {
251                                final JFileChooser fc = new JFileChooser();
252                                if (fc.showOpenDialog(contentPanel) == 0) {
253                                        textFieldExpectedFile.setText(fc.getSelectedFile()
254                                                        .getAbsolutePath());
255                                }
256                        }
257                });
258                btnSearchFile.setBounds(93, 61, 89, 23);
259                panelFileEquals.add(btnSearchFile);
260
261                JLabel lblNewLabel_1 = new JLabel("Expected file:");
262                lblNewLabel_1.setBounds(10, 70, 89, 14);
263                panelFileEquals.add(lblNewLabel_1);
264
265                textFieldExpectedFile = new JTextField();
266                textFieldExpectedFile.setColumns(10);
267                textFieldExpectedFile.setBounds(10, 88, 587, 20);
268                panelFileEquals.add(textFieldExpectedFile);
269
270                {
271                        buttonPane.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null,
272                                        null));
273                        buttonPane.setBounds(12, 583, 607, 51);
274                        contentPanel.add(buttonPane);
275                        {
276                                // clicking 'Insert'
277                                okButton.setBounds(462, 11, 135, 31);
278                                okButton.addMouseListener(new MouseAdapter() {
279                                        public void mouseClicked(MouseEvent arg0) {
280                                                if (insertAssertion(sequences, selectedIndex,
281                                                                insertBefore, tree, comboBoxAssertionType
282                                                                                .getSelectedItem().toString()) == false) {
283                                                        return;
284                                                }
285
286                                                dispose();
287                                        }
288                                });
289                                buttonPane.setLayout(null);
290                                okButton.setActionCommand("OK");
291                                buttonPane.add(okButton);
292                                getRootPane().setDefaultButton(okButton);
293                        }
294
295                        {
296                                // clicking 'Cancel'
297                                JButton cancelButton = new JButton("Cancel");
298                                cancelButton.setBounds(10, 11, 135, 31);
299                                cancelButton.addMouseListener(new MouseAdapter() {
300
301                                        public void mouseClicked(MouseEvent arg0) {
302                                                dispose();
303                                        }
304                                });
305                                cancelButton.setActionCommand("Cancel");
306                                buttonPane.add(cancelButton);
307                        }
308                }
309               
310                selectAssertionType(numberOfAssertionTypes, panels,
311                                comboBoxAssertionType.getSelectedIndex(),
312                                buttonPane, okButton);
313        }
314
315        /**
316         * Build up the tree containing all available targets.
317         *
318         * @param root
319         *            The tree root.
320         */
321        @SuppressWarnings("unchecked")
322        private void buildTargetTree(final DefaultMutableTreeNode root) {
323                // get targets from GlobalDataContainer
324                SortedSet<String> listTargets = new TreeSet<String>();
325                try {
326                        listTargets = (SortedSet<String>) GlobalDataContainer.getInstance()
327                                        .getData("ListTargets");
328                } catch (ClassCastException e) {
329                        Console.println("Not able to cast data in GlobalDataContainer to SortedSet of Strings");
330                }
331
332                // build the tree
333                for (String target : listTargets) {
334                        DefaultMutableTreeNode currentParent = root;
335
336                        String splitted[] = target.split("/>");
337
338                        for (String targetPart : splitted) {
339                                DefaultMutableTreeNode node = compareTargetWithNode(
340                                                currentParent, targetPart + "/>");
341
342                                if (node != null) {
343                                        currentParent = node;
344                                } else {
345                                        node = new DefaultMutableTreeNode(targetPart + "/>");
346                                        currentParent.add(node);
347                                        currentParent = node;
348                                }
349                        }
350                }
351        }
352
353        /**
354         * Check if there is a child equal to 'target'.
355         *
356         * @param node
357         *            The parent node which is browsed for a node equal to 'target'.
358         * @param target
359         *            'node' is browsed for this String.
360         * @return If there was no fitting node found, the return value is null.
361         *         Otherwise it is the node.
362         */
363        DefaultMutableTreeNode compareTargetWithNode(DefaultMutableTreeNode node,
364                        String target) {
365
366                if (node.isLeaf()) {
367                        if (target.contains(node.toString()))
368                                return node;
369                        else
370                                return null;
371                } else {
372                        for (@SuppressWarnings("unchecked")
373                        Enumeration<DefaultMutableTreeNode> e = node.children(); e
374                                        .hasMoreElements();) {
375                                DefaultMutableTreeNode nodeReturn = compareTargetWithNode(
376                                                e.nextElement(), target);
377                                if (nodeReturn == null) {
378                                        if (target.contains(node.toString())) {
379                                                return node;
380                                        }
381                                } else {
382                                        return nodeReturn;
383                                }
384                        }
385                }
386
387                return null;
388        }
389
390        /**
391         * Expand or collapse the target tree.
392         *
393         * @param tree
394         *            The tree itself.
395         * @param parent
396         *            The parent node which has to be expanded/collapsed.
397         * @param expand
398         *            To choose wether it is expanded or collapsed.
399         */
400        private void expandAll(JTree tree, TreePath parent, boolean expand) {
401                // Traverse children
402                TreeNode node = (TreeNode) parent.getLastPathComponent();
403                if (node.getChildCount() >= 0) {
404                        for (@SuppressWarnings("unchecked")
405                        Enumeration<DefaultMutableTreeNode> e = node.children(); e
406                                        .hasMoreElements();) {
407                                TreeNode n = (TreeNode) e.nextElement();
408                                TreePath path = parent.pathByAddingChild(n);
409                                expandAll(tree, path, expand);
410                        }
411                }
412
413                // Expansion or collapse must be done bottom-up
414                if (expand) {
415                        tree.expandPath(parent);
416                } else {
417                        tree.collapsePath(parent);
418                }
419        }
420
421        /**
422         * Select another assertion type in the comboBox.
423         *
424         * @param numberOfAssertionTypes
425         *            Number of available assertion types.
426         * @param panels
427         *            The corresponding panels of the types.
428         * @param selectedIndex
429         *            The index of the selected type.
430         * @param buttonPane
431         *            The buttonPane of the dialog.
432         * @param okButton
433         *            The okButton of the buttonPane.
434         */
435        private void selectAssertionType(final int numberOfAssertionTypes,
436                        final JPanel[] panels, int selectedIndex, final JPanel buttonPane,
437                        final JButton okButton) {
438                for (int i = 0; i < numberOfAssertionTypes; i++) {
439                        panels[i].setVisible(false);
440                }
441
442                JPanel activePanel = panels[selectedIndex];
443                activePanel.setVisible(true);
444                activePanel.setLocation(10, 40);
445
446                buttonPane.setLocation(activePanel.getX(), activePanel.getY()
447                                + activePanel.getHeight() + 15);
448                buttonPane.setSize(activePanel.getWidth(), buttonPane.getHeight());
449                setSize(activePanel.getX() + activePanel.getSize().width + 15,
450                                buttonPane.getY() + buttonPane.getSize().height + 35);
451                okButton.setLocation(buttonPane.getWidth() - okButton.getWidth() - 10,
452                                okButton.getY());
453
454        }
455
456        /**
457         * To check if all the parameters needed where entered correctly.
458         *
459         * @param sequences
460         *            A list of the events where an assertion will be inserted.
461         * @param selectedIndex
462         *            The position for inserting an assertion.
463         * @param insertBefore
464         *            To decide if the user clicked 'insert before' or 'insert
465         *            after'.
466         * @param tree
467         *            The target tree.
468         * @param selectedItem
469         *            To identify the selected assertion type.
470         * @return If the assertion was inserted, the return value is true.
471         *         Otherwise it is false.
472         */
473        private boolean insertAssertion(final List<Event<?>> sequences,
474                        final int selectedIndex, final boolean insertBefore,
475                        final JTree tree, final String selectedItem) {
476
477                // FileEquals
478                if (selectedItem == "OutputFileEquals") {
479                        if (textFieldActualFile.getText().length() == 0) {
480                                JOptionPane.showMessageDialog(null,
481                                                "Please declare an actual file.",
482                                                "No actual file declared", JOptionPane.OK_OPTION);
483
484                                return false;
485                        } else if (!new File(textFieldExpectedFile.getText()).exists()) {
486                                if (textFieldExpectedFile.getText().length() == 0) {
487                                        JOptionPane.showMessageDialog(null,
488                                                        "Please choose an expected file.",
489                                                        "No expected file chosen", JOptionPane.OK_OPTION);
490                                } else {
491                                        JOptionPane.showMessageDialog(null, "The expected file \""
492                                                        + textFieldActualFile.getText()
493                                                        + "\" does not exist.",
494                                                        "Expected file does not exist",
495                                                        JOptionPane.OK_OPTION);
496                                }
497
498                                return false;
499                        } else {
500                                FileEqualsReplay file = new FileEqualsReplay();
501                                file.setActualFile(textFieldActualFile.getText());
502                                file.setExpectedFile(textFieldExpectedFile.getText());
503
504                                AssertEvent<FileEqualsReplay> e = new AssertEvent<FileEqualsReplay>(
505                                                "FileEquals");
506                                e.addReplayEvent(file);
507                                e.setTarget(" ");
508                                if (insertBefore)
509                                        sequences.add(selectedIndex, e);
510                                else
511                                        sequences.add(selectedIndex + 1, e);
512                        }
513                }
514                // TextEquals
515                else if (selectedItem == "TextEquals") {
516                        if (textFieldExpectedValue.getText().length() == 0) {
517                                JOptionPane.showMessageDialog(null,
518                                                "\"Expected value\" is missing.", "Expected value",
519                                                JOptionPane.OK_OPTION);
520                                return false;
521                        } else if (tree.getSelectionCount() == 0
522                                        || tree.getSelectionPath().toString()
523                                                        .compareTo("[Targets]") == 0) {
524                                JOptionPane.showMessageDialog(null, "Please select a target.",
525                                                "No target selected", JOptionPane.OK_OPTION);
526                                return false;
527                        } else {
528
529                                // get target ***
530                                String selectionPath = tree.getSelectionPath().toString();
531
532                                // remove leading and ending brackets
533                                selectionPath = selectionPath.substring(1);
534                                selectionPath = selectionPath.substring(0,
535                                                selectionPath.length() - 1);
536                                // remove leading string "targets"
537                                selectionPath = selectionPath.substring(7);
538
539                                String splitted[] = selectionPath.toString().split(", ");
540
541                                // get all parents
542                                String target = "";
543                                for (int i = 0; i < splitted.length; i++) {
544                                        target += splitted[i];
545                                }
546                                // ***
547
548                                TextEqualsReplay text = new TextEqualsReplay();
549                                text.setExpectedValue(textFieldExpectedValue.getText());
550                                text.setTarget(target);
551
552                                AssertEvent<TextEqualsReplay> e = new AssertEvent<TextEqualsReplay>(
553                                                "TextEquals");
554                                e.addReplayEvent(text);
555                                e.setTarget(" ");
556                                if (insertBefore)
557                                        sequences.add(selectedIndex, e);
558                                else
559                                        sequences.add(selectedIndex + 1, e);
560                        }
561                }
562
563                return true;
564        }
565}
Note: See TracBrowser for help on using the repository browser.