Revision: 19515
http://sourceforge.net/p/gate/code/19515
Author: markagreenwood
Date: 2016-08-19 10:39:39 +0000 (Fri, 19 Aug 2016)
Log Message:
-----------
code cleanup and sorted some findbugs issues
Modified Paths:
--------------
gate/branches/sawdust2/plugins/Developer_Tools/pom.xml
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/EDTMonitor.java
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/HeapDumper.java
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/Log4JALL.java
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/TheDuplicator.java
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/UnusedPluginUnloader.java
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/org/jdesktop/swinghelper/debug/CheckThreadViolationRepaintManager.java
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/org/jdesktop/swinghelper/debug/EventDispatchThreadHangMonitor.java
Modified: gate/branches/sawdust2/plugins/Developer_Tools/pom.xml
===================================================================
--- gate/branches/sawdust2/plugins/Developer_Tools/pom.xml 2016-08-19
10:17:23 UTC (rev 19514)
+++ gate/branches/sawdust2/plugins/Developer_Tools/pom.xml 2016-08-19
10:39:39 UTC (rev 19515)
@@ -9,7 +9,6 @@
<artifactId>base-plugin</artifactId>
<!-- this should be the version of GATE you wish to build
against -->
<version>9.0-SNAPSHOT</version>
- <relativePath>../../build/Plugin_Base</relativePath>
</parent>
<!-- this is the description of this plugin -->
Modified:
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/EDTMonitor.java
===================================================================
---
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/EDTMonitor.java
2016-08-19 10:17:23 UTC (rev 19514)
+++
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/EDTMonitor.java
2016-08-19 10:39:39 UTC (rev 19515)
@@ -28,11 +28,9 @@
@Override
public Resource init() throws ResourceInstantiationException {
RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
-
// These actually seems to cause things to hang sometimes so don't use it
// until we have figured out why
// EventDispatchThreadHangMonitor.initMonitoring();
-
return this;
}
}
Modified:
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/HeapDumper.java
===================================================================
---
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/HeapDumper.java
2016-08-19 10:17:23 UTC (rev 19514)
+++
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/HeapDumper.java
2016-08-19 10:39:39 UTC (rev 19515)
@@ -36,9 +36,9 @@
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
-@SuppressWarnings("serial")
@CreoleResource(tool = true, isPrivate = true, autoinstances = @AutoInstance,
name = "Java Heap Dumper", helpURL =
"http://gate.ac.uk/userguide/sec:misc-creole:dev-tools", comment = "Dumps the
Java heap to the specified file")
public class HeapDumper extends AbstractResource implements ActionsPublisher {
+ private static final long serialVersionUID = 5742636053440982835L;
// the cached set of actions so we don't have to keep creating them
private List<Action> actions = null;
@@ -48,95 +48,91 @@
// a handle to the method we'll use for doing the heap dump
private static volatile Method dumper = null;
-
static {
synchronized(HeapDumper.class) {
try {
- // This is complicated by the fact that the class we want might not
- // exist as it's an internal sun class so we have to do everything by
- // reflection so that the rest of the plugin loads normally even if we
+ // This is complicated by the fact that the class we want might
+ // not
+ // exist as it's an internal sun class so we have to do
+ // everything by
+ // reflection so that the rest of the plugin loads normally even
+ // if we
// abort this tool
-
// Get the management bean server
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
-
// get a handle to the HotSpot management bean
hotspot =
- ManagementFactory.newPlatformMXBeanProxy(
- server,
- "com.sun.management:type=HotSpotDiagnostic",
- HeapDumper.class.getClassLoader().loadClass(
- "com.sun.management.HotSpotDiagnosticMXBean"));
-
+ ManagementFactory.newPlatformMXBeanProxy(
+ server,
+ "com.sun.management:type=HotSpotDiagnostic",
+ HeapDumper.class.getClassLoader().loadClass(
+ "com.sun.management.HotSpotDiagnosticMXBean"));
// get the dumpHeap method from the HotSpot bean
dumper =
- hotspot.getClass().getMethod("dumpHeap", String.class,
boolean.class);
-
- } catch(Exception e) {
- // for now we just swallow any problems and don't add the menu item
+ hotspot.getClass().getMethod("dumpHeap", String.class,
+ boolean.class);
+ } catch(ClassNotFoundException | IOException | NoSuchMethodException
+ | SecurityException e) {
+ // for now we just swallow any problems and don't add the menu
+ // item
}
}
}
@Override
public List<Action> getActions() {
-
if(actions == null) {
// let's build the actions list...
-
// create an empty list
actions = new ArrayList<Action>();
-
if(isHotSpotAvailable()) {
- // only if the HotSpot JVM is available do we add the menu item...
-
+ // only if the HotSpot JVM is available do we add the menu
+ // item...
actions.add(new AbstractAction("Dump Java Heap...", new HeapDumpIcon(
- 24, 24)) {
+ 24, 24)) {
+ private static final long serialVersionUID = -8104408765275754233L;
@Override
public void actionPerformed(ActionEvent e) {
- // show the file chooser so the user can say where to save the file
+ // show the file chooser so the user can say where to
+ // save the file
XJFileChooser fileChooser = MainFrame.getFileChooser();
ExtensionFileFilter filter =
- new ExtensionFileFilter("Java Heap Dump (*.hprof)", "hprof");
-
+ new ExtensionFileFilter("Java Heap Dump (*.hprof)", "hprof");
fileChooser.resetChoosableFileFilters();
- fileChooser.setAcceptAllFileFilterUsed(true);
+ fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.addChoosableFileFilter(filter);
fileChooser.setFileFilter(filter);
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setDialogTitle("Java Heap Dump Generator");
-
// if the user canceled then just return
if(fileChooser.showSaveDialog(MainFrame.getInstance()) !=
JFileChooser.APPROVE_OPTION)
return;
-
// get the file to dump into
final File selectedFile = fileChooser.getSelectedFile();
-
- // if the file is null then something weird happened with the
+ // if the file is null then something weird happened
+ // with the
// chooser so just quit
if(selectedFile == null) return;
-
- // the method we are using fails if the file already exists so try
+ // the method we are using fails if the file already
+ // exists so try
// deleting it and quit if we can't
if(selectedFile.exists() && !selectedFile.delete()) {
JOptionPane.showMessageDialog(MainFrame.getInstance(),
- "Unable to delete existing heap file",
- "Java Heap Dump Generator", JOptionPane.ERROR_MESSAGE);
+ "Unable to delete existing heap file",
+ "Java Heap Dump Generator", JOptionPane.ERROR_MESSAGE);
}
-
- // dumping the heap can take a while so we want to do it separate
+ // dumping the heap can take a while so we want to do it
+ // separate
// from the EDT so we do it from a new thread
Runnable runableAction = new Runnable() {
@Override
public void run() {
-
- // stop anyone doing anything else while we are dumping the
heap
+ // stop anyone doing anything else while we are
+ // dumping the heap
// by locking the GUI
MainFrame.lockGUI("Dumping Heap...");
-
try {
// try and dump the heap
dumpHeap(selectedFile);
@@ -153,17 +149,14 @@
}
}
};
-
// run the thread we just built
Thread thread = new Thread(runableAction, "Heap Dumper");
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
-
});
}
}
-
return actions;
}
@@ -178,10 +171,8 @@
* while storing the heap
*/
public static void dumpHeap(File file) throws IOException {
-
if(!isHotSpotAvailable())
throw new IOException("Unable to access HotSpot to dump heap");
-
try {
dumper.invoke(hotspot, file.getAbsolutePath(), false);
} catch(Exception e) {
Modified:
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/Log4JALL.java
===================================================================
---
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/Log4JALL.java
2016-08-19 10:17:23 UTC (rev 19514)
+++
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/Log4JALL.java
2016-08-19 10:39:39 UTC (rev 19515)
@@ -31,61 +31,51 @@
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
-@SuppressWarnings("serial")
@CreoleResource(tool = true, isPrivate = true, autoinstances = @AutoInstance,
name = "Log4J Level: ALL", helpURL =
"http://gate.ac.uk/userguide/sec:misc-creole:dev-tools", comment = "Allows the
Log4J log level to be set to ALL from within the GUI")
public class Log4JALL extends AbstractResource implements ActionsPublisher {
+ private static final long serialVersionUID = -5305615531871359891L;
// the cached set of actions so we don't have to keep creating them
private List<Action> actions = null;
@Override
public List<Action> getActions() {
-
// if we have already built the action list then just return it
if(actions != null) return actions;
-
// create the empty actions list
actions = new ArrayList<Action>();
+ actions
+ .add(new AbstractAction("Log4J Level: ALL", new Log4JALLIcon(24, 24)) {
+ private static final long serialVersionUID = -1558851716974359770L;
- actions.add(new AbstractAction("Log4J Level: ALL", new Log4JALLIcon(
- 24, 24)) {
-
- @Override
- public void actionPerformed(ActionEvent e) {
-
- // for convenience get a handle on the root logger
- Logger rootLogger = Logger.getRootLogger();
-
- // set the log level to ALL on the top level repository
- rootLogger.getLoggerRepository().setThreshold(Level.ALL);
-
- @SuppressWarnings("unchecked")
- Enumeration<Logger> loggers =
- rootLogger.getLoggerRepository().getCurrentLoggers();
- while(loggers.hasMoreElements()) {
- // for each logger...
- Logger logger = loggers.nextElement();
-
- // if the log level is set, re-set it to ALL
- if(logger.getLevel() != null) logger.setLevel(Level.ALL);
- }
-
- @SuppressWarnings("unchecked")
- Enumeration<Appender> appenders = rootLogger.getAllAppenders();
- while(appenders.hasMoreElements()) {
- // for each appender...
- Appender appender = appenders.nextElement();
-
- if(appender instanceof AppenderSkeleton) {
- // try and set the output threshold to ALL
- ((AppenderSkeleton)appender).setThreshold(Level.ALL);
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ // for convenience get a handle on the root logger
+ Logger rootLogger = Logger.getRootLogger();
+ // set the log level to ALL on the top level repository
+ rootLogger.getLoggerRepository().setThreshold(Level.ALL);
+ @SuppressWarnings("unchecked")
+ Enumeration<Logger> loggers =
+ rootLogger.getLoggerRepository().getCurrentLoggers();
+ while(loggers.hasMoreElements()) {
+ // for each logger...
+ Logger logger = loggers.nextElement();
+ // if the log level is set, re-set it to ALL
+ if(logger.getLevel() != null) logger.setLevel(Level.ALL);
+ }
+ @SuppressWarnings("unchecked")
+ Enumeration<Appender> appenders = rootLogger.getAllAppenders();
+ while(appenders.hasMoreElements()) {
+ // for each appender...
+ Appender appender = appenders.nextElement();
+ if(appender instanceof AppenderSkeleton) {
+ // try and set the output threshold to ALL
+ ((AppenderSkeleton)appender).setThreshold(Level.ALL);
+ }
+ }
}
- }
- }
-
- });
-
- //return the list of actions
+ });
+ // return the list of actions
return actions;
}
}
Modified:
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/TheDuplicator.java
===================================================================
---
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/TheDuplicator.java
2016-08-19 10:17:23 UTC (rev 19514)
+++
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/TheDuplicator.java
2016-08-19 10:39:39 UTC (rev 19515)
@@ -33,22 +33,20 @@
@SuppressWarnings("serial")
@CreoleResource(tool = true, isPrivate = true, autoinstances = @AutoInstance,
name = "The Duplicator", helpURL =
"http://gate.ac.uk/userguide/sec:misc-creole:dev-tools", comment = "Duplicate
any resource with a right click menu option")
public class TheDuplicator extends ResourceHelper {
-
@Override
protected List<Action> buildActions(final NameBearerHandle handle) {
final MainFrame mf = MainFrame.getInstance();
int height =
mf.getFontMetrics(UIManager.getFont("MenuItem.font")).getHeight();
List<Action> rightClick = new ArrayList<Action>();
- rightClick.add(new AbstractAction("Duplicate" , new
TheDuplicatorIcon(height,height)
- ) {
+ rightClick.add(new AbstractAction("Duplicate", new TheDuplicatorIcon(
+ height, height)) {
@Override
public void actionPerformed(ActionEvent e) {
try {
Resource r = (Resource)handle.getTarget();
Factory.duplicate(r);
- }
- catch (Exception ex) {
+ } catch(Exception ex) {
ex.printStackTrace();
}
}
Modified:
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/UnusedPluginUnloader.java
===================================================================
---
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/UnusedPluginUnloader.java
2016-08-19 10:17:23 UTC (rev 19514)
+++
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/gate/creole/UnusedPluginUnloader.java
2016-08-19 10:39:39 UTC (rev 19515)
@@ -40,56 +40,46 @@
* @author Johann Petrak
* @author Mark A. Greenwood
*/
-@SuppressWarnings("serial")
@CreoleResource(tool = true, isPrivate = true, autoinstances = @AutoInstance,
name = "Unload Unused Plugins", helpURL =
"http://gate.ac.uk/userguide/sec:misc-creole:dev-tools", comment = "Unloads all
plugins for which we cannot find any loaded instances")
public class UnusedPluginUnloader extends AbstractResource implements
- ActionsPublisher {
+ ActionsPublisher {
+ private static final long serialVersionUID = 8302662658331004851L;
// the cached set of actions so we don't have to keep creating them
private List<Action> actions;
@Override
public List<Action> getActions() {
-
// if we have already built the action list then just return it
if(actions != null) return actions;
-
// create the empty actions list
actions = new ArrayList<Action>();
-
// we need access to the hidden instances as well and we can only do this
// through the impl so of something weird is going on and we have a
// different CreoleRegister than we expect then don't add the menu item
if(!(Gate.getCreoleRegister() instanceof CreoleRegisterImpl))
return actions;
-
actions.add(new AbstractAction("Unload Unused Plugins",
- new PluginUnloaderIcon(24, 24)) {
+ new PluginUnloaderIcon(24, 24)) {
+ private static final long serialVersionUID = -6919800157605929638L;
@Override
public void actionPerformed(ActionEvent e) {
-
// get a handle to the Creole register implementation
CreoleRegisterImpl reg = (CreoleRegisterImpl)Gate.getCreoleRegister();
-
// this will hold the set of plugins that are to be unloaded
Set<Plugin> pluginsToUnload = new HashSet<Plugin>();
-
for(Plugin plugin : reg.getPlugins()) {
// for each registered plugin...
-
// assume the plugin is unused
boolean unused = true;
-
// get the plugin nifo
for(ResourceInfo rInfo : plugin.getResourceInfoList()) {
// for each Resource the plugin defines...
-
try {
// get the instances of the resource
List<Resource> loaded =
- reg.getAllInstances(rInfo.getResourceClassName(), true);
-
+ reg.getAllInstances(rInfo.getResourceClassName(), true);
if(!loaded.isEmpty()) {
// if there are any instances then the plugin is in use
unused = false;
@@ -99,13 +89,11 @@
// ignore this, in the worst case we won't unload this plugin ...
}
}
-
// if we went through all the Resources and there aren't instances of
// any of them then the plugin is not in use and can be unloaded
if(unused) pluginsToUnload.add(plugin);
}
-
- //TODO replace this with a GUI to give users some control
+ // TODO replace this with a GUI to give users some control
if(pluginsToUnload.isEmpty()) {
System.out.println("No plugin unloaded");
} else {
@@ -113,17 +101,16 @@
// The system logs plugins getting unloaded, so we do not have to
do
// it
System.out.println("Trying to unload plugin: " + plugin);
- reg.unregisterPlugin(plugin);
+ reg.unregisterPlugin(plugin);
}
System.out.println("Plugins unloaded: " + pluginsToUnload.size());
System.out.println("\nPlugins still loaded:");
for(URL plugin : reg.getDirectories()) {
System.out.println(" " + plugin);
}
- }
+ }
}
});
-
// return the list of actions
return actions;
}
Modified:
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/org/jdesktop/swinghelper/debug/CheckThreadViolationRepaintManager.java
===================================================================
---
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/org/jdesktop/swinghelper/debug/CheckThreadViolationRepaintManager.java
2016-08-19 10:17:23 UTC (rev 19514)
+++
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/org/jdesktop/swinghelper/debug/CheckThreadViolationRepaintManager.java
2016-08-19 10:39:39 UTC (rev 19515)
@@ -17,10 +17,7 @@
import java.lang.ref.WeakReference;
-import javax.swing.JButton;
import javax.swing.JComponent;
-import javax.swing.JEditorPane;
-import javax.swing.JFrame;
import javax.swing.RepaintManager;
import javax.swing.SwingUtilities;
@@ -115,61 +112,4 @@
System.out.println("\tat " + st);
}
}
-
- public static void main(String[] args) throws Exception {
- // set CheckThreadViolationRepaintManager
- RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
- // Valid code
- SwingUtilities.invokeAndWait(new Runnable() {
- public void run() {
- test();
- }
- });
- System.out.println("Valid code passed...");
- repaintTest();
- System.out.println("Repaint test - correct code");
- // Invalide code (stack trace expected)
- test();
- }
-
- static void test() {
- JFrame frame = new JFrame("Am I on EDT?");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.add(new JButton("JButton"));
- frame.pack();
- frame.setVisible(true);
- frame.dispose();
- }
-
- // this test must pass
- static void imageUpdateTest() {
- JFrame frame = new JFrame();
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- JEditorPane editor = new JEditorPane();
- frame.setContentPane(editor);
- editor.setContentType("text/html");
- // it works with no valid image as well
- editor.setText("<html><img src=\"file:\\lala.png\"></html>");
- frame.setSize(300, 200);
- frame.setVisible(true);
- }
-
- private static JButton test;
-
- static void repaintTest() {
- try {
- SwingUtilities.invokeAndWait(new Runnable() {
- public void run() {
- test = new JButton();
- test.setSize(100, 100);
- }
- });
- } catch(Exception e) {
- e.printStackTrace();
- }
- // repaint(Rectangle) should be ok
- test.repaint(test.getBounds());
- test.repaint(0, 0, 100, 100);
- test.repaint();
- }
}
\ No newline at end of file
Modified:
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/org/jdesktop/swinghelper/debug/EventDispatchThreadHangMonitor.java
===================================================================
---
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/org/jdesktop/swinghelper/debug/EventDispatchThreadHangMonitor.java
2016-08-19 10:17:23 UTC (rev 19514)
+++
gate/branches/sawdust2/plugins/Developer_Tools/src/main/java/org/jdesktop/swinghelper/debug/EventDispatchThreadHangMonitor.java
2016-08-19 10:39:39 UTC (rev 19515)
@@ -19,11 +19,7 @@
import java.awt.AWTEvent;
import java.awt.EventQueue;
-import java.awt.FlowLayout;
import java.awt.Toolkit;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
@@ -32,10 +28,6 @@
import java.util.Timer;
import java.util.TimerTask;
-import javax.swing.JButton;
-import javax.swing.JDialog;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
import javax.swing.SwingUtilities;
/**
@@ -216,13 +208,13 @@
* Sets up hang detection for the event dispatch thread.
*/
public static void initMonitoring() {
- //do the switch on the EDT as a fix for this bug
- //http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7097333
+ // do the switch on the EDT as a fix for this bug
+ // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7097333
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Toolkit.getDefaultToolkit().getSystemEventQueue().push(INSTANCE);
- }
+ }
});
}
@@ -244,21 +236,10 @@
}
}
- @SuppressWarnings("unused")
- private void debug(String which) {
- if(false) {
- for(int i = dispatches.size(); i >= 0; --i) {
- System.out.print(' ');
- }
- System.out.println(which);
- }
- }
-
/**
* Starts tracking a dispatch.
*/
private synchronized void preDispatchEvent() {
- debug("pre");
synchronized(dispatches) {
dispatches.addLast(new DispatchInfo());
}
@@ -284,25 +265,8 @@
}
}
}
- debug("post");
}
- @SuppressWarnings("unused")
- private static void checkForDeadlock() {
- ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
- long[] threadIds = threadBean.findMonitorDeadlockedThreads();
- if(threadIds == null) { return; }
- Log.warn("deadlock detected involving the following threads:");
- ThreadInfo[] threadInfos =
- threadBean.getThreadInfo(threadIds, Integer.MAX_VALUE);
- for(ThreadInfo info : threadInfos) {
- Log.warn("Thread #" + info.getThreadId() + " " + info.getThreadName()
- + " (" + info.getThreadState() + ") waiting on " + info.getLockName()
- + " held by " + info.getLockOwnerName()
- + stackTraceToString(info.getStackTrace()));
- }
- }
-
private static String stackTraceToString(StackTraceElement[] stackTrace) {
StringBuilder result = new StringBuilder();
// We used to avoid showing any code above where this class gets
@@ -320,173 +284,6 @@
return ++hangCount;
}
- public static void main(String[] args) {
- initMonitoring();
- // special case for deadlock test
- if(args.length > 0 && "deadlock".equals(args[0])) {
- EventDispatchThreadHangMonitor.INSTANCE.haveShownSomeComponent = true;
- Tests.runDeadlockTest();
- return;
- }
- Tests.main(args);
- }
-
- private static class Tests {
- public static void main(final String[] args) {
- java.awt.EventQueue.invokeLater(new Runnable() {
- public void run() {
- for(String arg : args) {
- final JFrame frame = new JFrame();
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setLocationRelativeTo(null);
- if(arg.equals("exception")) {
- runExceptionTest(frame);
- } else if(arg.equals("focus")) {
- runFocusTest(frame);
- } else if(arg.equals("modal-hang")) {
- runModalTest(frame, true);
- } else if(arg.equals("modal-no-hang")) {
- runModalTest(frame, false);
- } else {
- System.err.println("unknown regression test '" + arg + "'");
- System.exit(1);
- }
- frame.pack();
- frame.setVisible(true);
- }
- }
- });
- }
-
- private static void runDeadlockTest() {
- class Locker {
- private Locker locker;
-
- public void setLocker(Locker locker) {
- this.locker = locker;
- }
-
- public synchronized void tryToDeadlock() {
- locker.toString();
- }
-
- public synchronized String toString() {
- try {
- Thread.sleep(50);
- } catch(InterruptedException e) {
- e.printStackTrace();
- }
- return super.toString();
- }
- }
- final Locker one = new Locker();
- final Locker two = new Locker();
- one.setLocker(two);
- two.setLocker(one);
- // Deadlock expected here:
- for(int i = 0; i < 100; i++) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- one.tryToDeadlock();
- }
- });
- two.tryToDeadlock();
- }
- }
-
- // If we don't do our post-dispatch activity in a finally block, we'll
- // report bogus hangs.
- private static void runExceptionTest(final JFrame frame) {
- JButton button = new JButton("Throw Exception");
- button.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- // This shouldn't cause us to report a hang.
- throw new RuntimeException("Nobody expects the Spanish
Inquisition!");
- }
- });
- frame.add(button);
- }
-
- // A demonstration of nested calls to dispatchEvent caused by
- // SequencedEvent.
- private static void runFocusTest(final JFrame frame) {
- final JDialog dialog = new JDialog(frame, "Non-Modal Dialog");
- dialog.add(new JLabel("Close me!"));
- dialog.pack();
- dialog.setLocationRelativeTo(frame);
- dialog.addWindowFocusListener(new WindowAdapter() {
- public void windowGainedFocus(WindowEvent e) {
- System.out.println("FocusTest.windowGainedFocus");
- // If you don't cope with nested calls to dispatchEvent, you
- // won't detect this.
- // See java.awt.SequencedEvent for an example.
- sleep(2500);
- }
- });
- JButton button = new JButton("Show Non-Modal Dialog");
- button.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- dialog.setVisible(true);
- }
- });
- frame.add(button);
- }
-
- // A demonstration of the problems of dealing with modal dialogs.
- private static void runModalTest(final JFrame frame,
- final boolean shouldSleep) {
- System.out.println(shouldSleep
- ? "Expect hangs!"
- : "There should be no hangs...");
- JButton button = new JButton("Show Modal Dialog");
- button.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- if(shouldSleep) {
- sleep(2500); // This is easy.
- }
- JDialog dialog = new JDialog(frame, "Modal dialog", true);
- dialog.setLayout(new FlowLayout());
- dialog.add(new JLabel("Close this dialog!"));
- final JLabel label = new JLabel(" ");
- dialog.add(label);
- dialog.pack();
- dialog.setLocation(frame.getX() - 100, frame.getY());
- // Make sure the new event pump has some work to do, each
- // unit of which is insufficient to cause a hang.
- new Thread(new Runnable() {
- public void run() {
- for(int i = 0; i <= 100000; ++i) {
- final int value = i;
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- label.setText(Integer.toString(value));
- }
- });
- }
- }
- }).start();
- dialog.setVisible(true);
- if(shouldSleep) {
- sleep(2500); // If you don't distinguish different stack
- // traces, you won't report this.
- }
- }
- });
- frame.add(button);
- }
-
- private static void sleep(long ms) {
- try {
- System.out.println("Sleeping for " + ms + " ms on "
- + Thread.currentThread() + "...");
- Thread.sleep(ms);
- System.out.println("Finished sleeping...");
- } catch(Exception ex) {
- ex.printStackTrace();
- }
- }
- }
-
private static class Log {
public static void warn(String str) {
// MAG: send messages to the console, because if the AWT is locked
This was sent by the SourceForge.net collaborative development platform, the
world's largest Open Source development site.
------------------------------------------------------------------------------
_______________________________________________
GATE-cvs mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/gate-cvs