-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestGUI.java
More file actions
1978 lines (1741 loc) · 84.2 KB
/
TestGUI.java
File metadata and controls
1978 lines (1741 loc) · 84.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* TestGUI by Kris McCoy & Dagar Ahmed v2.13
* Run customized tests of various classes/method and custom build your GUI
* This version adds:
* Cleared ambiguity for Point class.
* TO CREATE A HEADER IN THE GUI
* void header(String name)
*
* Example:
* header("Histogram");
* TO CREATE A MESSAGE/NOTE IN THE GUI
* void message(String information)
* void message(String information, boolean correct)
*
* Example:
* message("This portion of the assignment is optional and for extra credit only."); //default grey color
* message("I'm requesting that this method have a green background.", true) //green color
* message("I'm requesting that this method have a red background.", false) //red color
*
* TO CREATE A BUTTON FOR LOADING SOURCE CODE / DATA FILES
* void srcButton(String sourceFileNamesCommaDelimited)
* void srcButton(String[] sourceFileNames)
*
* Example:
* srcButton("PracticeProblems, Data.txt"); //If file has no extension, .java is assumed
* srcButton(new String[]{"Car.java", "Truck.java", "DataFile.in"}
* TO TEST A CONSTRUCTOR AND RECEIVE THE INSTANTIATED OBJECT:
* Object makeObject(String className, Object[] args)
* Object makeObject(String className, Object[] args, String inputScript)
*
* Parameters:
* className - Name of the constructor you are calling
* args - arguments you are passing to the constructor. null can be used if calling a default
* (no parameter) constructor
* inputScript - data that will be fed through System.in in the event that the constructor
* requests user input
*
* Returns:
* the object constructed from the call
*
* Example usage:
* //Using this... // is similar to using this...
* Object o = makeObject("Person", new Object[]{"Fred", 27}); // Object o = new Person("Fred", 27);
* Object o = makeObject("Person", null, "Fred\n27"); // Object o = new Person(); (provides user input)
* TO TEST A METHOD (The testMethod method is very overloaded. You have several options.)
* Object testMethod(Object o, String mName, Object[] args)
* Object testMethod(String cName, String mName, Object[] args)
* Object testMethod(Object o, String mName, Object[] args, String expOut)
* Object testMethod(String cName, String mName, Object[] args, String expOut)
* Object testMethod(Object o, String mName, Object[] args, String expOut, double allowableError)
* Object testMethod(String cName, String mName, Object[] args, String expOut, double allowableError)
* Object testMethod(Object o, String mName, Object[] args, String expOut, String inputScript)
* Object testMethod(String cName, String mName, Object[] args, String expOut, String inputScript)
* Object testMethod(Object o, String mName, Object[] args, String expOut, double allowableError, String inputScript)
* Object testMethod(String cName, String mName, Object[] args, String expOut, double allowableError, String inputScript)
*
* Parameters:
* o - the object invoking the method you want to test (for non-static methods)
* cName - name of the class invoking the method you want to test (for static methods)
* mName - name of the method being invoked
* args - arguments being passing to the method. null can be used if the method being testing
* does not require any parameters.
* expOut - the expected output or return value from running the method
* If an expOut is provided the GUI will compare this against the actual output/return
* value from the test and make a comparison. Leave this off or pass null if you don't want
* to make a red light/green light comparison against the actual output.)
* Wildcards can be used in the expected output to allow for tokens that aren't expected to match.
* Wildcards: %int% - actual output may contain any int value at this location of this token
* %double% - actual output may contain any double value at this location of this token
* %word% - actual output may contain any single token at this location of this token
* %line% - actual output may contain any number of any tokens from this location to the end of the line.
* allowableError - the plus/minus error allowable when conparing floating-point values.
* If the expOut contains a value of 10.0 and the allowableError is .2, then the actual
* output must fall between 9.8 and 10.2. To handle minor errors caused by rounding of floating-point values,
* the recommended allowable error is .0001.
* inputScript - data that will be fed through System.in in the event that the method
* requests user input
*
* Returns:
* the return value of the method being invoked (as Object)
* or null when testing void methods or the student code fails to run/throws exception
*
* Example usage:
* //Using this... // is similar to using this...
* testMethod(myHistogram, "encounter", new Object[]{7}); // myHistogram.encounter(7);
* testMethod("Practice", "printXs", new Object[]{4}, "xxxx") // Practice.printXs(4);
* int s = testMethod(myCar, "getSpeed", null, "55"); // int s = myCar.getSpeed();
* TO GET A CLASS OBJECT FROM ITS NAME
* Class getClassFromName(String className)
*
* Example usage:
* Class c = getClassFromName("Truck");
*
* Note: Why would you want to do this? This will allow you to collect various information about
* how students coded the class, useful for checking how well students understand class design and
* inheritance. You can verify that the Truck class extends the Vehicle class. You can find out
* how many declared fields the student included (vs how many fields were inherited.) Also, this is
* your only way to get a version of the Class object that uses the same ClassLoader as the TestGUI
* (in the event that you need to try to cast Object o as a student-coded Truck.) For more info,
* read about the Class class here: https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html
* TO SET HOW MANY SECONDS SHOULD BE WAITED BEFORE AN INDIVIDUAL TEST TIMES OUT
* setTimeOutSec(int seconds); //how many seconds to wait before giving up. (Default 2)
*
*/
import java.awt.*;
import java.awt.Point;
import java.awt.event.*;
import java.io.*;
import java.lang.invoke.*;
import java.lang.reflect.*;
import java.nio.*;
import java.nio.file.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.filechooser.*;
import javax.tools.*;
@SuppressWarnings({"unchecked", "deprecation"})
public class TestGUI
{
//ADJUSTABLES. EDIT AS YOU SEE FIT
private static final int WIDTH = 940;
private static final int HEIGHT = 800;
private static final int SOURCE_CODE_FRAME_WIDTH = 940;
private static final int SOURCE_CODE_FRAME_HEIGHT = 800;
private static final Font HEADER_FONT = new Font(Font.MONOSPACED, Font.BOLD, 20);
private static final Font REGULAR_FONT = new Font(Font.MONOSPACED, Font.PLAIN, 16);
private static final Font MESSAGE_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 16);
private static final Font PATH_FONT = new Font(Font.MONOSPACED, Font.PLAIN, 16);
private static final Color HEADER_BG_COLOR = new Color(200,200,255);
private static final Color MESSAGE_BG_COLOR = new Color(200,200,200);
public static final Color RED = new Color(250, 180, 180); //Output did NOT match expected
public static final Color YELLOW = new Color(250, 250, 180); //Output had spacing issues only
public static final Color GREEN = new Color(160, 225, 200); //Output DID match expected
private static final int SCROLL_SPEED = 40;
private static final String NOFILES_ALERT = "WARNING: The current source directory does not contain any helpful source files. Choose new source path.";
//BUT DON'T MESS WITH THESE.
public static final double V_NUM = 2.13;
private static String windowName;
private static Class testClass;
private static ArrayList<TestData> testResults = new ArrayList<TestGUI.TestData>();
private static int countGreen, countYellow, countRed;
private ArrayList<JPanel> subFrameList;
private static final PrintStream originalSystemOut = System.out;
private static final InputStream originalSystemIn = System.in;
private static InputStream hijackedSystemIn;
private JFrame mainFrame;
private JScrollPane scrPane;
private JTextArea srcLabel, greenLabel, yellowLabel, redLabel;
private JPanel buttonPanel, statPanel;
private JButton loadButton, nextSourceButton, retestButton;
private ArrayList<JButton> srcButtonList = new ArrayList<JButton>();
private static final String mistakeStartFlag = (char)16+"!!", mistakeStopFlag = "!!"+(char)17;
private static File srcPath;
private static File originalSrcPath;
private static JFileChooser chooser;
private static URL classUrl;
private static URLClassLoader classLoader;
private static boolean timeOutThrown = false;
/**
* Used on initial build to collect window name and class name containing test cases
* Default source path is the directory containing this TestGUI.class
*/
public TestGUI(){
try {
String callingClassName = Thread.currentThread().getStackTrace()[2].getClassName();
this.windowName = callingClassName;
this.testClass = Class.forName(callingClassName);
} catch (Exception e) {}
letsDoSomeGUI();
}
public void letsDoSomeGUI() {
SwingUtilities.invokeLater(
new Runnable()
{
@Override
public void run() {
buildWindow();
}
});
}
public void buildWindow() {
mainFrame = new JFrame("Current Test Sequence: " + windowName);
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainFrame.setSize(WIDTH, HEIGHT);
BorderLayout buttonLayout = new BorderLayout();
buttonLayout.setHgap(5);
buttonPanel = new JPanel(buttonLayout);
buttonPanel.setBorder(new EmptyBorder(5,5,5,5));
loadButton = new JButton("Choose Source");
loadButton.setToolTipText( "Select a new source folder." );
nextSourceButton = new JButton(">");
nextSourceButton.setToolTipText( "Advance to next source folder in directory tree." );
initializeFileChooser();
retestButton = new JButton("Retest");
retestButton.setToolTipText( "Recompile source folder and run tests again." );
retestButton.setEnabled(false);
setSrcLabel(srcPath);
setGreenLabel(countGreen=0);
setYellowLabel(countYellow=0);
setRedLabel(countRed=0);
loadButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e) {
if (loadPath()) { compileAndTest(); }
}
}
);
nextSourceButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e) {
nextSourceFolder();
}
}
);
retestButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e) {
compileAndTest();
}
}
);
BorderLayout statLayout = new BorderLayout();
statPanel = new JPanel(statLayout);
statPanel.add(greenLabel, BorderLayout.WEST);
statPanel.add(yellowLabel, BorderLayout.CENTER);
statPanel.add(redLabel, BorderLayout.EAST);
BorderLayout eastButtonLayout = new BorderLayout();
JPanel eastButtonPanel = new JPanel(eastButtonLayout);
eastButtonPanel.add(nextSourceButton, BorderLayout.WEST);
eastButtonPanel.add(retestButton, BorderLayout.CENTER);
eastButtonPanel.add(statPanel, BorderLayout.EAST);
buttonPanel.add(srcLabel, BorderLayout.CENTER);
buttonPanel.add(loadButton, BorderLayout.WEST);
buttonPanel.add(eastButtonPanel, BorderLayout.EAST);
mainFrame.add(buttonPanel, BorderLayout.NORTH);
compileAndTest(); //run a test from current directory
}
@SuppressWarnings("unchecked")
private void compileAndTest() {
if (scrPane != null) {
mainFrame.remove(scrPane);
}
retestButton.setEnabled(false);
loadButton.setEnabled(false);
nextSourceButton.setEnabled(false);
buttonPanel.remove(srcLabel);
setSrcLabel("Loading... Please wait.");
countGreen = countYellow = countRed = 0;
refreshStatPanel();
buttonPanel.add(srcLabel, BorderLayout.CENTER);
mainFrame.repaint();
mainFrame.setVisible(true);
SwingUtilities.invokeLater(
new Runnable()
{
@Override
public void run() {
try {
testResults = new ArrayList<TestGUI.TestData>();
compileAllSrcFiles();
} catch(Exception e) { System.out.println("Unable to compile source files."); }
try {
EchoingByteArrayInputStream.hijackSystemIn();
testClass.getMethod("runTests").invoke(testClass);
EchoingByteArrayInputStream.restoreSystemIn();
} catch(Exception e) { System.out.println("Error with runTests. Bad test cases?\nException: "+e); }
try {
showResults();
buttonPanel.remove(srcLabel);
setSrcLabel(srcPath);
buttonPanel.add(srcLabel, BorderLayout.CENTER);
refreshStatPanel();
if (!timeOutThrown) {
retestButton.setEnabled(true);
loadButton.setEnabled(true);
nextSourceButton.setEnabled(true);
}
mainFrame.setVisible(true);
} catch(Exception e) { System.out.println("Unable to build GUI."); }
}
}
);
}
private void nextSourceFolder(){
//Advance the current source file directory to the next directory in the directory tree
if (srcPath == null)
return;
chooser = new JFileChooser(".");
chooser.setCurrentDirectory(srcPath);
File previous = chooser.getCurrentDirectory();
if (! srcPath.getName().equals(originalSrcPath.getName())) chooser.changeToParentDirectory();
chooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES);
File fDir = chooser.getCurrentDirectory();
FileSystemView fsv = chooser.getFileSystemView();
File[] fileArray = fsv.getFiles(fDir, true);
for (int i = 0; i < fileArray.length; i++) {
File f = fileArray[i];
if (f.isDirectory() && f.getPath().equals(previous.getPath())) {
for (int j = i + 1; j < fileArray.length; j++) {
File next = fileArray[j];
if (next.isDirectory()) {
srcPath = next;
compileAndTest();
return;
}
}
}
}
}
private void initializeFileChooser(){
// Let the user pick from a filtered list of files
chooser = new JFileChooser(".");
Action details = chooser.getActionMap().get("viewTypeDetails");
//details.actionPerformed(null);
if (srcPath == null) {
srcPath = originalSrcPath = new File(System.getProperty("user.dir"));
}
chooser.setCurrentDirectory(srcPath);
if (! srcPath.getName().equals(originalSrcPath.getName())) chooser.changeToParentDirectory();
chooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileFilter(
new javax.swing.filechooser.FileFilter()
{
String description = "Java files";
@Override
public boolean accept(File f) {
if (f.isDirectory())
return true;
if (f.getName().endsWith(".java"))
return true;
return false;
}
@Override
public String getDescription() {
return this.description; }
}
);
}
private boolean loadPath() {
int returnVal = chooser.showOpenDialog(mainFrame);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File newFile = chooser.getSelectedFile();
srcPath = (newFile.isDirectory()) ? newFile : newFile.getParentFile();
} else {
return false;
}
return true;
}
public void compileAllSrcFiles() {
TestData.setClassLoader();
File[] arrayOfFiles = srcPath.listFiles(
new java.io.FileFilter()
{
@Override
public boolean accept(File f) {
String fn = f.getName();
String exclude1 = testClass.getName()+".java";
String exclude2 = "TestGUI.java";
if (f.getName().endsWith(".java")) {
if (f.getName().equals(exclude1) || f.getName().equals(exclude2))
return false;
return true;
}
return false;
}
}
);
if (arrayOfFiles.length==0) {
TestData.messageAlert(NOFILES_ALERT);
return;
}
//Before we compile this list of .java files, let's delete old .class files
for (File jFile : arrayOfFiles)
{
String jFilename = jFile.getPath();
String cFilename = jFilename.substring(0, jFilename.indexOf(".java")) + ".class";
File toDelete = new File(cFilename);
toDelete.delete();
}
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
String[] baseArgs = new String[]{
"-Xlint:none",
"-d",
srcPath.getAbsolutePath(),
"-g",
"-sourcepath",
srcPath.getAbsolutePath()
};
ArrayList<String> arguments = new ArrayList<String>(Arrays.asList(baseArgs));
ArrayList<String> fileNames = new ArrayList<String>();
for (File f : arrayOfFiles) arguments.add(f.getPath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
javaCompiler.run(null, null, baos, arguments.toArray(new String[arguments.size()]));
//Data in the baos means there was a compile error. Try one file at a time.
if (baos.size() > 0) {
baos.reset();
System.out.println("Trying to compile all project files at once caused an error.");
System.out.println("Please wait while I compile one file at a time.");
arguments = new ArrayList<String>(Arrays.asList(baseArgs));
for (File f : arrayOfFiles) {
arguments.add(f.getPath());
javaCompiler.run(null, null, baos, arguments.toArray(new String[arguments.size()]));
arguments.remove(arguments.size()-1);
}
if (baos.size() > 0) System.out.println("\n\nCompiler Errors:\n" + baos);
}
}
public void showResults() {
subFrameList = new ArrayList<JPanel>();
for(TestData td : testResults){
if(td.getHeader() != null)
makeHeaderFrame(td);
if(td.getMessage() != null)
makeMessageFrame(td);
if(td.getSrcFiles() != null)
makeSrcButtonFrame(td);
if ( td.getExpectedOut() != null || td.getActualOut() != null )
makeFourSubFrames(td);
else if(td.getMethodCall() != null)
makeTwoSubFrames(td);
}
//put all subFrames into a scrollable box
ScrollablePanel subFrameBox = new ScrollablePanel();
subFrameBox.setLayout(new BoxLayout(subFrameBox, BoxLayout.Y_AXIS));
for(JPanel subFrame : subFrameList)
subFrameBox.add(subFrame);
//Put that scrollable box into the scroll pane
if (scrPane != null) { mainFrame.remove(scrPane); }
scrPane = new JScrollPane(subFrameBox);
scrPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// add to the scroll pane to the main frame and view it
mainFrame.add(scrPane, BorderLayout.CENTER);
//mainFrame.setVisible(true);
SwingUtilities.invokeLater(
new Runnable()
{
@Override
public void run() {
scrPane.getViewport().setViewPosition( new Point(0, 0) );
}
}
);
}
public void setSrcLabel(File s){
String p = s.getPath();
if (p.length()>45) p = "..."+p.substring(p.length()-45);
setSrcLabel("SRC>>"+p);
}
public void setSrcLabel(String s){
srcLabel = new JTextArea(s);
srcLabel.setFont(PATH_FONT);
srcLabel.setBackground(Color.WHITE);
srcLabel.setLineWrap(true);
srcLabel.setWrapStyleWord(false);
srcLabel.setEditable(false);
if (srcPath != null) srcLabel.setToolTipText(srcPath.getPath());
}
public void setGreenLabel(int num) {
greenLabel = new JTextArea(" "+num+" ");
greenLabel.setFont(PATH_FONT);
greenLabel.setBackground(GREEN);
greenLabel.setLineWrap(false);
greenLabel.setWrapStyleWord(false);
greenLabel.setEditable(false);
greenLabel.setToolTipText("Tests identified as matching.");
}
public void setYellowLabel(int num) {
yellowLabel = new JTextArea(" "+num+" ");
yellowLabel.setFont(PATH_FONT);
yellowLabel.setBackground(YELLOW);
yellowLabel.setLineWrap(false);
yellowLabel.setWrapStyleWord(false);
yellowLabel.setEditable(false);
yellowLabel.setToolTipText("Tests identified as spacing issues.");
}
public void setRedLabel(int num) {
redLabel = new JTextArea(" "+num+" ");
redLabel.setFont(PATH_FONT);
redLabel.setBackground(RED);
redLabel.setLineWrap(false);
redLabel.setWrapStyleWord(false);
redLabel.setEditable(false);
redLabel.setToolTipText("Tests identified as NOT matching.");
}
public void refreshStatPanel() {
statPanel.remove(greenLabel);
statPanel.remove(yellowLabel);
statPanel.remove(redLabel);
setGreenLabel(countGreen);
setYellowLabel(countYellow);
setRedLabel(countRed);
statPanel.add(greenLabel, BorderLayout.WEST);
statPanel.add(yellowLabel, BorderLayout.CENTER);
statPanel.add(redLabel, BorderLayout.EAST);
}
public void makeHeaderFrame(TestData td){
JPanel jp = new JPanel();
subFrameList.add(jp);
JTextArea textArea = new JTextArea("\n"+td.getHeader()+"\n");
textArea.setFont(HEADER_FONT);
textArea.setBackground(HEADER_BG_COLOR);
textArea.setColumns(td.getHeader().length());
textArea.setLineWrap(false);
textArea.setEditable(false);
jp.setBackground(HEADER_BG_COLOR);
jp.setBorder(BorderFactory.createLineBorder(new Color(0)));
jp.add(textArea,BorderLayout.CENTER);
}
public void makeMessageFrame(TestData td){
JPanel jp = new JPanel(new BorderLayout());
subFrameList.add(jp);
JPanel jpInner = new JPanel(new BorderLayout());
jpInner.setBorder(new EmptyBorder(5,15,5,5));
jpInner.setBackground(td.getResultColor());
JTextArea textArea = new JTextArea(td.getMessage());
textArea.setFont(MESSAGE_FONT);
textArea.setBackground(td.getResultColor());
if (td.getResultColor() == GREEN) countGreen++;
else if (td.getResultColor() == YELLOW) countYellow++;
else if (td.getResultColor() == RED) countRed++;
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
jp.setBackground(td.getResultColor());
jp.setBorder(BorderFactory.createLineBorder(new Color(0)));
jpInner.add(textArea,BorderLayout.CENTER);
jp.add(jpInner,BorderLayout.CENTER);
}
public void makeSrcButtonFrame(TestData td){
JPanel jp = new JPanel(new BorderLayout());
subFrameList.add(jp);
JPanel jpInner = new JPanel(new FlowLayout(FlowLayout.LEADING));
jpInner.setBorder(new EmptyBorder(0,15,0,5));
jpInner.setBackground(Color.WHITE);
JTextArea lbl = new JTextArea("Source Files: ");
lbl.setBackground(Color.WHITE);
jpInner.add(lbl);
String[] fileName = td.getSrcFiles();
int oldSize = srcButtonList.size();
for(int i = 0; i < fileName.length; i++) {
//Make button
//See if file exists. Disable button if file is missing.
File temp = null;
try {
temp = new File(srcPath + "/" + fileName[i]);
if (! temp.exists()) {
temp = new File(srcPath + "/" + fileName[i] + ".java");
}
if (! temp.exists()) temp = null;
}
catch (Exception e) { }
JButton newButton;
if (temp != null) {
newButton = new JButton(temp.getName());
} else {
newButton = new JButton(fileName[i]);
newButton.setEnabled(false);
}
srcButtonList.add(newButton);
}
for(int i = oldSize; i < srcButtonList.size(); i++){
final int index = i;
srcButtonList.get(index).addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e) {
SourceCodeFrame srcFrame = new SourceCodeFrame(srcPath + "/" + srcButtonList.get(index).getLabel());
}
}
);
jpInner.add(srcButtonList.get(index));
}
JScrollPane srcScrollable = new JScrollPane(jpInner,
JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
WheelScrolling.install(srcScrollable);
srcScrollable.setBorder(BorderFactory.createEmptyBorder());
jp.add(srcScrollable,BorderLayout.CENTER);
jp.setBorder(BorderFactory.createLineBorder(new Color(0)));
}
public JPanel getMethodCallPanel(TestData td) {
JPanel jp = new JPanel(new BorderLayout());
jp.setBackground(Color.WHITE);
jp.setBorder(BorderFactory.createTitledBorder("Invoking"));
JPanel jpInner = new JPanel(new BorderLayout());
jpInner.setBorder(new EmptyBorder(5,5,5,5));
jpInner.setBackground(Color.WHITE);
JTextArea textArea = new JTextArea(td.getMethodCall());
textArea.setFont(REGULAR_FONT);
textArea.setLineWrap(true);
textArea.setEditable(false);
jpInner.add(textArea,BorderLayout.CENTER);
jp.add(jpInner,BorderLayout.CENTER);
return jp;
}
public JPanel getResultPanel(TestData td) {
JPanel jp = new JPanel(new BorderLayout());
jp.setBackground(Color.WHITE);
jp.setBorder(BorderFactory.createTitledBorder("Result"));
JPanel jpInner = new JPanel(new BorderLayout());
jpInner.setBorder(new EmptyBorder(5,5,5,5));
jpInner.setBackground(Color.WHITE);
JTextArea textArea = new JTextArea(td.getResult());
textArea.setFont(REGULAR_FONT);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
if (td.getResultColor() != null) {
if (td.getResultColor() == GREEN) countGreen++;
else if (td.getResultColor() == YELLOW) countYellow++;
else if (td.getResultColor() == RED) countRed++;
textArea.setBackground(td.getResultColor());
textArea.setFont(textArea.getFont().deriveFont(Font.BOLD));
}
jpInner.add(textArea,BorderLayout.CENTER);
jp.add(jpInner,BorderLayout.CENTER);
return jp;
}
public JPanel getExpOutPanel(TestData td) {
JPanel jp = new JPanel(new BorderLayout());;
jp.setBackground(Color.WHITE);
jp.setBorder(BorderFactory.createTitledBorder("Expected Output/Return Value"));
JPanel jpInner = new JPanel(new BorderLayout());
jpInner.setBorder(new EmptyBorder(5,5,5,5));
jpInner.setBackground(Color.WHITE);
StyledDocument document = new DefaultStyledDocument();
SimpleAttributeSet attributes = new SimpleAttributeSet();
StyleConstants.setFontFamily(attributes, "Monospace");
attributes.addAttribute(StyleConstants.FontConstants.Family, Font.MONOSPACED);
attributes.addAttribute(StyleConstants.FontConstants.Size, 16);
try {
if (td.getExpectedOut() != null)
document.insertString(0, td.getExpectedOut() + "\n", attributes);
} catch (BadLocationException badLocationException) {
System.out.println("Unable to build expected output document.");
}
/* I CAN'T FIGURE OUT HOW TO SET THIS
textArea.setLineWrap(true);
*/
JTextPane textPane = new JTextPane(document);
textPane.setEditable(false);
jpInner.add(textPane,BorderLayout.CENTER);
jp.add(jpInner,BorderLayout.CENTER);
return jp;
}
public JPanel getActOutPanel(TestData td) {
JPanel jp = new JPanel(new BorderLayout());
jp.setBackground(Color.WHITE);
jp.setBorder(BorderFactory.createTitledBorder("Actual Output/Return Value"));
JPanel jpInner = new JPanel(new BorderLayout());
jpInner.setBorder(new EmptyBorder(5,5,5,5));
jpInner.setBackground(Color.WHITE);
StyledDocument document = new DefaultStyledDocument();
SimpleAttributeSet attributesNormal = new SimpleAttributeSet();
StyleConstants.setFontFamily(attributesNormal, "Monospace");
attributesNormal.addAttribute(StyleConstants.FontConstants.Family, Font.MONOSPACED);
attributesNormal.addAttribute(StyleConstants.FontConstants.Size, 16);
SimpleAttributeSet attributesMistake = (SimpleAttributeSet)(attributesNormal.clone());
attributesMistake.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.TRUE);
attributesMistake.addAttribute(StyleConstants.ColorConstants.Foreground, new Color(200, 0, 0));
String textToInsert = td.getActualOut();
if (textToInsert != null)
try {
int startLocation = textToInsert.indexOf(mistakeStartFlag);
int stopLocation = textToInsert.indexOf(mistakeStopFlag);
while (startLocation != -1 && stopLocation != -1) {
String good = textToInsert.substring(0, startLocation);
String mistake = textToInsert.substring(startLocation+mistakeStartFlag.length(), stopLocation);
textToInsert = textToInsert.substring(stopLocation+mistakeStopFlag.length()) ;
document.insertString(document.getLength(), good, attributesNormal);
document.insertString(document.getLength(), mistake, attributesMistake);
startLocation = textToInsert.indexOf(mistakeStartFlag);
stopLocation = textToInsert.indexOf(mistakeStopFlag);
}
//insert remaining text
document.insertString(document.getLength(), textToInsert + "\n", attributesNormal);
} catch (BadLocationException badLocationException) {
System.out.println("Unable to parse actual output for style document.");
}
JTextPane textPane = new JTextPane(document);
textPane.setEditable(false);
jpInner.add(textPane,BorderLayout.CENTER);
jp.add(jpInner,BorderLayout.CENTER);
return jp;
}
public void makeFourSubFrames(TestData td){
GridLayout myGL = new GridLayout(1,2);
myGL.setHgap(8);
EmptyBorder padding = new EmptyBorder(5,10,5,10);
JPanel jpOuter = new JPanel();
jpOuter.setLayout(new BoxLayout(jpOuter, BoxLayout.Y_AXIS));
JPanel jpTop = new JPanel(myGL);
JPanel jpBottom = new JPanel(myGL);
jpTop.setBackground(Color.WHITE);
jpBottom.setBackground(Color.WHITE);
jpTop.setBorder(padding);
jpBottom.setBorder(padding);
//4 panels
JPanel topLeft = new JPanel(new BorderLayout());
topLeft.add(getMethodCallPanel(td), BorderLayout.NORTH);
topLeft.setBackground(Color.WHITE);
JPanel topRight = new JPanel(new BorderLayout());
topRight.setBackground(Color.WHITE);
topRight.add(getResultPanel(td), BorderLayout.NORTH);
JScrollPane bottomLeftScrollable = new JScrollPane(getExpOutPanel(td),
JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
WheelScrolling.install(bottomLeftScrollable);
bottomLeftScrollable.setBorder(BorderFactory.createEmptyBorder());
JScrollPane bottomRightScrollable = new JScrollPane(getActOutPanel(td),
JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
WheelScrolling.install(bottomRightScrollable);
bottomRightScrollable.setBorder(BorderFactory.createEmptyBorder());
jpTop.add(topLeft);
jpTop.add(topRight);
jpBottom.add(bottomLeftScrollable);
jpBottom.add(bottomRightScrollable);
jpOuter.add(jpTop);
jpOuter.add(jpBottom);
jpOuter.setBackground(Color.WHITE);
jpOuter.setBorder(BorderFactory.createLineBorder(new Color(0)));
subFrameList.add(jpOuter);
}
public void makeTwoSubFrames(TestData td){
GridLayout myGL = new GridLayout(1,2);
myGL.setHgap(8);
EmptyBorder padding = new EmptyBorder(5,10,5,10);
JPanel jpOuter = new JPanel();
jpOuter.setLayout(new BoxLayout(jpOuter, BoxLayout.Y_AXIS));
JPanel jpTop = new JPanel(myGL);
jpTop.setBackground(Color.WHITE);
jpTop.setBorder(padding);
//2 panels
JPanel topLeft = new JPanel(new BorderLayout());
topLeft.add(getMethodCallPanel(td), BorderLayout.NORTH);
topLeft.setBackground(Color.WHITE);
JPanel topRight = new JPanel(new BorderLayout());
topRight.setBackground(Color.WHITE);
topRight.add(getResultPanel(td), BorderLayout.NORTH);
jpTop.add(topLeft);
jpTop.add(topRight);
jpOuter.add(jpTop);
jpOuter.setBackground(Color.WHITE);
jpOuter.setBorder(BorderFactory.createLineBorder(new Color(0)));
subFrameList.add(jpOuter);
}
/**
* ScrollablePanel is basically a JPanel that will properly resize when it contains a JScrollPane
*/
private static class ScrollablePanel extends JPanel implements Scrollable {
public Dimension getPreferredScrollableViewportSize() {
return super.getPreferredSize(); }
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return SCROLL_SPEED; }
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return SCROLL_SPEED; }
public boolean getScrollableTracksViewportWidth() {
return true; }
public boolean getScrollableTracksViewportHeight() {
return false; }
} //end Inner Class ScrollablePanel
/**
* A TestData object performs requested tests and stores the information collected during the test.
* All these TestData objects are loaded into a list of TestResults
* which is used to build the GUI's results scroll pane.
*/
static class TestData {
public static final double VERSION_NUM = V_NUM;
private static ByteArrayOutputStream baos = new ByteArrayOutputStream();
private static long timeOutSec = 2;
private String methodCall, result;
private String expectedOut, actualOut;
private Color resultColor;
private String header, message;
private String[] srcFiles;
public TestData() { }
public TestData(String s, boolean isHeader) {
if (isHeader) this.header = s;
else this.message = s;
}
public TestData(String methodCall, String result, String expectedOut, String actualOut) {
this(methodCall, result, expectedOut, actualOut, new Color(255, 255, 255));
}
public TestData(String methodCall, String result, String expectedOut, String actualOut, Color resultColor) {
//header and message remain null
this.methodCall = methodCall;
this.result = result;
this.expectedOut = expectedOut;
this.actualOut = actualOut;
this.resultColor = resultColor;
}
public TestData(String[] srcFiles){
this.srcFiles = srcFiles;
}
public static void setTimeOutSec(int sec) { timeOutSec = (long) sec; }
public void setColor(int r, int g, int b, int a) { resultColor = new Color(r, g, b, a); }
public void setColor(int r, int g, int b) { resultColor = new Color(r, g, b); }
public String getHeader() {
return header; }
public String getMessage() {
return message; }
public String getMethodCall() {
return methodCall; }
public String getResult() {
return result; }
public String getExpectedOut() {
return expectedOut; }
public String getActualOut() {
return actualOut; }
public Color getResultColor() {
return resultColor; }
public String[] getSrcFiles(){
return srcFiles;
}
public String setHeader(String header) {
this.header = header;
return header;
}
public String setMessage(String message) {
resultColor = MESSAGE_BG_COLOR;
return this.message = message;
}
public void setResultColorForMessage(boolean correct) {
if (correct) resultColor = GREEN;
else resultColor = RED;
}
public String setMethodCall(String methodCall) {
return this.methodCall = methodCall; }
public String setResult(String result) {
return this.result = result; }
public String setResult(String result, Color resultColor) {
this.resultColor = resultColor;
return this.result = result;
}
public String setExpectedOut(String expectedOut) {
this.expectedOut = expectedOut;
return expectedOut;
}
public String setActualOut(String actualOut) {
return this.actualOut = actualOut; }
public static void header(String name) {
testResults.add(new TestGUI.TestData(name, true));
}
public static void srcButton(String srcFileName) {
String[] fileNames = srcFileName.split(",");
for (int i = 0; i < fileNames.length; i++) fileNames[i] = fileNames[i].trim();
testResults.add(new TestGUI.TestData(fileNames));
}
public static void srcButton(String[] srcFileNames) {
testResults.add(new TestGUI.TestData(srcFileNames));
}
private static void messageAlert(String m) {
TestGUI.TestData newEntry = new TestGUI.TestData(m, false); //set message
newEntry.setResultColorForMessage(false); //red
testResults.add(0, newEntry);
}