-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCritterMain.java
More file actions
4744 lines (4129 loc) · 179 KB
/
CritterMain.java
File metadata and controls
4744 lines (4129 loc) · 179 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
// Critters
// Authors: Dat Ly, Marty Stepp, and Stuart Reges
//
// Provides the main method for the simulation.
//
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.geom.Rectangle2D;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessControlException;
import java.security.Permission;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.swing.BorderFactory;
import javax.swing.border.TitledBorder;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.Timer;
import javax.swing.UIManager;
public class CritterMain {
public static void main(String[] args) {
CritterGui.createGui();
}
}
// Marty's note to self: If you change the names of the animal classes assigned,
// make sure to update ClassUtils.java's getClasses method (lines 203-214)
// and CritterClassVerifier's CLASSES_TO_CHECK_METHODS array.
// Also update retro.txt before creating the sample solution file.
// Critters
// Authors: Marty Stepp, Stuart Reges
// The overall graphical user interface for the Critter simulation.
class CritterGui implements ActionListener, Observer, WindowListener {
// class constants
public static final String SAVE_STATE_FILE_NAME = "_critters_network_settings.txt";
public static final boolean PRINT_EXCEPTIONS = true;
public static final boolean SHOULD_SAVE_SETTINGS = true;
public static final boolean DEFAULT_NETWORK_ENABLED = false;
public static final boolean DEFAULT_DEBUG = false;
private static final String TITLE = "Critters";
private static final long serialVersionUID = 0;
private static final int DELAY = 100; // default MS between redraws
private static final int MAX_CLASS_NAME_LENGTH = 24;
public static final boolean SECURE = true; // use security manager?
// constants for saving/loading GUI state
private static final String LAST_HOST_NAME_KEY = "lastHostName";
private static final String FPS_KEY = "fps";
private static final String ACCEPT_KEY = "accept";
private static final String BACKGROUND_COLORS_KEY = "backgroundColors";
// private static final String DEBUG_KEY = "debug";
private static final String ALWAYS_VALUE = "always";
private static final String ASK_VALUE = "ask";
private static final String NEVER_VALUE = "never";
// constant for loading files from the course web site
// CS312 - THE NETWORK FEATURE IS NOT AVAILABLE
// DO NOT USE THE FOLLOWING STRINGS
public static final String ZIP_FILE_NAME = "huskies.zip";
public static final String ZIP_CODE_BASE = "http://webster.cs.washington.edu/facebook/critters/huskies/" + ZIP_FILE_NAME;
private static final Font STATUS_FONT = new Font("monospaced", Font.PLAIN, (int) (CritterPanel.FONT_SIZE / 1.2));
private static final Font CLASS_FONT = new Font("sansserif", Font.BOLD, (int) (CritterPanel.FONT_SIZE / 1.2));
static {
try {
// make the GUI look like your operating system
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
}
}
// This is basically the main method that makes the GUI and starts the program.
// I am "hiding" it here for student readability.
public static void createGui() {
CritterClassVerifier.checkForSillyMethods();
CritterGui gui = CritterClassVerifier.initialSettings();
if (gui == null) {
// user canceled
try {
System.exit(0);
} catch (Exception e) {
}
} else {
gui.start(); // run the GUI
}
}
// fields
private CritterModel model;
private CritterPanel panel;
private JFrame frame;
private JButton go, stop, tick, reset, loadFromWeb;
private JSlider slider;
private JComponent east;
private JRadioButton always, never, ask;
private String lastHostName = "";
private JLabel moves;
private JCheckBox backgroundColors;
private JCheckBox debug;
private boolean enableNetwork;
private boolean enableLoadFromWeb;
private boolean enableSendRequest;
// receives critters from others and lets me voluntarily send mine out
// packets = [hostname, classname, critter text]
private CritterNetworkManager networkSenderListener;
// lets me host my wolf so others can reach out and request it from me
// packets = [hostname, classname requested]
private CritterNetworkManager networkServer;
// keeps track of which classes already have a ClassPanel on the east side
// of the window, so we know when we need to add a new one (on network receive etc)
private Map<String, ClassPanel> counts;
// Constructs a new GUI to display the given model of critters.
public CritterGui(CritterModel model) {
this(model, false, false);
}
public CritterGui(CritterModel model, boolean network, boolean secure) {
this.model = model;
model.addObserver(this);
enableNetwork = enableLoadFromWeb = enableSendRequest = network;
// try to load settings from disk (fail silently)
Properties props = null;
if (SHOULD_SAVE_SETTINGS) {
try {
props = loadConfiguration();
} catch (IOException ioe) {
} catch (SecurityException ioe) {
// don't print security exceptions
}
}
// important not to store security manager anywhere as a field;
// prevent evil hands from getting a reference to it
final SecurityManager mgr = new CritterSecurityManager();
if (secure) {
try {
model.lock(mgr);
System.setSecurityManager(mgr);
} catch (SecurityException e) {}
}
// set up network listeners
networkSenderListener = new CritterNetworkManager();
networkSenderListener.getReceiveEvent().addObserver(this);
networkSenderListener.getErrorEvent().addObserver(this);
networkServer = new CritterNetworkManager(CritterNetworkManager.DEFAULT_PORT_2);
networkServer.getReceiveEvent().addObserver(this);
networkServer.getErrorEvent().addObserver(this);
// set up critter picture panel and set size
panel = new CritterPanel(model, true);
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
// add the animation timer
UberTimer timer = new UberTimer(mgr); //...;
timer.setCoalesce(true);
// east panel to store critter class info
counts = new TreeMap<String, ClassPanel>();
// east = new JPanel(new GridLayout(0, 1));
east = new JPanel();
east.setLayout(new BoxLayout(east, BoxLayout.Y_AXIS));
// FlowLayout wrapper so that ClassPanels aren't stretched vertically
JPanel eastWrapper = new JPanel();
eastWrapper.setLayout(new FlowLayout()); // new BoxLayout(eastWrapper, BoxLayout.Y_AXIS));
eastWrapper.add(east);
JScrollPane scrollPane = new JScrollPane(eastWrapper);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// east.setBorder(BorderFactory.createTitledBorder("Critter classes:"));
if (enableLoadFromWeb) {
loadFromWeb = GuiFactory.createButton("Load from Web...", 'L', this, east);
loadFromWeb.setAlignmentX(0.5f);
}
// timer controls
JPanel southcenter = new JPanel();
go = GuiFactory.createButton("Go", 'G', timer, southcenter);
go.setBackground(Color.GREEN);
stop = GuiFactory.createButton("Stop", 'S', timer, southcenter);
stop.setBackground(new Color(255, 96, 96));
tick = GuiFactory.createButton("Tick", 'T', timer, southcenter);
tick.setBackground(Color.YELLOW);
reset = GuiFactory.createButton("Reset", 'R', timer, southcenter);
go.addKeyListener(timer);
stop.addKeyListener(timer);
tick.addKeyListener(timer);
reset.addKeyListener(timer);
Container southCenterHolder = Box.createVerticalBox();
southCenterHolder.add(southcenter);
Container southCenterCheckboxArea = new JPanel();
backgroundColors = GuiFactory.createCheckBox("AdamSandler background colors", 'A', this, southCenterCheckboxArea);
backgroundColors.setAlignmentX(1.0f);
debug = GuiFactory.createCheckBox("Debug", 'D', timer, southCenterCheckboxArea);
debug.setAlignmentX(1.0f);
southCenterHolder.add(southCenterCheckboxArea);
// slider for animation speed
JPanel southwest = new JPanel();
southwest.add(new JLabel("Speed:"));
slider = GuiFactory.createSlider(1, 61, 1000 / DELAY, 20, 5, timer, southwest);
slider.addKeyListener(timer);
moves = new JLabel();
moves.setFont(STATUS_FONT);
setMovesText();
southwest.add(moves);
// checkbox
JPanel southeast = new JPanel(); // new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 5));
southeast.setBorder(BorderFactory.createTitledBorder("Accept requests:"));
ButtonGroup group = new ButtonGroup();
always = GuiFactory.createRadioButton("Always", 'A', false, group, this, southeast);
always.setToolTipText("When selected, automatically accepts critters sent to you "
+ "and automatically shares requested critters.");
ask = GuiFactory.createRadioButton("Ask", 'k', true, group, this, southeast);
ask.setToolTipText("When selected, prompts you when critters are sent to you "
+ "and when requested to share your critters.");
never = GuiFactory.createRadioButton("Never", 'N', false, group, this, southeast);
never.setToolTipText("When selected, never accepts critters sent to you "
+ "and refuses all requests to share your critters.");
// south panel to hold various widgets
Container south = new JPanel(new BorderLayout());
south.add(southCenterHolder);
south.add(southwest, BorderLayout.WEST);
if (enableSendRequest) {
south.add(southeast, BorderLayout.EAST);
} else {
south.add(Box.createHorizontalStrut(southwest.getPreferredSize().width), BorderLayout.EAST);
}
JPanel center = new JPanel();
center.add(panel);
// use saved settings, if any (fail silently)
if (props != null) {
try {
boolean battleMode = false;
try {
if (System.getProperty("critters.battlemode") != null) {
battleMode = true;
}
} catch (Exception e) {
battleMode = true;
}
enableNetwork = enableNetwork && !battleMode;
if (!battleMode) {
slider.setValue(Integer.parseInt(props.getProperty(FPS_KEY)));
}
String accept = props.getProperty(ACCEPT_KEY);
if (accept.equals(ALWAYS_VALUE)) {
always.setSelected(true);
} else if (accept.equals(NEVER_VALUE)) {
never.setSelected(true);
} else if (accept.equals(ASK_VALUE)) {
ask.setSelected(true);
}
backgroundColors.setSelected(battleMode || Boolean.parseBoolean(props.getProperty(BACKGROUND_COLORS_KEY, "true")));
// debug.setSelected(Boolean.parseBoolean(props.getProperty(DEBUG_KEY, "false")));
if (!battleMode && model.isDebug()) {
model.setDebug(false);
}
debug.setSelected(!battleMode && model.isDebug());
lastHostName = props.getProperty(LAST_HOST_NAME_KEY, "");
// timer.setDelay(Integer.parseInt(props.getProperty(FPS_KEY)));
} catch (Exception e) {}
}
// enable or disable background colors behind critters
panel.setBackgroundColors(backgroundColors.isSelected());
model.setDebug(debug.isSelected(), mgr);
// create frame and do layout
frame = new JFrame();
frame.addKeyListener(timer);
if (enableNetwork) {
frame.setTitle(TITLE);
NetworkManager.findIPAddress(new ActionListener() {
public void actionPerformed(ActionEvent event) {
frame.setTitle(TITLE + ": " + CritterNetworkManager.getHostName()
+ " " + CritterNetworkManager.getIpAddresses());
}
});
} else {
frame.setTitle(TITLE);
}
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(this);
// frame.setResizable(false);
frame.add(center, BorderLayout.CENTER);
frame.add(south, BorderLayout.SOUTH);
frame.add(scrollPane, BorderLayout.EAST);
GuiFactory.center(frame);
timer.doEnabling();
go.requestFocus();
}
// wrapped timer so that there is no reference to the SecurityManager
// and code to mutate the model
private class UberTimer extends Timer implements ActionListener, KeyListener, ChangeListener {
private static final long serialVersionUID = 0;
private SecurityManager mgr;
public UberTimer(SecurityManager mgr) {
super(DELAY, CritterGui.this);
this.removeActionListener(CritterGui.this);
this.addActionListener(this);
this.mgr = mgr;
}
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == go) {
this.start();
stop.requestFocus();
} else if (src == stop) {
this.stop();
go.requestFocus();
} else if (src == this || (src == tick && !this.isRunning())) {
try {
model.update(mgr);
} catch (CritterModel.BuggyCritterException ex) {
this.stop();
Throwable cause = ex.getCause();
cause.printStackTrace();
errorMessagePane("An error occurred while updating the simulator!\n"
+ ex.getMessage() + "\n"
+ cause + "\n\n"
+ "See the console for more details about the error.");
} catch (Throwable ex) {
this.stop();
ex.printStackTrace();
errorMessagePane("An error occurred while updating the simulator!\n"
+ ex + "\n\n"
+ "See the console for more details about the error.");
}
} else if (src == reset) {
try {
model.reset(mgr);
} catch (CritterModel.BuggyCritterException ex) {
this.stop();
Throwable cause = ex.getCause();
cause.printStackTrace();
errorMessagePane("An error occurred while resetting the simulator!\n"
+ ex.getMessage() + "\n"
+ cause + "\n\n"
+ "See the console for more details about the error.");
} catch (Throwable ex) {
ex.printStackTrace();
errorMessagePane("An error occurred while resetting the simulator!\n"
+ ex + "\n\n"
+ "See the console for more details about the error.");
}
} else if (src == debug) {
model.setDebug(debug.isSelected(), mgr);
setMovesText();
panel.repaint();
}
doEnabling();
}
// required method of interface KeyListener
public void keyPressed(KeyEvent e) {
if (e.isAltDown() && e.getKeyCode() == KeyEvent.VK_LEFT) {
int value = slider.getValue();
value = Math.max(value - slider.getMinorTickSpacing(), slider.getMinimum());
slider.setValue(value);
this.setDelay(1000 / value);
} else if (e.isAltDown() && e.getKeyCode() == KeyEvent.VK_RIGHT) {
int value = slider.getValue();
value = Math.min(value + slider.getMinorTickSpacing(), slider.getMaximum());
slider.setValue(value);
this.setDelay(1000 / value);
}
}
// required method of interface KeyListener
public void keyReleased(KeyEvent e) {}
// required method of interface KeyListener
public void keyTyped(KeyEvent e) {}
// Responds to change events on the slider.
public void stateChanged(ChangeEvent e) {
int fps = slider.getValue();
this.setDelay(1000 / fps);
// timer.setInitialDelay(1000 / fps);
// timer.restart();
}
// Sets which buttons can be clicked at any given moment.
private void doEnabling() {
go.setEnabled(!this.isRunning());
stop.setEnabled(this.isRunning());
tick.setEnabled(!this.isRunning());
reset.setEnabled(!this.isRunning());
}
}
// Responds to action events in the GUI.
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == loadFromWeb) {
Thread thread = new Thread(new ZipDownloader(ZIP_CODE_BASE, model,
frame, loadFromWeb));
thread.start();
} else if (src == backgroundColors) {
panel.setBackgroundColors(backgroundColors.isSelected());
panel.repaint();
for (ClassPanel cpanel : counts.values()) {
cpanel.updateBorder();
cpanel.updateBackground();
}
}
}
// Starts the simulation. Assumes all critters have already been added.
public void start() {
setCounts();
// frame.pack();
GuiFactory.center(frame);
frame.setVisible(true);
// start network listeners
try {
if (enableNetwork) {
networkSenderListener.start();
networkServer.start();
}
} catch (java.net.BindException e) {
errorMessagePane("Error: The network is already in use.\n\n"
+ "If you want to be able to send and receive critters over the network,\n"
+ "please close all instances of the Critters GUI and run it again.",
"Network in use");
} catch (IOException e) {
errorMessagePane("Error starting network listener:\n" + e, "Network error");
if (PRINT_EXCEPTIONS) {
e.printStackTrace();
}
}
frame.toFront();
}
// Responds to Observable updates in the model.
public void update(Observable o, Object arg) {
if (o == model) {
// model is notifying us of an update
if (arg == CritterModel.Event.ADD
|| arg == CritterModel.Event.REMOVE_ALL
|| arg == CritterModel.Event.UPDATE
|| arg == CritterModel.Event.RESET) {
updateCounts();
setMovesText();
}
// TODO: remove overall gui as observer of model?
} else if (o == networkSenderListener.getReceiveEvent() && arg != null) {
// we received a message (a class to load)
if (never.isSelected()) {
return;
}
String[] strings = (String[]) arg;
loadClassText(strings);
// setCounts();
} else if (o == networkServer.getReceiveEvent() && arg != null) {
// we received a message (a request to send our wolf)
if (never.isSelected()) {
// refuse all requests
return;
}
String[] strings = (String[]) arg;
String hostName = strings[0];
String className = strings[1];
if (ask.isSelected()) {
// "Always Accept" not checked, so ask to confirm
int choice = JOptionPane
.showConfirmDialog(frame, "Host \"" + hostName
+ "\" requests your " + className
+ " class. Send it?", "Critter send request",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (choice != JOptionPane.YES_OPTION) {
// refuse request (send back a null answer)
sendJavaFile(null, hostName);
return;
}
}
// user confirmed, so send the class data
sendJavaFile(className, hostName);
} else if (o == networkSenderListener.getErrorEvent()
|| o == networkServer.getErrorEvent()) {
// something failed in a network send/receive attempt
if (!this.frame.isVisible()) {
// closing down the program; don't bother to show this error
return;
}
Exception e = (Exception) arg;
String message;
if (e instanceof UnknownHostException) {
message = "Cannot reach target computer:\n\n" + e;
} else if (e instanceof ConnectException) {
message = "Target computer refused connection:\n\n" + e;
} else if (e instanceof IOException) {
message = "I/O error:\n" + e;
} else {
message = e.toString();
}
try {
errorMessagePane(message, "network error");
} catch (RuntimeException re) {}
}
}
// Called when the window is about to close.
// Used to save the GUI's settings.
public void windowClosing(WindowEvent e) {
if (SHOULD_SAVE_SETTINGS) {
try {
networkServer.stop();
networkSenderListener.stop();
saveConfiguration();
} catch (SecurityException sex) {
// don't print applet security exceptions
} catch (Exception ex) {
if (PRINT_EXCEPTIONS) {
ex.printStackTrace();
}
}
}
try {
System.exit(0);
} catch (Exception ex) {
}
}
// Required to implement WindowListener interface.
public void windowActivated(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
private void errorMessagePane(String message) {
errorMessagePane(message, "An error has occurred!");
}
private void errorMessagePane(String message, String title) {
JOptionPane.showMessageDialog(frame, message, title, JOptionPane.ERROR_MESSAGE);
}
// Helper method to read an integer input from a set of choices.
private int getInput(String message, Object defaultValue, Object... choices) {
Object countStr = JOptionPane.showInputDialog(frame, message,
"Question", JOptionPane.QUESTION_MESSAGE, null, choices,
defaultValue);
if (countStr == null) {
return -1;
}
try {
return Integer.parseInt(countStr.toString());
} catch (NumberFormatException e) {
return -1;
}
}
// Helper method to read a String input (with the given initial String in the field)
// and return a default value if an empty string is entered.
private String getInput(String message, String initialValue,
String defaultValue) {
String input = (String) JOptionPane.showInputDialog(frame, message,
"Question", JOptionPane.QUESTION_MESSAGE, null, null,
initialValue);
if (input != null && input.length() == 0) {
input = defaultValue;
}
return input;
}
/*
// Loads a class received over the network.
// The given array contains [host name, class name, encoded base64 classfile text]
@SuppressWarnings("unchecked")
private void loadClassEncoded(String[] strings) {
String hostName = strings[0];
String className = strings[1];
String encodedFileText = strings[2];
if (encodedFileText == null) {
// they refused our request and sent back a null
JOptionPane.showMessageDialog(frame, hostName + " refused the request.",
"Request refused", JOptionPane.ERROR_MESSAGE);
return;
}
// find out how many critters to add to the world
int count = DEFAULT_NUMBER_OF_CRITTERS;
if (ask.isSelected()) {
count = getInput("Received " + className + " from host \"" + hostName +
"\".\nHow many to add? (Or Cancel to refuse this class)",
DEFAULT_NUMBER_OF_CRITTERS,
0, 1, 25, 50, 100);
if (count < 0) {
return;
}
}
// try to compile and load the received class, add it to simulation
try {
Class<? extends Critter> critterClass = (Class<? extends Critter>) ClassUtils
.writeAndLoadEncodedClass(encodedFileText, className);
model.add(count, critterClass);
} catch (CritterModel.TooManyCrittersException e) {
JOptionPane.showMessageDialog(frame,
"Error: Not enough room to add all critters",
"Too many critters", JOptionPane.ERROR_MESSAGE);
} catch (CritterModel.InvalidCritterClassException e) {
JOptionPane.showMessageDialog(frame,
"Problem with critter class:\n" + e + "\n\n" +
"This is probably DrJava's fault; DrJava has some issues with dynamically loading code over the network.\n" +
"If you've got a " + className + ClassUtils.CLASS_EXTENSION + " file in your program's folder, the file got to you successfully, but\n" +
"DrJava wasn't able to load it into the simulator.\n\n" +
"Try closing and re-running the simulator; this will give DrJava a chance to see the new animal type and load it.\n" +
"Hopefully, when you re-run the simulator, the " + className + " type will appear.",
"Problem with critter class",
JOptionPane.ERROR_MESSAGE);
} catch (ClassNotFoundException cnfe) {
JOptionPane.showMessageDialog(frame, "Error loading class:\n" + cnfe, "Error",
JOptionPane.ERROR_MESSAGE);
cnfe.printStackTrace();
} catch (IOException ioe) {
JOptionPane.showMessageDialog(frame, "Error loading class:\n" + ioe, "Error",
JOptionPane.ERROR_MESSAGE);
ioe.printStackTrace();
}
}
*/
// Loads a class received over the network.
// The given array contains [host name, class name, class text]
@SuppressWarnings("unchecked")
private void loadClassText(String[] strings) {
String hostName = strings[0];
String className = strings[1];
String fileText = strings[2];
if (fileText == null) {
// they refused our request and sent back a null
errorMessagePane(hostName + " refused the request.", "Request refused");
return;
}
// find out how many critters to add to the world
int count = CritterModel.DEFAULT_CRITTER_COUNT;
if (ask.isSelected()) {
count = getInput("Received " + className + " from host \""
+ hostName
+ "\".\nHow many to add? (Or Cancel to refuse this class)",
CritterModel.DEFAULT_CRITTER_COUNT, 0, 1, 25, 50, 100);
if (count < 0) {
return;
}
}
// try to compile and load the received class, add it to simulation
try {
Class<? extends Critter> critterClass = (Class<? extends Critter>) ClassUtils
.writeAndLoadClass(fileText, className, true);
model.add(count, critterClass);
} catch (CritterModel.TooManyCrittersException e) {
errorMessagePane("Error: Not enough room to add all critters", "Too many critters");
} catch (CritterModel.InvalidCritterClassException e) {
if (ClassUtils.isDrJavasFault(className)) {
errorMessagePane(className + " received; simulator must be restarted.\n"
+ "Try closing the GUI and re-running CritterMain.", "Restart required");
} else {
errorMessagePane("Problem with critter class:\n"
+ e + "\n\n"
+ "This is probably DrJava's fault; DrJava has some issues with dynamically loading code over the network.\n"
+ "If you've got a " + className + ClassUtils.CLASS_EXTENSION
+ " file in your program's folder, the file got to you successfully, but\n"
+ "DrJava wasn't able to load it into the simulator.\n\n"
+ "Try closing and re-running the simulator; this will give DrJava a chance to see the new animal type and load it.\n"
+ "Hopefully, when you re-run the simulator, the "
+ className + " type will appear.",
"Problem with critter class");
if (PRINT_EXCEPTIONS) {
e.printStackTrace();
}
}
} catch (ClassNotFoundException e) {
errorMessagePane("Unable to find the Java compiler.\n"
+ "If you aren't using DrJava or jGRASP, try running the simulator from there.");
if (PRINT_EXCEPTIONS) {
e.printStackTrace();
}
} catch (Exception e) {
errorMessagePane("Error loading class:\n" + e);
if (PRINT_EXCEPTIONS) {
e.printStackTrace();
}
}
}
private Properties loadConfiguration() throws IOException {
Properties prop = new Properties();
prop.load(new FileInputStream(SAVE_STATE_FILE_NAME));
return prop;
}
private void saveConfiguration() throws IOException {
Properties prop = new Properties();
int fps = slider.getValue();
prop.setProperty(LAST_HOST_NAME_KEY, lastHostName);
prop.setProperty(FPS_KEY, String.valueOf(fps));
if (always.isSelected()) {
prop.setProperty(ACCEPT_KEY, ALWAYS_VALUE);
} else if (ask.isSelected()) {
prop.setProperty(ACCEPT_KEY, ASK_VALUE);
} else if (never.isSelected()) {
prop.setProperty(ACCEPT_KEY, NEVER_VALUE);
}
prop.setProperty(BACKGROUND_COLORS_KEY, String.valueOf(backgroundColors.isSelected()));
// prop.setProperty(DEBUG_KEY, String.valueOf(debug.isSelected()));
prop.store(new PrintStream(SAVE_STATE_FILE_NAME), "CSE 142 Critters saved network settings");
}
/*
// sends the given class code to the given host computer
// if className is null, sends null text to signify request refused
private void sendClassFile(String className, String hostName) {
try {
String encodedFileText = null;
String newClassName = className;
if (className != null) {
// new class name = old one + current user name?
// e.g. "Wolf" --> "Wolf_Stepp"
String userName = System.getProperty("user.name");
if (userName.length() > 0) {
userName = userName.substring(0, 1).toUpperCase() + userName.substring(1).toLowerCase();
}
newClassName += "_" + userName;
encodedFileText = ClassUtils.renameCompileEncode(className, newClassName);
}
networkSenderListener.sendText(hostName, newClassName, encodedFileText);
} catch (IOException e) {
JOptionPane.showMessageDialog(frame,
"Error reading file:\n" + e, "I/O Error",
JOptionPane.ERROR_MESSAGE);
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(frame,
"Error preparing class to send:\n" + e, "Class Error",
JOptionPane.ERROR_MESSAGE);
}
}
*/
// sends the given class code to the given host computer
// if className is null, sends null text to signify request refused
private void sendJavaFile(String className, String hostName) {
try {
String fileText = null;
String newClassName = className;
if (className != null) {
// new class name = old one + current user name?
// e.g. "Wolf" --> "Wolf_Stepp"
String userName = System.getProperty("user.name");
if (userName.length() > 0) {
userName = userName.substring(0, 1).toUpperCase()
+ userName.substring(1).toLowerCase();
}
newClassName += "_" + userName;
// rename and read
fileText = ClassUtils.readAndRename(className, newClassName);
}
networkSenderListener.sendText(hostName, newClassName, fileText);
} catch (IOException ioe) {
errorMessagePane("Error reading file:\n" + ioe, "I/O Error");
}
}
// Adds right-hand column of labels showing how many of each type are alive.
// Updates the counter labels to store the current count information.
private void setCounts() {
Set<String> classNames = model.getClassNames();
if (classNames.size() > 0 && classNames.size() == counts.size()) {
return; // nothing to do
}
for (ClassPanel cpanel : counts.values()) {
east.remove(cpanel);
}
counts.clear();
panel.ensureAllColors();
boolean packed = false;
int count = 0;
for (String className : classNames) {
ClassPanel cpanel = new ClassPanel(className);
east.add(cpanel);
counts.put(className, cpanel);
if (!packed && count >= 3) {
east.validate();
frame.pack();
frame.setSize(frame.getWidth() + 20, frame.getHeight());
packed = true;
}
}
if (!packed) {
east.validate();
frame.pack();
// buffer because for some reason Swing underestimates east's width
frame.setSize(frame.getWidth() + 20, frame.getHeight());
packed = true;
}
east.validate();
go.requestFocus();
}
private void setMovesText() {
String movesText = "<html>" + Util.padNumber(model.getMoveCount(), 6, true) + " moves<br>\n";
if (model.isDebug()) {
movesText += "(" + (model.getPartialIndex() + 1) + "/" + model.getTotalCritterCount() + ")";
} else {
movesText += " ";
}
movesText += "</html>";
moves.setText(movesText);
}
// Adds right-hand column of labels showing how many of each type are alive.
// Updates the counter labels to store the current count information.
private void updateCounts() {
// if list of classes is out of date, may need to update east panel
Set<String> classNames = model.getClassNames();
if (classNames.size() != counts.size()) {
setCounts();
return;
}
for (String className : classNames) {
if (!counts.containsKey(className)) {
setCounts();
return;
}
}
panel.ensureAllColors();