Datasets:
Dataset Viewer (First 5GB)
index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0 |
java-sources/abbot/abbot/1.4.0
|
java-sources/abbot/abbot/1.4.0/abbot/AssertionFailedError.java
|
package abbot;
import java.io.File;
import abbot.i18n.Strings;
import abbot.script.Step;
import abbot.script.Script;
/** Indirect usage to avoid too much direct linkage to JUnit. */
public class AssertionFailedError
extends junit.framework.AssertionFailedError {
private File file;
private int line;
public AssertionFailedError() { }
public AssertionFailedError(String msg) { super(msg); }
public AssertionFailedError(String msg, Step step) {
super(getMessage(msg, step));
this.file = Script.getFile(step);
this.line = Script.getLine(step);
}
public File getFile() { return file; }
public int getLine() { return line; }
private static String getMessage(String msg, Step step) {
File file = Script.getFile(step);
int line = Script.getLine(step);
if (file == null || line <= 0)
return msg;
return Strings.get("step.failure", new Object[] {
msg, file, new Integer(line)
});
}
}
|
0 |
java-sources/abbot/abbot/1.4.0
|
java-sources/abbot/abbot/1.4.0/abbot/BugReport.java
|
package abbot;
import javax.swing.UIManager;
import java.io.*;
import abbot.tester.Robot;
import abbot.i18n.Strings;
/** Exception for reporting unexpected situations in the program.
* Automatically generates a message suitable for posting in a bug report.
*/
public class BugReport extends Error implements Version {
private static final String LS = System.getProperty("line.separator");
private static final String BUGREPORT_URL = Strings.get("bugreport.url");
private static String getReportingInfo() {
return Strings.get("bugreport.info",
new Object[] { LS + BUGREPORT_URL + LS });
}
public static String getSystemInfo() {
return ""
+ "abbot version: " + VERSION + LS
+ " mode: " + Robot.getEventModeDescription() + LS
+ " OS: " + System.getProperty("os.name")
+ " " + System.getProperty("os.version")
+ " (" + System.getProperty("os.arch") + ") " + LS
+ " Java version: " + System.getProperty("java.version")
+ " (vm " + System.getProperty("java.vm.version") + ")" + LS
+ " Classpath: " + System.getProperty("java.class.path") + LS
+ "Look and Feel: " + UIManager.getLookAndFeel();
}
private String errorMessage;
private Throwable throwable;
public BugReport(String error) {
this(error, null);
}
public BugReport(String error, Throwable thr) {
super(error);
this.errorMessage = error;
this.throwable = thr;
}
public String toString() {
String exc = "";
if (throwable != null) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
exc = writer.toString();
}
return errorMessage
+ LS + getReportingInfo()
+ LS + getSystemInfo()
+ LS + exc;
}
}
|
0 |
java-sources/abbot/abbot/1.4.0
|
java-sources/abbot/abbot/1.4.0/abbot/ExitException.java
|
package abbot;
/** Provide a tagging interface and storage for attempted exits from code
under test.
*/
public class ExitException extends SecurityException {
private int status;
public ExitException(String msg, int status) {
super(msg + " (" + status + ") on " + Thread.currentThread());
this.status = status;
Log.log("Exit exception created at "
+ Log.getStack(Log.FULL_STACK, this));
}
public int getStatus() {
return status;
}
}
|
0 |
java-sources/abbot/abbot/1.4.0
|
java-sources/abbot/abbot/1.4.0/abbot/InterruptedAbbotException.java
|
package abbot;
import abbot.tester.FailedException;
/**
* Record the case where the current thread has been interrupted,
* a proxy for the normal
*/
public class InterruptedAbbotException extends FailedException {
// public WaitTimedOutError() { }
public InterruptedAbbotException(String msg) { super(msg); }
}
|
0 |
java-sources/abbot/abbot/1.4.0
|
java-sources/abbot/abbot/1.4.0/abbot/Log.java
|
// $Id: Log.java 2866 2014-08-14 08:37:05Z gdavison $
// Copyright (c) Oculus Technologies Corporation, all rights reserved
// ----------------------------------------------------------------------------
package abbot;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import abbot.util.Tee;
/**
Various logging, assertion, and debug routines. Typical usage is to
include the following code
<blockquote><code><pre>
public static void main(String[] args) {
args = Log.{@link Log#init(String[]) init}(args)
...
}
</pre></code></blockquote>
at an application's main entry point. This way the Log class can remove its
options from the full set passed into the application. See the
{@link #init(String[]) Log.init} method for initialization options. <p>
General usage notes on public functions:<p>
<ul>
<li>{@link #warn(String)}<br>
Programmer warnings; things that you think shouldn't be happening or
indicate something might be wrong. Warnings typically mean "Something
happened that I didn't expect would happen".<p>
<li>{@link #log(String)}<br>
Important information that might be needed for later reference; things the
user or debugger might be interested in. By default, all messages go
here. Logs are made available so that the customer may provide us with an
accurate record of software activity.<br>
All warnings and failed assertions are written to the log. Debug
statements are also written to log in non-release code.<p>
<li>{@link #debug(String)}<br>
Any messages which might be useful for debugging.
</ul>
<p>
Per-class stack trace depth can be specified when adding a class, e.g.
classname[:stack-depth].<p>
Extraction of the stack trace and logging to file are performed on a
separate thread to minimize performance impact due to filesystem delays.
Use {@link #setSynchronous(boolean) setSynchronous(false)} if you want
the output to be asynchronous with program execution.<p>
@author [email protected]
*/
public class Log {
/** No instantiations. */
protected Log() { }
private static final int LOG = 0x0001;
private static final int WARN = 0x0002;
private static final int DEBUG = 0x0004;
private static final class StdErrTee extends Tee {
private StdErrTee(PrintStream p1) {
super(STDERR, p1);
}
public String toString() {
return "<stderr> and log";
}
}
private static final class StdOutTee extends Tee {
private StdOutTee(PrintStream p1) {
super(STDOUT, p1);
}
public String toString() {
return "<stdout> and log";
}
}
private static class Context extends Throwable {
public Throwable thrown;
public int type;
public Context(int type) { this.type = type; }
public Context(int type, Throwable t) {
this(type);
this.thrown = t;
}
}
private static final String NL = System.getProperty("line.separator");
/** Mnemonic to print all lines of a stack trace. */
public static final int FULL_STACK = 0;
/** No stack, just a message. */
public static final int NO_STACK = -1;
/** Mnemonic to print the default number of lines of stack trace. */
private static final int CLASS_STACK_DEPTH = -2;
private static final String STDOUT_NAME = "<stdout>";
/** Basic warning categories. FIXME use these.
public static final int ERROR = 0x0001;
public static final int WARNING = 0x0002;
public static final int DEBUG = 0x0004;
public static final int INFO = 0x0008;*/
/** Whether log output is synchronous */
private static boolean synchronous = true;
/** Whether to log messages. Default on so that we capture output until
* the log file has been set or not set in <code>#init()</code>.
*/
private static boolean logMessages = true;
/** Whether to send anything to the console. */
private static boolean echoToConsole = true;
private static final PrintStream STDOUT = System.out;
private static final PrintStream STDERR = System.err;
/** Whether to show threads in debug output. */
private static boolean showThreads = false;
/** Default number of lines of stack trace to print. */
private static int debugStackDepth;
/** Default number of lines of stack trace to log. */
private static int logStackDepth;
/** Default number of lines of exception stack trace to print. */
private static int excStackDepth;
/** Show timestamps in the log? */
private static boolean showTimestamp = true;
private static java.text.DateFormat timestampFormat =
new java.text.SimpleDateFormat("yyMMdd HH:mm:ss:SSS");
/** Strip this out of output, since it doesn't add information to see it
repeatedly. */
private static final String COMMON_PREFIX = "com.oculustech.DOME.client";
private static final boolean ECLIPSE =
System.getProperty("java.class.path").indexOf("eclipse") != -1;
/** Store which class names we want to see debug info for. */
private static Map debugged = new HashMap();
/** Store which class names we don't want to see debug info for */
private static Set notdebugged = new HashSet();
/** Debug all classes? */
private static boolean debugAll;
/** Treat inner/anonymous classes as outer class? */
private static boolean debugInner = true;
private static final String DEFAULT_LOGFILE_NAME = "co-log.txt";
private static ByteArrayOutputStream preInitLog =
new ByteArrayOutputStream();
private static PrintStream logStream;
/** Stream which ensures a copy goes to stdout */
private static PrintStream debugStream;
/** Stream which ensures a copy goes to stderr */
private static PrintStream warnStream;
private static LogThread logThread;
private static String logFilename;
private static boolean showWarnings = true;
private static PrintStream BUFFER = new PrintStream(preInitLog);
//private static PrintStream STDOUT_AND_BUFFER = new Tee(STDOUT, BUFFER);
static {
setDestination(BUFFER);
logThread = new LogThread();
logThread.start();
debugStackDepth = Integer.
getInteger("co.debug_stack_depth", 1).intValue();
logStackDepth = Integer.
getInteger("co.log_stack_depth", NO_STACK).intValue();
excStackDepth = Integer.
getInteger("co.exception_stack_depth", FULL_STACK).intValue();
// Make sure the log gets closed on System.exit
Runtime.getRuntime().addShutdownHook(new Thread("Log shutdown hook") {
public void run() {
close();
}
});
}
/** Debug/log initialization, presumably from the command line.
<br>Recognized options:
<pre>
--debug all | className[:depth] | *.partialClassName[:depth]
--no-debug className | *.partialClassName
--log <log file name>
--no-timestamp
--enable-warnings
--show-threads
--stack-depth <depth>
--exception-depth <depth>
</pre>
*/
public static String[] init(String[] args){
logMessages = false;
ArrayList newArgs = new ArrayList();
for (int i=0;i < args.length;i++){
if (args[i].equals("--enable-warnings")){
showWarnings = true;
setEchoToConsole(true);
}
else if (args[i].equals("--no-timestamp")) {
showTimestamp = false;
}
else if (args[i].equals("--show-threads")){
showThreads = true;
}
else if (args[i].equals("--keep-console")){
setEchoToConsole(true);
}
else if (args[i].equals("--stack-depth")) {
if (++i < args.length) {
try {
debugStackDepth = Integer.parseInt(args[i]);
}
catch(Exception exc) {
}
}
else {
warn("Ignoring --stack-depth with no argument");
}
}
else if (args[i].equals("--exception-depth")) {
if (++i < args.length) {
try {
excStackDepth = Integer.parseInt(args[i]);
}
catch(Exception exc) {
}
}
else {
warn("Ignoring --exception-depth with no argument");
}
}
else if (args[i].equals("--debug")
|| args[i].equals("--no-debug")) {
if (++i < args.length) {
boolean exclude = args[i].startsWith("--no");
if (exclude)
removeDebugClass(args[i]);
else {
addDebugClass(args[i]);
setEchoToConsole(true);
}
}
else {
warn("Ignoring " + args[i-1] + " with no argument");
}
}
else if (args[i].equals("--log")){
String filename = DEFAULT_LOGFILE_NAME;
if (++i < args.length) {
filename = args[i];
}
initLogging(filename);
}
else {
newArgs.add(args[i]);
}
}
return (String[])newArgs.toArray(new String[newArgs.size()]);
}
/** Is log output enabled? */
public static boolean loggingInitialized() {
return logMessages && logStream != null;
}
private static String hostname = null;
private static final String DEFAULT_HOSTNAME = "unknown";
public static String getHostName() {
if(hostname == null) {
try {
hostname = java.net.InetAddress.getLocalHost().getHostName();
}
catch(java.net.UnknownHostException e) {
hostname = DEFAULT_HOSTNAME;
warn("Cannot get hostname, using " + hostname);
}
}
return hostname;
}
public static String getLogFilename() {
return logFilename;
}
public static PrintStream getLog() {
return logStream;
}
/** Enable log output to the given file. A filename of "-" means stdout. */
public static void initLogging(String filename) {
PrintStream ps = STDOUT;
logFilename = STDOUT_NAME;
if (!"-".equals(filename) && filename != null) {
try {
ps = new PrintStream(new FileOutputStream(filename), true);
logFilename = filename;
}
catch(IOException e) {
STDERR.println("Unable to write to " + filename);
STDERR.println("Output will go to the console");
}
}
setDestination(ps);
log("Log started on " + getHostName()
+ " (directed to " + logFilename + ")");
// Always insert the system information
Log.log(getSystemInfo());
}
/** Enable log output to the given {@link PrintStream}. */
public static void setDestination(PrintStream ps) {
logMessages = true;
logStream = ps;
// If there's a log file, redirect stdout/stderr there
if (logStream == STDOUT) {
debugStream = logStream;
warnStream = STDERR;
}
else if (logStream == BUFFER) {
debugStream = new StdOutTee(BUFFER);
warnStream = new StdErrTee(BUFFER);
}
else {
if (preInitLog.size() > 0) {
ps.print(preInitLog.toString());
preInitLog.reset();
}
debugStream = new StdOutTee(logStream);
warnStream = new StdErrTee(logStream);
System.setErr(warnStream);
System.setOut(debugStream);
if (logFilename != null) {
File file = new File(logFilename);
STDOUT.println("Output also captured in the log file at "
+ file.getAbsolutePath());
}
}
setEchoToConsole(logStream != STDOUT);
}
public static String getSystemInfo() {
Locale loc = Locale.getDefault();
return "System Details:" + NL
+ " java: " + System.getProperty("java.vm.name")
+ " " + System.getProperty("java.vm.version") + NL
+ " os: " + System.getProperty("os.name")
+ " " + System.getProperty("os.version")
+ " " + System.getProperty("os.arch") + NL
+ " user.dir: " + System.getProperty("user.dir") + NL
+ " locale: " + loc.getDisplayName()
+ " " + "[" + loc.getLanguage() + " " + loc.getCountry() + "]" + NL
+ "classpath: " + System.getProperty("java.class.path");
}
/** Sets the debug stack depth to the given amount */
public static void setDebugStackDepth(int depth) {
debugStackDepth = depth;
}
/** Resets the lists of classes to debug and not debug to be
empty, and turns debugAll off.
*/
public static void clearDebugClasses() {
debugged.clear();
debugAll = false;
notdebugged.clear();
}
/** Indicate that the given class should NOT be debugged
(assuming --debug all) */
public static void removeDebugClass(String className) {
setClassDebugEnabled(className, false);
}
/** Indicate that debug messages should be output for the given class. */
public static void addDebugClass(Class class1) {
addDebugClass(class1.getName());
}
/** Indicate that debug messages should no longer be output for the given
* class.
*/
public static void removeDebugClass(Class class1) {
removeDebugClass(class1.getName());
}
/** Indicate the class name[:depth] to add to debug output. */
public static void addDebugClass(String className) {
if (className.indexOf(":") == -1)
addDebugClass(className, CLASS_STACK_DEPTH);
else
setClassDebugEnabled(className, true);
}
/** Indicate that debug messages should be output for the given class. */
public static void addDebugClass(String className, int depth){
setClassDebugEnabled(className + ":" + depth, true);
}
/** Parse the given string, which may should be of the format
"class[:depth]" */
private static void setClassDebugEnabled(String id, boolean enable) {
int colon = id.indexOf(":");
String className = colon == -1 ? id : id.substring(0, colon);
if ("all".equals(className)) {
debugAll = enable;
if (enable) {
notdebugged.clear();
}
else {
debugged.clear();
}
}
else {
className = getFullClassName(className);
int depth = CLASS_STACK_DEPTH;
try {
depth = colon == -1
? debugStackDepth
: Integer.parseInt(id.substring(colon+1));
}
catch (NumberFormatException nfe) {
}
if (enable) {
debugged.put(className, new Integer(depth));
notdebugged.remove(className);
debug("Debugging enabled for " + className + " (" + depth + ")");
}
else {
notdebugged.add(className);
debugged.remove(className);
debug("Debugging disabled for " + className);
}
}
}
/** Returns class from given name/descriptor. Descriptor can be either a
fully qualified classname, or a classname beginning with *. with
client-specific package and classname following.
*/
private static String getFullClassName(String className) {
if (COMMON_PREFIX != null && className.startsWith("*.")) {
className = COMMON_PREFIX + className.substring(1);
}
return className;
}
/** Return the requested number of levels of stack trace, not including
this call. Returns the full stack trace if LINES is FULL_STACK.
Skip the first POP frames of the trace, which is for excluding the
innermost stack frames when debug functions make nested calls.
The outermost call of getStackTrace itself is always removed from the
trace. */
private static String getStackTrace(int pop, int lines) {
return getStackTrace(pop, lines, new Throwable("--debug--"));
}
/** Return the requested number of levels of stack trace, not including
this call. Returns the full stack trace if LINES is FULL_STACK.
Skip the first POP frames of the trace, which is for excluding the
innermost stack frames when debug functions make nested calls.
The outermost call of getStackTrace itself is always removed from the
trace. Provide an exception to use for the stack trace,
rather than using the current program location.
*/
private static String getStackTrace(int pop, int lines, Throwable thr) {
if (lines != NO_STACK) {
String stack = getStackTrace(pop, thr);
if (lines == FULL_STACK)
return stack;
return trimStackTrace(stack, lines);
}
return "";
}
/** Return the stack trace contained in the given Throwable.
Skip the first POP frames of the trace, which is for excluding the
innermost stack frames when debug functions make nested calls.
The outermost call of getStackTrace itself is always removed from the
trace.
*/
private static String getStackTrace(int pop, Throwable thr){
OutputStream os = new ByteArrayOutputStream();
PrintStream newStream = new PrintStream(os, true);
// OUCH! this is a serious performance hit!
thr.printStackTrace(newStream);
String trace = os.toString();
// Pop off getStackTrace itself
// Skip over any calls to getStackTrace; the JIT sometimes puts a
// spurious entry, so don't just stop at the first one.
int getLoc = trace.lastIndexOf("getStackTrace");
int at = trace.indexOf("\tat ", getLoc);
if (at != -1)
trace = trace.substring(at + 3);
while (pop-- > 0){
// pop off the calling function
at = trace.indexOf("\tat ");
if (at != -1)
trace = trace.substring(at + 3);
}
return trace.trim();
}
/** Trim the given trace to LINES levels. */
private static String trimStackTrace(String trace, int lines) {
// Keep just as many lines as were requested
int end = trace.indexOf(")") + 1;
boolean all = (lines == FULL_STACK);
while (all || --lines > 0) {
int index = trace.indexOf("\tat ", end);
if (index < 0)
break;
end = trace.indexOf(")", index) + 1;
}
return trace.substring(0, end);
}
/** Return the class corresponding to the first line in the give stack
trace. Treat inner/anonymous classes as the enclosing class. */
// FIXME with JIT enabled, stack trace sometimes has spurious junk on the
// stack, which will indicate the wrong class...
private static String extractClass(String trace){
int paren = trace.indexOf("(");
String tmp = paren == -1 ? trace : trace.substring(0, paren);
int mstart = tmp.lastIndexOf(".");
String cname = mstart == -1 ? tmp : tmp.substring(0, mstart);
cname = cname.trim();
if (debugInner) {
int sub = cname.indexOf("$");
if (sub != -1)
cname = cname.substring(0, sub).trim();
}
return cname;
}
public static boolean isClassDebugEnabled(Class cls) {
return isClassDebugEnabled(cls.getName());
}
public static boolean isClassDebugEnabled(String className) {
return (debugAll || debugged.containsKey(className))
&& !notdebugged.contains(className);
}
static int getClassStackDepth(String cname) {
Integer depth = (Integer)debugged.get(cname);
if (depth != null && depth.intValue() != CLASS_STACK_DEPTH)
return depth.intValue();
return debugStackDepth;
}
/** Print a debug message. */
public static void debug(String event){
internalDebug(event, new Context(DEBUG));
}
/** Print a debug message with the given number of stack lines. */
public static void debug(String event, int lines){
internalDebug(event, new Context(DEBUG), lines);
}
/** Use this to display debug output for expected or common exceptions. */
public static void debug(Throwable thr) {
internalDebug("", new Context(DEBUG, thr));
}
/** Issue a debug statement regarding the given {@link Throwable}. */
public static void debug(String m, Throwable e) {
internalDebug(m, new Context(DEBUG, e));
}
private static void internalDebug(String msg, Context context) {
internalDebug(msg, context, CLASS_STACK_DEPTH);
}
private static void internalDebug(String msg, Context context, int lines) {
if (debugged.size() > 0 || debugAll) {
internalLog(msg, context, lines, 1, echoToConsole ? debugStream : logStream);
}
}
/** Replace all occurrences of a given expresion with a different
string. */
private static String abbreviate(String msg, String expr, String sub) {
// Eclipse uses the full classs name for navigation, so don't hide it
if (ECLIPSE) return msg;
StringBuffer sb = new StringBuffer(msg);
int index = msg.indexOf(expr);
int len = expr.length();
while (index >= 0){
sb.replace(index, index + len, sub);
index = sb.toString().indexOf(expr);
}
return sb.toString();
}
/** Strip out stuff we don't want showing in the message. */
private static String abbreviate(String msg){
if (COMMON_PREFIX != null)
msg = abbreviate(msg, COMMON_PREFIX, "*");
return msg;
}
/** Issue a warning. All warnings go to the log file and the error
stream. */
private static void internalWarn(String message, Context context,
int depth, int pop){
internalLog(message, context, depth, pop,
showWarnings ? warnStream : logStream);
}
/** Retrieve the given number of lines of the current stack, as a
string. */
public static String getStack(int lines){
return getStackTrace(1, lines);
}
/** Retrieve the full stack from the given Throwable, as a string. */
public static String getStack(Throwable t) {
return getStackTrace(Log.FULL_STACK, t);
}
/** Retrieve the given number of lines of stack from the given Throwable,
as a string. */
public static String getStack(int lines, Throwable thr){
return getStackTrace(1, lines, thr);
}
/** Issue a programmer warning, which will include the source line of the
warning. */
public static void warn(String message){
internalWarn(message, new Context(WARN), debugStackDepth, 1);
}
/** Issue a programmer warning, which will include the source line of the
warning. */
public static void warn(String message, Throwable e){
internalWarn(message, new Context(WARN, e), debugStackDepth, 1);
}
/** Issue a programmer warning, which will include the source line of the
warning, and a stack trace with up to the given number of lines. */
public static void warn(String message, int lines){
internalWarn(message, new Context(WARN), lines, 1);
}
/** Issue a programmer warning, which will include the source line of the
original thrown object. */
public static void warn(Throwable thr) {
internalWarn("", new Context(WARN, thr), debugStackDepth, 1);
}
/** Log an exception. */
public static void log(Throwable thr) {
internalLog("", new Context(LOG, thr), excStackDepth, 1);
}
/** Log an exception with a description. */
public static void log(String message, Throwable thr) {
internalLog(message, new Context(LOG, thr), excStackDepth, 1);
}
/** Log a message. */
public static void log(String message){
internalLog(message, new Context(LOG), logStackDepth, 1);
}
private static void internalLog(String event, Context context,
int depth, int pop) {
internalLog(event, context, depth, pop, logStream);
}
private static void internalLog(String event, Context context,
int depth, int pop,
PrintStream stream){
String thread = Thread.currentThread().getName();
if (synchronous) {
logMessage(event, new Date(), context,
depth, pop, stream, thread);
}
else if (logThread != null) {
logThread.post(event, thread, new Date(),
context, depth, pop, stream);
}
else {
STDERR.println("Message posted after close: " + event);
}
}
static void flush() {
while (logThread.queue.size() > 0) {
synchronized(logThread.queue) {
logThread.queue.notifyAll();
}
try { Thread.sleep(10); } catch(InterruptedException e) { Thread.currentThread().interrupt(); }
}
debugStream.flush();
warnStream.flush();
logStream.flush();
}
public static void close() {
flush();
log("Log closed");
logStream.close();
logThread.terminate();
logThread = null;
}
private static class LogThread extends Thread {
private boolean terminate;
private Vector queue = new Vector();
public LogThread() {
super("Logging thread");
setDaemon(true);
}
public void terminate() {
synchronized(queue) {
terminate = true;
queue.notifyAll();
}
}
public void post(String msg, String threadName,
Date date, Context throwable, int depth,
int pop, PrintStream output) {
synchronized(queue) {
if (!terminate) {
queue.add(new Object[]{ msg, date, throwable,
new int[] { depth, pop }, output, threadName });
queue.notifyAll();
}
else {
STDERR.println("discarded: " + msg);
}
}
}
public void run() {
setName("Logging thread (to " + logStream + ")");
while (!terminate) {
try {
while (queue.size() > 0) {
Object[] list = (Object[])queue.get(0);
int[] args = (int[])list[3];
logMessage((String)list[0], (Date)list[1],
(Context)list[2], args[0], args[1],
(PrintStream)list[4], (String)list[5]);
queue.remove(0);
}
synchronized(queue) {
if (queue.size() == 0) {
queue.wait();
}
}
}
catch(InterruptedException e) {
break;
}
catch(Throwable e) {
STDERR.println("Error in logging thread: " + e);
e.printStackTrace();
}
}
}
}
private static String lastMessage = null;
private static int lastMessageRepeatCount = 0;
private static String lastMessageTimestamp = null;
private static PrintStream lastMessageStream = null;
private static void logMessage(String msg, Date date, Context context,
int depth, int pop, PrintStream stream,
String threadName) {
boolean debug = context.type == DEBUG;
String trace;
if (debug) {
trace = getStackTrace(pop, Log.FULL_STACK, context);
String cname = extractClass(trace);
if (!isClassDebugEnabled(cname)) {
return;
}
if (depth == CLASS_STACK_DEPTH) {
trace = trimStackTrace(trace, getClassStackDepth(cname));
}
}
else {
trace = getStackTrace(pop, depth, context);
}
if (context.thrown != null) {
Throwable e = context.thrown;
String where = getStackTrace(0, excStackDepth, e);
String type = e instanceof Error ? "Error" : "Exception thrown";
trace = type + " at " + where + ": " + e + NL
+ "\t(caught at " + trace + ")";
if (e instanceof InvocationTargetException) {
e = ((InvocationTargetException)e).getTargetException();
where = getStackTrace(0, excStackDepth, e);
trace += NL + "Target exception was " + e + " at " + where;
}
else if (e instanceof UndeclaredThrowableException) {
e = ((UndeclaredThrowableException)e).getUndeclaredThrowable();
where = getStackTrace(0, excStackDepth, e);
trace += NL + "Undeclared exception was " + e + " at " + where;
}
else if (e instanceof ExceptionInInitializerError) {
e = ((ExceptionInInitializerError)e).getException();
where = getStackTrace(0, excStackDepth, e);
trace += NL + "Exception was " + e + " at " + where;
}
}
trace = abbreviate(trace);
if (showThreads) {
trace = "[" + threadName + "] " + trace;
}
String timestamp = timestampFormat.format(date);
if (showTimestamp) {
trace = timestamp + " " + trace;
}
String output = trace.trim();
if (msg != null && !"".equals(msg)) {
output += ":\n\t" + msg;
}
if (stream == lastMessageStream
&& (msg == lastMessage
|| (msg != null && msg.equals(lastMessage)))) {
++lastMessageRepeatCount;
lastMessageTimestamp = timestamp;
}
else {
if (lastMessageRepeatCount > 0) {
lastMessageStream.println(lastMessageTimestamp
+ ": Last message repeated "
+ lastMessageRepeatCount + " times");
lastMessageStream.flush();
}
stream.println(output);
lastMessage = msg;
lastMessageStream = stream;
lastMessageRepeatCount = 0;
lastMessageTimestamp = timestamp;
}
}
/** Set whether log output is synchronous with program execution. */
public static void setSynchronous(boolean b) {
synchronous = b;
}
/** Set whether to display the current thread of execution. */
public static void setShowThreads(boolean b) {
showThreads = b;
}
/** Set whether messages are echoed to the console in addition to the log.
*/
public static void setEchoToConsole(boolean b) {
echoToConsole = b;
}
}
|
0 |
java-sources/abbot/abbot/1.4.0
|
java-sources/abbot/abbot/1.4.0/abbot/NoExitSecurityManager.java
|
package abbot;
public abstract class NoExitSecurityManager extends SecurityManager {
private Exception creation;
public NoExitSecurityManager() {
class CreationLocationException extends Exception { }
creation = new CreationLocationException();
}
public void checkPermission(java.security.Permission perm,
Object context) {
// allow everything
}
public void checkPermission(java.security.Permission perm) {
// allow everything
}
/**
* Returns true if the exit has been invoked through a call
* of Runtime.exit or Runtime.halt .
*
* @return true <=> An exit has been invoked through a call of Runtime.exit / Runtime.halt .
*/
public boolean exitInvoked() {
// We only want to disallow Runtime.halt/Runtime.exit
// Anything else is ok (e.g. System.runFinalizersOnExit; some VMs do a
// check there as well -- 1.3 and prior, I think)
String stack = Log.getStack(Log.FULL_STACK);
return(
(stack.indexOf("java.lang.Runtime.exit") != -1) ||
(stack.indexOf("java.lang.Runtime.halt") != -1)
);
}
public void checkExit(int status) {
if (exitInvoked()) {
exitCalled(status);
String msg = "Application exit denied";
Log.log(msg + " from security manager "
+ "created at " + Log.getStack(Log.FULL_STACK, creation));
throw new ExitException(msg, status);
}
}
/** Implement this method to do any context-specific cleanup. This
hook is provided since it may not always be possible to catch the
ExitException explicitly (like when it's caught by someone else, or
thrown from the event dispatch thread).
*/
protected abstract void exitCalled(int status);
}
|
0 |
java-sources/abbot/abbot/1.4.0
|
java-sources/abbot/abbot/1.4.0/abbot/Platform.java
|
package abbot;
import java.util.StringTokenizer;
/** Simple utility to figure out what platform we're on, what java version
* we're running.
*/
public class Platform {
public static final int JAVA_1_0 = 0x1000;
public static final int JAVA_1_1 = 0x1100;
public static final int JAVA_1_2 = 0x1200;
public static final int JAVA_1_3 = 0x1300;
public static final int JAVA_1_4 = 0x1400;
public static final int JAVA_1_5 = 0x1500;
public static final int JAVA_1_6 = 0x1600;
public static final int JAVA_1_7 = 0x1700;
public static final int JAVA_1_8 = 0x1800;
public static final int JAVA_1_9 = 0x1900;
public static final String OS_NAME;
public static final String JAVA_VERSION_STRING;
public static final int JAVA_VERSION;
static {
OS_NAME = System.getProperty("os.name");
JAVA_VERSION_STRING = System.getProperty("java.version");
JAVA_VERSION = parse(JAVA_VERSION_STRING);
}
private static boolean isWindows = OS_NAME.startsWith("Windows");
private static boolean isWindows9X = isWindows
&& (OS_NAME.indexOf("95") != -1
|| OS_NAME.indexOf("98") != -1
|| OS_NAME.indexOf("ME") != -1);
private static boolean isWindowsXP = isWindows && OS_NAME.indexOf("XP") != -1;
private static boolean isMac = System.getProperty("mrj.version") != null;
private static boolean isOSX = isMac && OS_NAME.indexOf("OS X") != -1;
private static boolean isSunOS = (OS_NAME.startsWith("SunOS")
|| OS_NAME.startsWith("Solaris"));
private static boolean isHPUX = OS_NAME.equals("HP-UX");
private static boolean isLinux = OS_NAME.equals("Linux");
/** No instantiations. */
private Platform() {
}
private static String strip(String number) {
while (number.startsWith("0") && number.length() > 1)
number = number.substring(1);
return number;
}
static int parse(String vs) {
int version = 0;
try {
StringTokenizer st = new StringTokenizer(vs, "._");
version = Integer.parseInt(strip(st.nextToken())) * 0x1000;
version += Integer.parseInt(strip(st.nextToken())) * 0x100;
version += Integer.parseInt(strip(st.nextToken())) * 0x10;
version += Integer.parseInt(strip(st.nextToken()));
}
catch(NumberFormatException nfe) {
}
catch(java.util.NoSuchElementException nse) {
}
return version;
}
// FIXME this isn't entirely correct, maybe should look for a motif class
// instead.
public static boolean isX11() { return !isOSX && !isWindows; }
public static boolean isWindows() { return isWindows; }
public static boolean isWindows9X() { return isWindows9X; }
public static boolean isWindowsXP() { return isWindowsXP; }
public static boolean isMacintosh() { return isMac; }
public static boolean isOSX() { return isOSX; }
public static boolean isSolaris() { return isSunOS; }
public static boolean isHPUX() { return isHPUX; }
public static boolean isLinux() { return isLinux; }
public static boolean is6OrAfter() { return JAVA_VERSION>=JAVA_1_6; }
public static boolean is7OrAfter() { return JAVA_VERSION>=JAVA_1_7; }
public static boolean is8OrAfter() { return JAVA_VERSION>=JAVA_1_8; }
public static boolean isBefore7() { return JAVA_VERSION<JAVA_1_7; }
public static boolean isBefore8() { return JAVA_VERSION<JAVA_1_8; }
public static boolean is6() { return JAVA_VERSION>=JAVA_1_6 && JAVA_VERSION<JAVA_1_7; }
public static boolean is7() { return JAVA_VERSION>=JAVA_1_7 && JAVA_VERSION<JAVA_1_8; }
public static boolean is8() { return JAVA_VERSION>=JAVA_1_8 && JAVA_VERSION<JAVA_1_9; }
public static void main(String[] args) {
System.out.println("Java version is " + JAVA_VERSION_STRING);
System.out.println("Version number is " + Integer.toHexString(JAVA_VERSION));
System.out.println("os.name=" + OS_NAME);
}
}
|
0 |
java-sources/abbot/abbot/1.4.0
|
java-sources/abbot/abbot/1.4.0/abbot/Version.java
|
package abbot;
/** Current version of the framework. */
public interface Version {
String VERSION = "1.4.0-SNAPSHOT";
}
|
0 |
java-sources/abbot/abbot/1.4.0
|
java-sources/abbot/abbot/1.4.0/abbot/WaitTimedOutException.java
|
package abbot;
import abbot.tester.FailedException;
/**
* Record the case where are have failed to wait for something, used to
* extend an AssertionError; but now extends FailException so we get the
* extra diagnostics.
*/
public class WaitTimedOutException extends FailedException {
// public WaitTimedOutError() { }
public WaitTimedOutException(String msg) { super(msg); }
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/finder/AWTHierarchy.java
|
package abbot.finder;
import javax.swing.*;
import abbot.Log;
import abbot.ExitException;
import abbot.tester.WindowTracker;
import abbot.tester.Robot;
import abbot.util.AWT;
import java.awt.Component;
import java.awt.Container;
import java.awt.Window;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
/** Provides access to the current AWT hierarchy. */
public class AWTHierarchy implements Hierarchy {
protected static final WindowTracker tracker = WindowTracker.getTracker();
protected static final Collection EMPTY = new ArrayList();
private static Hierarchy defaultHierarchy = null;
/** Obtain a default Hierarchy. This method is provided only to support
* the deprecated <code>ComponentTester.assertFrameShowing()</code> method.
*/
public static Hierarchy getDefault() {
/*System.out.println("Using default Hierarchy: "
+ Log.getStack(Log.FULL_STACK));*/
return defaultHierarchy != null
? defaultHierarchy : new AWTHierarchy();
}
/** Set the default Hierarchy. This method is provided only to support
* the deprecated <code>ComponentTester.assertFrameShowing()</code> method.
*/
public static void setDefault(Hierarchy h) {
defaultHierarchy = h;
}
/** Returns whether the given component is reachable from any of the root
* windows. The default is to consider all components to be contained in
* the hierarchy, whether they are reachable or not (NOTE: isReachable is
* a distinctly different operation).
*/
public boolean contains(Component c) {
return true;
}
/** Properly dispose of the given Window, making it and its native
* resources available for garbage collection.
*/
public void dispose(final Window w) {
if (AWT.isAppletViewerFrame(w)) {
// Don't dispose, it must quit on its own
return;
}
Log.debug("Dispose " + w);
Window[] owned = w.getOwnedWindows();
for (int i=0;i < owned.length;i++) {
// Window.dispose is recursive; make Hierarchy.dispose recursive
// as well.
dispose(owned[i]);
}
if (AWT.isSharedInvisibleFrame(w)) {
// Don't dispose, or any child windows which may be currently
// ignored (but not hidden) will be hidden and disposed.
return;
}
// Ensure the dispose is done on the swing thread so we can catch any
// exceptions. If Window.dispose is called from a non-Swing thread,
// it will invokes the dispose action on the Swing thread but in that
// case we have no control over exceptions.
Runnable action = new Runnable() {
public void run() {
try {
// Distinguish between the abbot framework disposing a
// window and anyone else doing so.
System.setProperty("abbot.finder.disposal", "true");
w.dispose();
System.setProperty("abbot.finder.disposal", "false");
}
catch(NullPointerException npe) {
// Catch bug in AWT 1.3.1 when generating hierarchy
// events
Log.log(npe);
}
catch(ExitException e) {
// Some apps might call System.exit on WINDOW_CLOSED
Log.log("Ignoring SUT exit: " + e);
}
catch(Throwable e) {
// Don't allow other exceptions to interfere with
// disposal.
Log.warn(e);
Log.warn("An exception was thrown when disposing "
+ " the window " + Robot.toString(w)
+ ". The exception is ignored");
}
}
};
if (SwingUtilities.isEventDispatchThread()) {
action.run();
}
else {
try { SwingUtilities.invokeAndWait(action); }
catch(Exception e) { }
}
}
/** Return all root components in the current AWT hierarchy. */
public Collection getRoots() {
return tracker.getRootWindows();
}
/** Return all descendents of interest of the given Component.
This includes owned windows for Windows, children for Containers.
*/
public Collection getComponents(Component c) {
if (c instanceof Container) {
final Container cont = (Container)c;
Callable<List> componentListClosure = new Callable<List>() {
@Override
public List call() {
List list = new ArrayList();
list.addAll(Arrays.asList(cont.getComponents()));
// Add other components which are not explicitly children, but
// that are conceptually descendents
if (cont instanceof JMenu) {
list.add(((JMenu)cont).getPopupMenu());
}
else if (cont instanceof Window) {
list.addAll(Arrays.asList(((Window)cont).getOwnedWindows()));
}
else if (cont instanceof JDesktopPane) {
// Add iconified frames, which are otherwise unreachable.
// For consistency, they are still considerered children of
// the desktop pane.
list.addAll(findInternalFramesFromIcons(cont));
}
return list;
}
};
List list = abbot.tester.Robot.callAndWait(cont, componentListClosure);
// List list;
//
// try {
// list = componentListClosure.call();
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
return list;
}
return EMPTY;
}
private Collection findInternalFramesFromIcons(Container cont) {
ArrayList list = new ArrayList();
int count = cont.getComponentCount();
for (int i=0;i < count;i++) {
Component child = cont.getComponent(i);
if (child instanceof JInternalFrame.JDesktopIcon) {
JInternalFrame frame =
((JInternalFrame.JDesktopIcon)child).
getInternalFrame();
if (frame != null)
list.add(frame);
}
// OSX puts icons into a dock; handle icon manager situations here
else if (child instanceof Container) {
list.addAll(findInternalFramesFromIcons((Container)child));
}
}
return list;
}
public Container getParent(Component c) {
// This call appears to be fairly thread safe
Container p = c.getParent();
if (p == null && c instanceof JInternalFrame) {
// workaround for bug in JInternalFrame: COMPONENT_HIDDEN is sent
// before the desktop icon is set, so
// JInternalFrame.getDesktopPane will throw a NPE if called while
// dispatching that event. Reported against 1.4.x.
JInternalFrame.JDesktopIcon icon =
((JInternalFrame)c).getDesktopIcon();
if (icon != null) {
p = icon.getDesktopPane();
}
// p = ((JInternalFrame)c).getDesktopPane();
}
return p;
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/finder/BasicFinder.java
|
package abbot.finder;
import java.awt.Container;
import java.awt.Component;
import java.awt.Window;
import java.util.*;
import javax.swing.SwingUtilities;
import abbot.i18n.Strings;
/** Provides basic component lookup, examining each component in turn.
Searches all components of interest in a given hierarchy.
*/
public class BasicFinder implements ComponentFinder {
private Hierarchy hierarchy;
private static final ComponentFinder DEFAULT =
new BasicFinder(new AWTHierarchy());
public static ComponentFinder getDefault() { return DEFAULT; }
private class SingleComponentHierarchy implements Hierarchy {
private Component root;
private ArrayList list = new ArrayList();
public SingleComponentHierarchy(Container root) {
this.root = root;
list.add(root);
}
public Collection getRoots() {
return list;
}
public Collection getComponents(Component c) {
return getHierarchy().getComponents(c);
}
public Container getParent(Component c) {
return getHierarchy().getParent(c);
}
public boolean contains(Component c) {
return getHierarchy().contains(c)
&& SwingUtilities.isDescendingFrom(c, root);
}
public void dispose(Window w) { getHierarchy().dispose(w); }
}
public BasicFinder() {
this(AWTHierarchy.getDefault());
}
public BasicFinder(Hierarchy h) {
hierarchy = h;
}
protected Hierarchy getHierarchy() {
return hierarchy;
}
/** Find a Component, using the given Matcher to determine whether a given
component in the hierarchy under the given root is the desired
one.
*/
public Component find(Container root, Matcher m)
throws ComponentNotFoundException, MultipleComponentsFoundException {
Hierarchy h = root != null
? new SingleComponentHierarchy(root) : getHierarchy();
return find(h, m);
}
/** Find a Component, using the given Matcher to determine whether a given
component in the hierarchy used by this ComponentFinder is the desired
one.
*/
public Component find(Matcher m)
throws ComponentNotFoundException, MultipleComponentsFoundException {
return find(getHierarchy(), m);
}
protected Component find(Hierarchy h, Matcher m)
throws ComponentNotFoundException, MultipleComponentsFoundException {
Set found = new HashSet();
Iterator iter = h.getRoots().iterator();
while (iter.hasNext()) {
findMatches(h, m, (Component)iter.next(), found);
}
if (found.size() == 0) {
String msg = Strings.get("finder.not_found",
new Object[] { m.toString() });
throw new ComponentNotFoundException(msg);
}
else if (found.size() > 1) {
Component[] list = (Component[])
found.toArray(new Component[found.size()]);
if (!(m instanceof MultiMatcher)) {
String msg = Strings.get("finder.multiple_found",
new Object[] { m.toString() });
throw new MultipleComponentsFoundException(msg, list);
}
return ((MultiMatcher)m).bestMatch(list);
}
return (Component)found.iterator().next();
}
protected void findMatches(Hierarchy h, Matcher m,
Component c, Set found) {
if (found.size() == 1 && !(m instanceof MultiMatcher))
return;
Iterator iter = h.getComponents(c).iterator();
while (iter.hasNext()) {
findMatches(h, m, (Component)iter.next(), found);
}
if (m.matches(c)) {
found.add(c);
}
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/finder/ComponentFinder.java
|
package abbot.finder;
import java.awt.*;
/** Interface to support looking up existing components based on a number of
different criteria.
@see Matcher
*/
public interface ComponentFinder {
/** Find a Component, using the given Matcher to determine whether a given
component in the hierarchy used by this ComponentFinder is the desired
one.
<p>
Note that {@link MultipleComponentsFoundException} can only be
thrown if the {@link Matcher} argument is an instance of
{@link MultiMatcher}.
*/
Component find(Matcher m)
throws ComponentNotFoundException, MultipleComponentsFoundException;
/** Find a Component, using the given Matcher to determine whether a given
component in the hierarchy under the given root is the desired
one.
<p>
Note that {@link MultipleComponentsFoundException} can only be
thrown if the {@link Matcher} argument is an instance of
{@link MultiMatcher}.
*/
Component find(Container root, Matcher m)
throws ComponentNotFoundException, MultipleComponentsFoundException;
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/finder/ComponentNotFoundException.java
|
package abbot.finder;
/** Indicates no component could be found, where one was required. */
public class ComponentNotFoundException extends ComponentSearchException {
public ComponentNotFoundException() { }
public ComponentNotFoundException(String msg) { super(msg); }
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/finder/ComponentSearchException.java
|
package abbot.finder;
/** General exception class which encapsulates all failures generated
* attempting to find a component in the currently available GUI.
*/
public class ComponentSearchException extends Exception {
public ComponentSearchException() { }
public ComponentSearchException(String msg) { super(msg); }
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/finder/Hierarchy.java
|
package abbot.finder;
import java.awt.Component;
import java.awt.Container;
import java.awt.Window;
import java.util.Collection;
/** Provides access to all components in a hierarchy. */
public interface Hierarchy {
/** Provides all root components in the hierarchy. Similar to
* Frame.getFrames().
*/
Collection getRoots();
/** Returns all sub-components of the given component. What constitutes a
* sub-component may vary depending on the Hierarchy implementation.
*/
Collection getComponents(Component c);
/** Return the parent component for the given Component. */
Container getParent(Component c);
/** Returns whether the hierarchy contains the given Component. */
boolean contains(Component c);
/** Provide proper disposal of the given Window, appropriate to this
* Hierarchy. After disposal, the Window and its descendents will no
* longer be reachable from this Hierarchy.
*/
void dispose(Window w);
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/finder/Matcher.java
|
package abbot.finder;
import java.awt.Component;
/** Provides an indication whether a Component matches some desired
criteria. For use with implementations of {@link ComponentFinder}.
You can conveniently inline a custom matcher like so:<br>
<pre><code>
ComponentFinder finder;
...
// Find a label with known text
JLabel label = (JLabel)finder.find(new Matcher() {
public boolean matches(Component c) {
return c instanceof JLabel
&& "expected text".equals(((JLabel)c).getText());
}
});
</code></pre>
@see ComponentFinder
*/
public interface Matcher {
/** Return whether the given Component matches some lookup criteria. */
boolean matches(Component c);
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/finder/MultiMatcher.java
|
package abbot.finder;
import java.awt.Component;
/** Provides methods for determining the best match among a group of matching
components.<p>
For use with implementations of {@link ComponentFinder}.
You can conveniently inline a custom matcher like so:<br>
<pre><code>
ComponentFinder finder = BasicFinder.getDefault();
...
// Find the widest label with known text
JLabel label = (JLabel)finder.find(new MultiMatcher() {
public boolean matches(Component c) {
return c instanceof JLabel
&& "OK".equals(((JLabel)c).getText());
}
public Component bestMatch(Component[] candidates)
throws MultipleComponentsFoundException {
Component biggest = candidates[0];
for (int i=1;i < candidates.length;i++) {
if (biggest.getWidth() < candidates[i].getWidth())
biggest = candidates[i];
}
return biggest;
}
});
</code></pre>
@see ComponentFinder
*/
public interface MultiMatcher extends Matcher {
/** Returns the best match among all the given candidates, or throws an
exception if there is no best match.
*/
Component bestMatch(Component[] candidates)
throws MultipleComponentsFoundException;
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/finder/MultipleComponentsFoundException.java
|
package abbot.finder;
import java.awt.Component;
import abbot.tester.Robot;
/** Indicates more than one component was found (usually where only one was
* desired).
*/
public class MultipleComponentsFoundException extends ComponentSearchException {
Component[] components;
public MultipleComponentsFoundException(Component[] list) {
components = list;
}
public MultipleComponentsFoundException(String msg, Component[] list) {
super(msg);
components = list;
}
public Component[] getComponents() { return components; }
public String toString() {
StringBuffer buf = new StringBuffer(super.toString());
buf.append(": ");
for (int i=0;i < components.length;i++) {
buf.append("\n (");
buf.append(String.valueOf(i));
buf.append(") ");
buf.append(Robot.toHierarchyPath(components[i]));
buf.append(": ");
buf.append(components[i].toString());
}
return buf.toString();
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/finder/TestHierarchy.java
|
package abbot.finder;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.SwingUtilities;
import abbot.Log;
import abbot.util.*;
/** Provide isolation of a Component hierarchy to limit consideration to only
those Components created during the lifetime of this Hierarchy instance.
Extant Components (and any subsequently generated subwindows) are ignored
by default.<p>
Implicitly auto-filters windows which are disposed (i.e. generate a
WINDOW_CLOSED event), but also implicitly un-filters them if they should
be shown again. Any Window explicitly disposed with
{@link #dispose(Window)} will be ignored permanently.<p>
*/
public class TestHierarchy extends AWTHierarchy {
// Map of components to ignore
private Map filtered = new WeakHashMap();
// Map of components implicitly filtered; these will be implicitly
// un-filtered if they are re-shown.
private Map transientFiltered = new WeakHashMap();
private static boolean trackAppletConsole =
Boolean.getBoolean("abbot.applet.track_console");
/** Avoid GC of the weak reference. */
private AWTEventListener listener;
/** Create a new TestHierarchy which does not contain any UI
* Components which might already exist.
*/
public TestHierarchy() {
this(true);
}
/** Create a new TestHierarchy, indicating whether extant Components
* should be omitted from the Hierarchy.
*/
public TestHierarchy(boolean ignoreExisting) {
if (ignoreExisting)
ignoreExisting();
// Watch for introduction of transient dialogs so we can automatically
// filter them on dispose (WINDOW_CLOSED). Don't do anything when the
// component is simply hidden, since we can't tell whether it will be
// re-used.
listener = new TransientWindowListener();
}
public boolean contains(Component c) {
return super.contains(c) && !isFiltered(c);
}
/** Dispose of the given Window, but only if it currently exists within
* the hierarchy. It will no longer appear in this Hierarchy or be
* reachable in a hierarchy walk.
*/
public void dispose(Window w) {
if (contains(w)) {
super.dispose(w);
setFiltered(w, true);
}
}
/** Make all currently extant components invisible to this Hierarchy,
* without affecting their current state.
*/
public void ignoreExisting() {
Iterator iter = getRoots().iterator();
while (iter.hasNext()) {
setFiltered((Component)iter.next(), true);
}
}
/** Returns all available root Windows, excluding those which have been
* filtered.
*/
public Collection getRoots() {
Collection s = super.getRoots();
s.removeAll(filtered.keySet());
return s;
}
/** Returns all sub-components of the given Component, omitting those
* which are currently filtered.
*/
public Collection getComponents(Component c) {
if (!isFiltered(c)) {
Collection s = super.getComponents(c);
// NOTE: this only removes those components which are directly
// filtered, not necessarily those which have a filtered ancestor.
s.removeAll(filtered.keySet());
return s;
}
return EMPTY;
}
private boolean isWindowFiltered(Component c) {
Window w = AWT.getWindow(c);
return w != null && isFiltered(w);
}
/** Returns true if the given component will not be considered when
* walking the hierarchy. A Component is filtered if it has explicitly
* been filtered via {@link #setFiltered(Component,boolean)}, or if
* any <code>Window</code> ancestor has been filtered.
*/
public boolean isFiltered(Component c) {
if (c == null)
return false;
if ("sun.plugin.ConsoleWindow".equals(c.getClass().getName()))
return !trackAppletConsole;
return filtered.containsKey(c)
|| ((c instanceof Window) && isFiltered(c.getParent()))
|| (!(c instanceof Window) && isWindowFiltered(c));
}
/** Indicates whether the given component is to be included in the
Hierarchy. If the component is a Window, recursively applies the
action to all owned Windows.
*/
public void setFiltered(Component c, boolean filter) {
// Never filter the shared frame
if (AWT.isSharedInvisibleFrame(c)) {
Iterator iter = getComponents(c).iterator();
while (iter.hasNext()) {
setFiltered((Component)iter.next(), filter);
}
}
else {
if (filter) {
filtered.put(c, Boolean.TRUE);
}
else {
filtered.remove(c);
}
transientFiltered.remove(c);
if (c instanceof Window) {
Window[] owned = ((Window)c).getOwnedWindows();
for (int i=0;i < owned.length;i++) {
setFiltered(owned[i], filter);
}
}
}
}
/** Provides for automatic filtering of auto-generated Swing dialogs. */
private class TransientWindowListener implements AWTEventListener {
private class DisposeAction implements Runnable {
private Window w;
public DisposeAction(Window w) {
this.w = w;
}
public void run() {
// If the window was shown again since we queued this action,
// it will have removed the window from the transientFiltered
// set, and we shouldn't filter.
if (transientFiltered.containsKey(w)) {
setFiltered(w, true);
Log.debug("window " + w.getName() + " filtered");
}
else {
Log.debug("cancel dispose of " + w.getName());
}
}
}
public TransientWindowListener() {
// Add a weak listener so we don't leave a listener lingering
// about.
long mask = WindowEvent.WINDOW_EVENT_MASK
| ComponentEvent.COMPONENT_EVENT_MASK;
new WeakAWTEventListener(this, mask);
}
public void eventDispatched(AWTEvent e) {
if (e.getID() == WindowEvent.WINDOW_OPENED
|| (e.getID() == ComponentEvent.COMPONENT_SHOWN
&& e.getSource() instanceof Window)) {
Window w = (Window)e.getSource();
Log.debug("window " + w.getName() + " open/shown");
if (transientFiltered.containsKey(w)) {
Log.debug("un-filter window " + w.getName());
setFiltered(w, false);
}
// Catch new sub-windows of filtered windows (i.e. dialogs
// generated by a test harness UI).
else if (isFiltered(w.getParent())) {
Log.debug("Parent is filtered, filter " + w.getName());
setFiltered(w, true);
}
}
else if (e.getID() == WindowEvent.WINDOW_CLOSED) {
final Window w = (Window)e.getSource();
// *Any* window disposal should result in the window being
// ignored, at least until it is again displayed.
if (!isFiltered(w)) {
transientFiltered.put(w, Boolean.TRUE);
// Filter this window only *after* any handlers for this
// event have finished.
Log.debug("queueing dispose of " + w.getName());
SwingUtilities.invokeLater(new DisposeAction(w));
}
}
}
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot/finder
|
java-sources/abbot/abbot/1.4.0/abbot/finder/matchers/AbstractMatcher.java
|
package abbot.finder.matchers;
import abbot.finder.Matcher;
import abbot.util.ExtendedComparator;
/** Convenience abstract class to provide regexp-based matching of strings. */
public abstract class AbstractMatcher implements Matcher {
/** Provides direct or regexp matching. To match a regular expression,
bound the expected string with slashes, e.g. /regular expression/.
*/
protected boolean stringsMatch(String expected, String actual) {
return ExtendedComparator.stringsMatch(expected, actual);
}
public String toString() {
return getClass().getName();
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot/finder
|
java-sources/abbot/abbot/1.4.0/abbot/finder/matchers/ClassMatcher.java
|
package abbot.finder.matchers;
import java.awt.Component;
/** Provides matching of components by class. */
public class ClassMatcher extends AbstractMatcher {
private Class cls;
private boolean mustBeShowing;
public ClassMatcher(Class cls) {
this(cls, false);
}
public ClassMatcher(Class cls, boolean mustBeShowing) {
this.cls = cls;
this.mustBeShowing = mustBeShowing;
}
public boolean matches(Component c) {
return cls.isAssignableFrom(c.getClass())
&& (!mustBeShowing || c.isShowing());
}
public String toString() {
return "Class matcher (" + cls.getName() + ")";
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot/finder
|
java-sources/abbot/abbot/1.4.0/abbot/finder/matchers/JMenuItemMatcher.java
|
package abbot.finder.matchers;
import java.awt.Component;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import abbot.finder.Matcher;
import abbot.util.ExtendedComparator;
import java.util.ArrayList;
import java.util.List;
/**
* Matches a {@link JMenuItem} given a simple label or a menu path of the
* format "menu|submenu|menuitem", for example "File|Open|Can of worms".
*
* @author twall
* @version $Id: JMenuItemMatcher.java 2815 2012-01-26 17:37:22Z gdavison $
*/
public class JMenuItemMatcher implements Matcher {
private String label;
public JMenuItemMatcher(String label) {
this.label = label;
}
public static String getPath(JMenuItem item) {
Component parent = item.getParent();
if (parent instanceof JPopupMenu) {
parent = ((JPopupMenu)parent).getInvoker();
}
if (parent instanceof JMenuItem) {
return getPath((JMenuItem)parent) + "|" + item.getText();
}
return item.getText();
}
/**
* @param path A path of the form File|Open|Can of worms
* @return A list of strings, File, File|Open, File|Open|Can of worms
*/
public static List splitMenuPath(String path) {
// Split the path
//
int lastFoundIndex = -1;
java.util.List selectionPath = new ArrayList();
while ((lastFoundIndex = path.indexOf('|', lastFoundIndex))!=-1)
{
selectionPath.add(path.substring(
0, lastFoundIndex));
lastFoundIndex = lastFoundIndex + 1;
}
selectionPath.add(path);
return selectionPath;
}
public boolean matches(Component c) {
if (c instanceof JMenuItem) {
JMenuItem mi = (JMenuItem)c;
String text = mi.getText();
return ExtendedComparator.stringsMatch(label, text)
|| ExtendedComparator.stringsMatch(label, getPath(mi));
}
return false;
}
public String toString()
{
return getClass().getSimpleName() + "[" + label + "]";
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot/finder
|
java-sources/abbot/abbot/1.4.0/abbot/finder/matchers/JMenuMatcher.java
|
package abbot.finder.matchers;
import abbot.finder.Matcher;
import abbot.util.ExtendedComparator;
import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
/**
* Extension of JMenuItemMatcher that only matches JMenu rather than
* all JMenuItem
*
* @author gdavison
* @version $Id: JMenuMatcher.java 1419 2005-01-05 18:34:48 +0000 (Wed, 05 Jan 2005) twall $
*/
public class JMenuMatcher extends JMenuItemMatcher {
public JMenuMatcher(String label) {
super(label);
}
public boolean matches(Component c) {
if (c instanceof JMenu) {
return super.matches(c);
}
return false;
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot/finder
|
java-sources/abbot/abbot/1.4.0/abbot/finder/matchers/NameMatcher.java
|
package abbot.finder.matchers;
import java.awt.Component;
import abbot.util.AWT;
/** Provides matching of Components by component name. */
public class NameMatcher extends AbstractMatcher {
private String name;
/** Construct a matcher that will match any component that has
explicitly been assigned the given <code>name</code>. Auto-generated
names (e.g. <code>win0</code>, <code>frame3</code>, etc. for AWT
(native) based components will not match.
*/
public NameMatcher(String name) {
this.name = name;
}
/** @return whether the given component has been explicitly assigned the
name given in the constructor.
*/
public boolean matches(Component c) {
String cname = c.getName();
if (name == null)
return cname == null || AWT.hasDefaultName(c);
return stringsMatch(name, cname);
}
public String toString() {
return "Name matcher (" + name + ")";
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot/finder
|
java-sources/abbot/abbot/1.4.0/abbot/finder/matchers/WindowMatcher.java
|
package abbot.finder.matchers;
import java.awt.*;
/** Provides matching of a Window by title or component name. */
public class WindowMatcher extends ClassMatcher {
private String id;
private boolean mustBeShowing;
public WindowMatcher(String id) {
this(id, true);
}
public WindowMatcher(String id, boolean mustBeShowing) {
super(Window.class);
this.id = id;
this.mustBeShowing = mustBeShowing;
}
public boolean matches(Component c) {
return super.matches(c)
&& (c.isShowing() || !mustBeShowing)
&& (stringsMatch(id, c.getName())
|| (c instanceof Frame
&& stringsMatch(id, ((Frame)c).getTitle()))
|| (c instanceof Dialog
&& stringsMatch(id, ((Dialog)c).getTitle())));
}
public String toString() {
return "Window matcher (id=" + id + ")";
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/i18n/Strings.java
|
package abbot.i18n;
import java.util.List;
import java.lang.ref.WeakReference;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import abbot.Log;
import abbot.editor.widgets.TextFormat;
/** Provides support for loading localized strings. Bundles may be added
by specifying the full resource name or by a simple name located in
com.oculustech.i18n.<p>
Bundles are searched from most- to least-recently added.
*/
public class Strings {
/** Resources whose name ends with this suffix (".tip") will automatically
* be formatted by the tooltip formatter.
* @see TextFormat#tooltip
*/
public static final String TOOLTIP_SUFFIX = ".tip";
/** Resources whose name ends with this suffix (".dlg") will automatically
* be formatted by the dialog formatter.
* @see TextFormat#dialog
*/
public static final String DIALOG_SUFFIX = ".dlg";
private static final String PREFIX =
Strings.class.getPackage().getName() + ".";
private static final String CORE_BUNDLE = "abbot";
private static List bundles = new ArrayList();
static {
// Load the default bundle
try {
addBundle(CORE_BUNDLE);
}
catch(MissingResourceException e) {
String msg = "No resource bundle found in " + CORE_BUNDLE;
if (System.getProperty("java.class.path").indexOf("junit") != -1)
Log.warn(msg);
else
throw new Error(msg);
}
}
/** Add the given bundle to the list searched. */
public static ResourceBundle addBundle(String name)
throws MissingResourceException {
return addBundle(name, null);
}
/** Add the given bundle to the list searched, loading from the given
class loader. The bundle will be weakly referenced.
*/
public static ResourceBundle addBundle(String name, ClassLoader cl)
throws MissingResourceException {
boolean wrap = cl != null;
if (cl == null) {
cl = Strings.class.getClassLoader();
}
Locale locale = Locale.getDefault();
ResourceBundle b;
try {
b = ResourceBundle.getBundle(name, locale, cl);
Log.debug("Added resource bundle " + name);
}
catch(MissingResourceException e) {
try {
b = ResourceBundle.getBundle(PREFIX + name, locale, cl);
Log.debug("Added resource bundle " + PREFIX + name);
}
catch(MissingResourceException e2) {
throw e;
}
}
synchronized(bundles) {
bundles.add(0, wrap ? new WeakReference(b) : (Object)b);
}
return b;
}
/** Add the given {@link ResourceBundle} as one to be searched. */
public static void addBundle(ResourceBundle b) {
synchronized(bundles) {
bundles.add(0, b);
}
}
private Strings() { }
/** Returns the localized String for the given key, or the key surrounded
by '#' if no corresponding localized string is found.
*/
public static String get(String key) {
return get(key, false);
}
/** Returns the localized string for the given key. If optional is true,
return null, otherwise returns the key surrounded by '#' if no
corresponding localized string is found.
*/
public static String get(String key, boolean optional) {
String defaultValue = "#" + key + "#";
String value = null;
synchronized(bundles) {
ListIterator iter = bundles.listIterator(bundles.size());
while (iter.hasPrevious()) {
Object bundle = iter.previous();
if (bundle instanceof WeakReference) {
bundle = ((WeakReference)bundle).get();
if (bundle == null) {
iter.remove();
continue;
}
}
try {
value = ((ResourceBundle)bundle).getString(key);
}
catch(MissingResourceException mre) {
}
}
}
if (value == null) {
if (!optional) {
Log.log("Missing resource '" + key + "'");
value = defaultValue;
}
}
else {
if (key.endsWith(TOOLTIP_SUFFIX)) {
value = TextFormat.tooltip(value);
}
else if (key.endsWith(DIALOG_SUFFIX)) {
value = TextFormat.dialog(value);
}
}
return value;
}
/** Returns a formatted localized string for the given key and arguments,
or the key if no corresponding localized string is found. Use
{@link java.text.MessageFormat} syntax for the format string and
arguments.
*/
public static String get(String key, Object... args) {
return new MessageFormat(get(key)).format(args);
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/AWTConstants.java
|
package abbot.tester;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import abbot.Platform;
import abbot.util.AWT;
/** Provides shared UI- and action-related constants. */
public interface AWTConstants {
int MULTI_CLICK_INTERVAL = 500; // a guess, TODO work out actual value by firing events at a window
/** Number of pixels traversed before a drag starts. */
// OSX 10(1.3.1), 5(1.4.1)
// Linux/X11: delay+16
// NOTE: could maybe install a drag gesture recognizer, but that's kinda
// complex for what you get out of it.
int DRAG_THRESHOLD =
Platform.isWindows() || Platform.isMacintosh() ? 10 : 16;
int BUTTON_MASK = (InputEvent.BUTTON1_MASK
| InputEvent.BUTTON2_MASK
| InputEvent.BUTTON3_MASK);
int POPUP_MASK = AWT.getPopupMask();
String POPUP_MODIFIER = AWT.getMouseModifiers(POPUP_MASK);
boolean POPUP_ON_PRESS = AWT.getPopupOnPress();
int TERTIARY_MASK = AWT.getTertiaryMask();
String TERTIARY_MODIFIER =
AWT.getMouseModifiers(TERTIARY_MASK);
int MENU_SHORTCUT_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
String MENU_SHORTCUT_MODIFIER =
AWT.getKeyModifiers(MENU_SHORTCUT_MASK);
String MENU_SHORTCUT_STRING =
MENU_SHORTCUT_MASK == InputEvent.ALT_MASK ? "alt "
: MENU_SHORTCUT_MASK == InputEvent.META_MASK ? "meta "
: MENU_SHORTCUT_MASK == InputEvent.SHIFT_MASK ? "shift "
: "control ";
String MENU_SHORTCUT_KEYCODE =
AWT.getKeyCode(AWT.maskToKeyCode(MENU_SHORTCUT_MASK));
// VM also allows ALT, I think
int MOVE_MASK = InputEvent.SHIFT_MASK;
/** Drag/drop copy mask. */
int COPY_MASK = Platform.isMacintosh()
? InputEvent.ALT_MASK : InputEvent.CTRL_MASK;
/** Drag/drop link mask. NOTE: w32 also natively uses ALT, but the VM
* doesn't (at least not 1.4.x).
*/
int LINK_MASK = Platform.isMacintosh()
? InputEvent.ALT_MASK | InputEvent.META_MASK
: InputEvent.CTRL_MASK | InputEvent.ALT_MASK;
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/AbstractButtonTester.java
|
package abbot.tester;
import java.awt.Component;
import javax.swing.*;
public class AbstractButtonTester extends JComponentTester {
public String deriveTag(Component comp) {
// If the component class is custom, don't provide a tag
if (isCustom(comp.getClass()))
return null;
AbstractButton absButton = ((AbstractButton)comp);
String tag = stripHTML(absButton.getText());
if ("".equals(tag) || tag == null) {
tag = super.deriveTag(comp);
}
return tag;
}
/** AbstractButton click action. */
public void actionClick(final Component c) {
/*
if (getEventMode() == EM_PROG) {
invokeAndWait(new Runnable() {
public void run() {
((JButton)c).doClick();
}
});
}
*/
if (c instanceof AbstractButton) {
AbstractButton b = (AbstractButton)c;
int x = b.getMinimumSize().width / 2;
int y = b.getHeight() / 2;
super.actionClick(b, x, y);
} else {
super.actionClick(c);
}
waitForIdle();
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/ActionFailedException.java
|
package abbot.tester;
import java.awt.Frame;
import java.awt.KeyboardFocusManager;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import javax.swing.FocusManager;
/** Indicates that a ComponentTester action failed to execute properly. */
public class ActionFailedException extends FailedException
{
public ActionFailedException(String msg, Throwable cause) {
super(msg, cause);
}
public ActionFailedException(String msg) {
super(msg);
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/ButtonTester.java
|
package abbot.tester;
import java.awt.Component;
import java.awt.Button;
import java.awt.event.ActionEvent;
/** Provides Button activation support, since otherwise AWT buttons cannot be
* activated in AWT mode.
*/
public class ButtonTester extends ComponentTester {
/** Programmatically clicks the Button if in AWT mode. */
public void click(Component comp, int x, int y, int mask, int count) {
if (getEventMode() == EM_AWT) {
postEvent(comp, new ActionEvent(comp, ActionEvent.ACTION_PERFORMED,
((Button)comp).getLabel()));
}
else {
super.click(comp, x, y, mask, count);
}
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/CallTimoutFailedException.java
|
package abbot.tester;
import java.awt.Frame;
import java.awt.KeyboardFocusManager;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import javax.swing.FocusManager;
/** Indicates that a Robot.callAndWait has failed to execute properly. */
public class CallTimoutFailedException extends FailedException
{
public CallTimoutFailedException(String msg, Throwable cause) {
super(msg, cause);
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/CheckboxTester.java
|
package abbot.tester;
import java.awt.Checkbox;
import java.awt.Component;
import java.awt.event.ItemEvent;
/** Provides Checkbox activation support, since otherwise AWT buttons cannot be
* activated in AWT mode.
*/
public class CheckboxTester extends ComponentTester {
/** Programmatically clicks the Checkbox if in AWT mode. */
public void click(final Component comp, int x, int y, int mask, int count) {
if (getEventMode() == EM_AWT) {
final Checkbox box = (Checkbox)comp;
invokeLater(new Runnable() {
public void run() {
box.setState(!box.getState());
ItemEvent e =
new ItemEvent(box, ItemEvent.ITEM_STATE_CHANGED,
box, box.getState() ? 1 : 0);
postEvent(box, e);
}
});
}
else {
super.click(comp, x, y, mask, count);
}
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/ChoiceTester.java
|
package abbot.tester;
import java.awt.*;
import java.awt.event.*;
import abbot.util.*;
/** AWT Choice (ComboBox/picklist) support. */
public class ChoiceTester extends ComponentTester {
private int CHOICE_DELAY =
Properties.getProperty("abbot.tester.choice_delay", 30000, 0, 60000);
private class Listener implements AWTEventListener {
public volatile boolean gotChange;
private int targetIndex = -1;
public Listener(int index) {
targetIndex = index;
}
public void eventDispatched(AWTEvent e) {
if (e.getID() == ItemEvent.ITEM_STATE_CHANGED
&& e.getSource() instanceof Choice) {
gotChange = ((Choice)e.getSource()).
getSelectedIndex() == targetIndex;
}
}
}
/** Select an item by index. */
public void actionSelectIndex(Component c, final int index) {
final Choice choice = (Choice)c;
int current = choice.getSelectedIndex();
if (current == index)
return;
// Don't add an item listener, because then we're at the mercy of any
// other ItemListener finishing. Don't bother clicking or otherwise
// sending events, since the behavior is platform-specific.
Listener listener = new Listener(index);
new WeakAWTEventListener(listener, ItemEvent.ITEM_EVENT_MASK);
choice.select(index);
ItemEvent ie = new ItemEvent(choice, ItemEvent.ITEM_STATE_CHANGED,
choice.getSelectedObjects()[0],
ItemEvent.SELECTED);
postEvent(choice, ie);
long now = System.currentTimeMillis();
while (!listener.gotChange) {
if (System.currentTimeMillis() - now > CHOICE_DELAY)
throw new ActionFailedException("Choice didn't fire for "
+ "index " + index);
sleep();
}
waitForIdle();
}
/** Select an item by its String representation. */
public void actionSelectItem(Component c, String item) {
Choice choice = (Choice)c;
for (int i=0;i < choice.getItemCount();i++) {
if (ExtendedComparator.stringsMatch(choice.getItem(i), item)) {
try {
actionSelectIndex(c, i);
return;
}
catch(ActionFailedException e) {
throw new ActionFailedException("Choice didn't fire for "
+ "item '" + item + "'");
}
}
}
throw new ActionFailedException("Item '" + item
+ "' not found in Choice");
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/ComponentLocation.java
|
package abbot.tester;
import java.awt.*;
import java.util.StringTokenizer;
import abbot.i18n.Strings;
/** Provides encapsulation of a visible Component-relative location.
* "Visible" in this context means currently accessible by the pointer
* (possibly via scrolling). A hidden node in a collapsed tree path
* would <strong>not</strong> be considered visible.
* <p>
* This class the specifics of location so that {@link ComponentTester}
* primitives
* ({@link ComponentTester#actionClick(Component,ComponentLocation)},
* {@link ComponentTester#actionShowPopupMenu(Component,ComponentLocation)},
* etc) may be directed to specific elements of
* substructure on a <code>Component</code> (list rows, tree paths, table
* cells, substructure values, etc.).
* <p>
* Classes derived from <code>ComponentLocation</code> should provide
* constructors for each type of location indication, e.g. value, index, and
* {@link Point}. The {@link #toString()} method should provide an encoded
* {@link String} suitable for use by the {@link #parse(String)} method, which
* must convert the {@link String} encoding back into a proper
* <code>ComponentLocation</code>.
* <p>
* By convention, {@link Point} locations are specified with (x,y) notation.
* Indexed locations should use square brackets, e.g. [i] or [r,c] and
* value locations should use a quoted {@link String}, e.g.
* '"cuckoo for cocoa puffs"'. The specific syntax allowed will vary by
* specific <code>ComponentLocation</code> type. The base
* <code>ComponentLocation</code> implementation
* supports only the explicit (x,y) notation.
* <p>
* Recorders
* should use the {@link String} value by default for consistency. The
* special value {@link #CENTER} is provided to indicate the center of a
* {@link Component}.
* <p>
* The method {@link #badFormat(String)} should provide usage-like information
* indicating the acceptable forms of input for this class.
*
* @see JListLocation
* @see JTreeLocation
* @see JTableLocation
*/
public class ComponentLocation {
/** Special <code>ComponentLocation</code> encoding which represents
the center of the component.
*/
public static final String CENTER = "(center)";
private Point where = null;
/** Create a simple location which represents the center of a component. */
public ComponentLocation() { }
/** Create a simple location. */
public ComponentLocation(Point where) {
this.where = new Point(where);
}
/** Convert the abstract location into a concrete one. Returns
* a {@link Point} relative to the given {@link Component}.
*/
public Point getPoint(Component c)
throws LocationUnavailableException {
return where != null
? new Point(where) : new Point(c.getWidth()/2, c.getHeight()/2);
}
/** Convert the abstract location into a concrete area, relative
* to the given <code>Component</code>. If a point has
* been specified, returns a 1x1 rectangle, otherwise returns the
* a rectangle at (0, 0) of the Component's size.
*/
public Rectangle getBounds(Component c)
throws LocationUnavailableException {
if (where == null)
return new Rectangle(0, 0, c.getWidth(), c.getHeight());
return new Rectangle(where.x, where.y, 1, 1);
}
/** Returns whether the given object is an equivalent
* <code>ComponentLocation</code>.
*/
public boolean equals(Object o) {
if (o instanceof ComponentLocation) {
ComponentLocation loc = (ComponentLocation)o;
return (where == null && loc.where == null)
|| (where != null && where.equals(loc.where));
}
return false;
}
public String toString() {
if (where != null)
return "(" + where.x + "," + where.y + ")";
return CENTER;
}
protected String badFormat(String encoded) {
return Strings.get("location.component.bad_format",
new Object[] { encoded });
}
protected String encodeIndex(int index) {
return "[" + index + "]";
}
/** Returns whether the given (trimmed) <code>String</code> is an encoded
index.
*/
protected boolean isIndex(String encoded) {
return encoded.startsWith("[") && encoded.endsWith("]");
}
/** Extract the encoded index. */
protected int parseIndex(String encoded) {
try {
return Integer.parseInt(encoded.
substring(1, encoded.length()-1).trim());
}
catch(NumberFormatException e) {
throw new IllegalArgumentException(badFormat(encoded));
}
}
protected String encodeValue(String value) {
return "\"" + value + "\"";
}
/** Returns whether the given (trimmed) <code>String</code> is an encoded
value.
*/
protected boolean isValue(String encoded) {
return encoded.startsWith("\"") && encoded.endsWith("\"");
}
/** Extract the encoded value. */
protected String parseValue(String encoded) {
return encoded.substring(1, encoded.length()-1);
}
/** Convert the given encoding into the proper location.
Allowed formats: (x, y)
<p>
*/
public ComponentLocation parse(String encoded) {
encoded = encoded.trim();
if (encoded.equals(CENTER)) {
where = null;
return this;
}
if (encoded.startsWith("(") && encoded.endsWith(")")) {
StringTokenizer st =
new StringTokenizer(encoded.substring(1, encoded.length()-1),
",");
if (st.countTokens() == 2) {
try {
int x = Integer.parseInt(st.nextToken().trim());
int y = Integer.parseInt(st.nextToken().trim());
where = new Point(x, y);
return this;
}
catch(NumberFormatException nfe) {
}
}
}
throw new IllegalArgumentException(badFormat(encoded));
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/ComponentMissingException.java
|
package abbot.tester;
/** Indicates that a component required by a ComponentTester action was not
* found.
*/
public class ComponentMissingException extends ActionFailedException {
public ComponentMissingException(String msg) { super(msg); }
public ComponentMissingException(String msg, Throwable cause) { super(msg, cause); }
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/ComponentNotShowingException.java
|
package abbot.tester;
/** Indicates that a ComponentTester action failed due to the component not
* being visible on screen.
*/
public class ComponentNotShowingException extends ActionFailedException {
public ComponentNotShowingException(String msg) { super(msg); }
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/ComponentTester.java
|
package abbot.tester;
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Point;
import java.awt.event.*;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleIcon;
import abbot.BugReport;
import abbot.Log;
import abbot.WaitTimedOutException;
import abbot.finder.AWTHierarchy;
import abbot.finder.BasicFinder;
import abbot.finder.ComponentFinder;
import abbot.finder.ComponentNotFoundException;
import abbot.finder.ComponentSearchException;
import abbot.finder.Hierarchy;
import abbot.finder.MultipleComponentsFoundException;
import abbot.finder.matchers.WindowMatcher;
import abbot.i18n.Strings;
import abbot.script.ComponentReference;
import abbot.tester.Robot.ConditionEDTDecorator;
import abbot.util.*;
/** Provides basic programmatic operation of a {@link Component} and related
UI objects such as windows, menus and menu bars throuh action methods.
Also provides some useful assertions about properties of a {@link
Component}.
<p>
There are two sets of event-generating methods. The internal, protected
methods inherited from {@link abbot.tester.Robot abbot.tester.Robot} are
for normal programmatic use within derived Tester classes. No event queue
synchronization should be performed except when modifying a component for
which results are required for the action itself.
<p>
The public <code>actionXXX</code> functions are meant to be invoked from a
script or directly from a hand-written test. These actions are
distinguished by name, number of arguments, and by argument type. The
actionX methods will be synchronized with the event dispatch thread when
invoked, so you should only do synchronization with waitForIdle when you
depend on the results of a particular event prior to sending the next one
(e.g. scrolling a table cell into view before selecting it).
All public action methods should ensure that the actions they
trigger are finished on return, or will be finished before any subsequent
actions are requested.
<p>
<i>Action</i> methods generally represent user-driven actions such
as menu selection, table selection, popup menus, etc. All actions should
have the following signature:
<blockquote>
<code>public void actionSpinMeRoundLikeARecord(Component c, ...);</code>
<code>public void actionPinchMe(Component c, ComponentLocation loc);</code>
</blockquote>
<p>
It is essential that the argument is of type {@link Component}; if you use
a more-derived class, then the actual invocation becomes ambiguous since
method parsing doesn't attempt to determine which identically-named method
is the most-derived.
<p>
The {@link ComponentLocation} abstraction allows all derived tester
classes to inherit click, popup menu, and drag variants without having to
explicitly define new methods for component-specific substructures. The
new class need only define the {@link #parseLocation(String)} method,
which should return a location specific to the component in question.
<p>
<i>Assertions</i> are either independent of any component (and should be
implemented in this class), or take a component as the first argument, and
perform some check on that component. All assertions should have one of
the following signatures:
<blockquote>
<code>public boolean assertMyself(...);</code><br>
<code>public boolean assertBorderIsAtrociouslyUgly(Component c, ...);</code>
</blockquote>
Note that these assertions do not throw exceptions but rather return a
<code>boolean</code> value indicating success or failure. Normally these
assertions will be wrapped by an abbot.script.Assert step if you want to
cause a test failure, or you can manually throw the proper failure
exception if the method returns false.
<p>
<i>Property checks</i> may also be implemented in cases where the component
"property" might not be readily available or easily comparable, e.g.
see {@link abbot.tester.JPopupMenuTester#getMenuLabels(Component)}.
<blockquote>
<code>public Object getHairpiece(Component c);</code><br>
<code>public boolean isRighteouslyIndignant(Component c);</code>
</blockquote>
Any non-property methods with the property signature, should be added to
the {@link #IGNORED_METHODS} set, since property-like methods are scanned
dynamically to populate the {@link abbot.editor.ScriptEditor editor}'s
action menus.
<p>
<a name=Customization>
<h2>Extending ComponentTester</h2>
Following are the steps required to implement a Tester object for a custom
class.
<ul>
<li><h3>Create the Tester Class</h3>
Derive from this class to implement actions and assertions specific to
a given component class. Testers for any classes found in the JRE
(i.e. in the {@link java.awt} or {@link javax.swing} packages) should be
in the {@link abbot.tester abbot.tester} package. Extensions (testers for
any <code>Component</code> subclasses not found in the JRE) must be in the
<code>abbot.tester.extensions</code> package and be
named the name of the <code>Component</code> subclass followed by "Tester".
For example, the {@link javax.swing.JButton javax.swing.JButton} tester
class is {@link JButtonTester abbot.tester.JButtonTester}, and a tester
for <code>org.me.PR0NViewer</code> would be
<code>abbot.tester.extensions.PR0NViewerTester</code>.
<li><h3>Add Action Methods</h3>
Add <code>action</code> methods which effect user actions.
See the section on <a href=Naming>naming conventions</a> below.
<li><h3>Add Assertion Methods</h3>
Add <code>assert</code> methods to access attributes not readily available
as properties<br>
<li><h3>Add Substructure Support</h3>
Add a corresponding <code>ComponentLocation</code> implementation to
handle any substructure present in your <code>Component</code>.
See {@link ComponentLocation} for details.
<li><h3>Add Substructure-handling Methods</h3>
<ul>
<li>{@link #parseLocation(String)}<br>
Convert the given <code>String</code> into an instance of
{@link ComponentLocation} specific to your Tester. Here is an example
implementation from {@link JListTester}:<br>
<code><pre>
public ComponentLocation parseLocation(String encoded) {
return new JListLocation().parse(encoded);
}
</pre></code>
<li>{@link #getLocation(Component,Point)}<br>
Use the given <code>Point</code> to create a {@link ComponentLocation}
instance appropriate for the <code>Component</code> substructure
available at that location. For example, on a {@link javax.swing.JList},
you would return a {@link JListLocation} based on the
stringified value at that location, the row/index at that
location, or the raw <code>Point</code>,
in order of preference. If a stringified value is unavailable,
fall back to an indexed position; if that is not possible (if, for
instance, the location is outside the list contents), return a
{@link ComponentLocation} based on the raw <code>Point</code>.
</ul>
<li><h3>Set Editor Properties</h3>
Add-on tester classes should set the following system properties so that
the actions provided by their tester can be properly displayed in the
script editor. For an action <code>actionWiggle</code> provided by class
<code>abbot.tester.extensions.PR0NViewerTester</code>, the following
properties should be defined:<br>
<ul>
<li><code>actionWiggle.menu</code> short name for Insert menu
<li><code>actionWiggle.desc</code> short description (optional)
<li><code>actionWiggle.icon</code> icon for the action (optional)
<li><code>PR0NViewerTester.actionWiggle.args</code> javadoc-style
description of method, displayed when asking the user for its arguments
</ul>
Since these properties are global, if your Tester class defines a method
which is also defined by another Tester class, you must supply the class
name as a prefix to the property.
</ul>
<p>
<a name=MethodNaming>
<h2>Method Naming Conventions</h2>
Action methods should be named according to the human-centric action that
is being performed if at all possible. For example, use
<code>actionSelectRow</code> in a List rather than
<code>actionSelectIndex</code>. If there's no common usage, or if the
usage is too vague or diverse, use the specific terms used in code.
For example, {@link JScrollBarTester} uses
{@link JScrollBarTester#actionScrollUnitUp(Component) actionScrollUnitUp()}
and
{@link JScrollBarTester#actionScrollBlockUp(Component) actionScrollBlockUp()};
since there is no common language usage for these
concepts (line and page exist, but are not appropriate if what is scrolled
is not text).
<p>
When naming a selection method, include the logical substructure target of
the selection in the name (e.g.
{@link JTableTester#actionSelectCell(Component,JTableLocation)}
JTableTester.actionSelectCell()),
since some components may have more than one type of selectable item
within them.
*/
public class ComponentTester extends Robot {
/** Add any method names here which should <em>not</em> show up in a
dynamically generated list of property methods.
*/
protected static Set IGNORED_METHODS = new HashSet();
static {
// Omit from method lookup deprecated methods or others we want to
// ignore
IGNORED_METHODS.addAll(Arrays.asList(new String[] {
"actionSelectAWTMenuItemByLabel",
"actionSelectAWTPopupMenuItemByLabel",
"getTag", "getTester", "isOnPopup", "getLocation",
}));
}
/** Maps class names to their corresponding Tester object. */
private static HashMap testers = new HashMap();
/** Establish the given ComponentTester as the one to use for the given
* class. This may be used to override the default tester for a given
* core class. Note that this will only work with components loaded by
* the framework class loader, not those loaded by the class loader for
* the code under test.
*/
public static void setTester(Class forClass, ComponentTester tester) {
testers.put(forClass.getName(), tester);
}
/** Return a shared instance of the appropriate
<code>ComponentTester</code> for the given {@link Component}.<p>
This method is primarily used by the scripting system, since the
appropriate <code>ComponentTester</code> for a given {@link Component}
is not known <i>a priori</i>. Coded unit tests should generally just
create an instance of the desired type of <code>ComponentTester</code>
for local use.
*/
public static ComponentTester getTester(Component comp) {
return comp != null ? getTester(comp.getClass())
: getTester(Component.class);
}
/** Return a shared instance of the corresponding
<code>ComponentTester</code> object for the given {@link Component}
class, chaining up the inheritance tree if no specific tester is found
for that class.<p>
The abbot tester package is searched first, followed by the tester
extensions package.<p>
This method is primarily used by the scripting system, since the
appropriate <code>ComponentTester</code> for a given Component is not
known <i>a priori</i>. Coded unit tests should generally just create
an instance of the desired type of <code>ComponentTester</code> for
local use.
*/
public static ComponentTester getTester(Class componentClass) {
String className = componentClass.getName();
ComponentTester tester = (ComponentTester)testers.get(className);
if (tester == null) {
if (!Component.class.isAssignableFrom(componentClass)) {
String msg = "Class " + className
+ " is not derived from java.awt.Component";
throw new IllegalArgumentException(msg);
}
Log.debug("Looking up tester for " + componentClass);
String testerName = simpleClassName(componentClass) + "Tester";
Package pkg = ComponentTester.class.getPackage();
String pkgName = "";
if (pkg == null) {
Log.warn("ComponentTester.class has null package; "
+ "the class loader is likely flawed: "
+ ComponentTester.class.getClassLoader()
+ ", "
+ Thread.currentThread().getContextClassLoader(),
Log.FULL_STACK);
pkgName = "abbot.tester";
}
else {
pkgName = pkg.getName();
}
if (className.startsWith("javax.swing.")
|| className.startsWith("java.awt.")) {
tester = findTester(pkgName + "." + testerName,
componentClass);
}
if (tester == null) {
tester = findTester(pkgName + ".extensions." + testerName,
componentClass);
if (tester == null) {
tester = getTester(componentClass.getSuperclass());
}
}
if (tester != null && !tester.isExtension()) {
// Only cache it if it's part of the standard framework,
// but cache it for every level that we looked up, so we
// don't repeat the effort.
testers.put(componentClass.getName(), tester);
}
}
return tester;
}
/** Return whether this tester is an extension. */
public final boolean isExtension() {
return getClass().getName().startsWith("abbot.tester.extensions");
}
/** Look up the given class, using special class loading rules to maintain
framework consistency. */
private static Class resolveClass(String testerName, Class componentClass)
throws ClassNotFoundException {
// Extension testers must be loaded in the context of the code under
// test.
Class cls;
if (testerName.startsWith("abbot.tester.extensions")) {
// In an OSGI environment it might be that the test classes
// are in a different class loader to the UI classes
//
try {
cls = Class.forName(testerName, true,
componentClass.getClassLoader());
}
catch (ClassNotFoundException cnfe){
// Deal with cases where the ccl is null and throw a new exception
// so that clients can properly trace the code back
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl!=null){
cls = Class.forName(testerName, true, ccl);
} else {
throw new ClassNotFoundException(testerName,cnfe);
}
}
}
else {
cls = Class.forName(testerName);
}
Log.debug("Loaded class " + testerName + " with "
+ cls.getClassLoader());
return cls;
}
/** Look up the given class with a specific class loader. */
private static ComponentTester findTester(String testerName,
Class componentClass) {
ComponentTester tester = null;
Class testerClass = null;
try {
testerClass = resolveClass(testerName, componentClass);
tester = (ComponentTester)testerClass.newInstance();
}
catch(InstantiationException ie) {
Log.warn(ie);
}
catch(IllegalAccessException iae) {
Log.warn(iae);
}
catch(ClassNotFoundException cnf) {
//Log.debug("Class " + testerName + " not found");
}
catch(ClassCastException cce) {
throw new BugReport("Class loader conflict: environment "
+ ComponentTester.class.getClassLoader()
+ " vs. " + testerClass.getClassLoader());
}
return tester;
}
/** Derive a tag from the given accessible context if possible, or return
* null.
*/
protected String deriveAccessibleTag(AccessibleContext context) {
String tag = null;
if (context != null) {
if (context.getAccessibleName() != null) {
tag = context.getAccessibleName();
}
if ((tag == null || "".equals(tag))
&& context.getAccessibleIcon() != null
&& context.getAccessibleIcon().length > 0) {
AccessibleIcon[] icons = context.getAccessibleIcon();
tag = icons[0].getAccessibleIconDescription();
if (tag != null) {
tag = tag.substring(tag.lastIndexOf("/") + 1);
tag = tag.substring(tag.lastIndexOf("\\") + 1);
}
}
}
return tag;
}
/** Default methods to use to derive a component-specific tag. These are
* things that will probably be useful in a custom component if the method
* is supported.
*/
private static final String[] tagMethods = {
"getLabel", "getTitle", "getText",
};
/** Return a reasonable identifier for the given component.
Note that this should not duplicate information provided by existing
attributes such as title, label, or text.
This functionality is provided to assist in identification of
non-standard GUI components only.
*/
public static String getTag(Component comp) {
return getTester(comp.getClass()).deriveTag(comp);
}
/** Returns whether the given class is not a core JRE class. */
protected boolean isCustom(Class c) {
return !(c.getName().startsWith("javax.swing.")
|| c.getName().startsWith("java.awt."));
}
/** Determine a component-specific identifier not already defined in other
* component attributes. This method should be defined to something
* unique for custom UI components.
*/
public String deriveTag(Component comp) {
// If the component class is custom, don't provide a tag
if (isCustom(comp.getClass()))
return null;
Method m;
String tag = null;
// Try a few default methods
for (int i=0;i < tagMethods.length;i++) {
// Don't use getText on text components
if (((comp instanceof javax.swing.text.JTextComponent)
|| (comp instanceof java.awt.TextComponent))
&& "getText".equals(tagMethods[i])) {
continue;
}
try {
m = comp.getClass().getMethod(tagMethods[i], null);
String tmp = (String)m.invoke(comp, null);
// Don't ever use empty strings for tags
if (tmp != null && !"".equals(tmp)) {
tag = tmp;
break;
}
}
catch(Exception e) {
}
}
// In the absence of any other tag, try to derive one from something
// recognizable on one of its ancestors.
if (tag == null || "".equals(tag)) {
Component parent = comp.getParent();
if (parent != null) {
String ptag = getTag(parent);
if (ptag != null && !"".equals(tag)) {
// Don't use the tag if it's simply the window title; that
// doesn't provide any extra information.
if (!ptag.endsWith(" Root Pane")) {
StringBuffer buf = new StringBuffer(ptag);
int under = ptag.indexOf(" under ");
if (under != -1)
buf = buf.delete(0, under + 7);
buf.insert(0, " under ");
buf.insert(0, simpleClassName(comp.getClass()));
tag = buf.toString();
}
}
}
}
return tag;
}
/**
* Wait for an idle AWT event queue. Will return when there are no more
* events on the event queue.
*/
public void actionWaitForIdle() {
waitForIdle();
}
/** Delay the given number of ms. */
public void actionDelay(int ms) {
delay(ms);
}
/** @deprecated Renamed to {@link #actionSelectAWTMenuItem(Frame,String)}.
*/
public void actionSelectAWTMenuItemByLabel(Frame menuFrame, String path) {
actionSelectAWTMenuItem(menuFrame, path);
}
/** Selects an AWT menu item ({@link java.awt.MenuItem}) and returns when
the invocation has triggered (though not necessarily completed).
@param menuFrame
@param path either a unique label or the menu path.
@see Robot#selectAWTMenuItem(Frame,String)
*/
public void actionSelectAWTMenuItem(Frame menuFrame, String path) {
AWTMenuListener listener = new AWTMenuListener();
new WeakAWTEventListener(listener, ActionEvent.ACTION_EVENT_MASK);
selectAWTMenuItem(menuFrame, path);
long start = System.currentTimeMillis();
while (!listener.eventFired) {
if (System.currentTimeMillis() - start > defaultDelay) {
throw new ActionFailedException("Menu item '" + path
+ "' failed to fire");
}
sleep();
}
waitForIdle();
}
/** @deprecated Renamed to
{@link #actionSelectAWTPopupMenuItem(Component,String)}.
*/
public void actionSelectAWTPopupMenuItemByLabel(Component invoker,
String path) {
actionSelectAWTPopupMenuItem(invoker, path);
}
/** Selects an AWT menu item and returns when the invocation has triggered
(though not necessarily completed).
@see Robot#selectAWTPopupMenuItem(Component,String)
*/
public void actionSelectAWTPopupMenuItem(Component invoker, String path) {
AWTMenuListener listener = new AWTMenuListener();
new WeakAWTEventListener(listener, ActionEvent.ACTION_EVENT_MASK);
selectAWTPopupMenuItem(invoker, path);
long start = System.currentTimeMillis();
while (!listener.eventFired) {
if (System.currentTimeMillis() - start > defaultDelay) {
throw new ActionFailedException("Menu item '" + path
+ "' failed to fire");
}
sleep();
}
waitForIdle();
}
/** Select the given menu item. */
public void actionSelectMenuItem(Component item) {
Log.debug("Attempting to select menu item " + toString(item));
selectMenuItem(item);
waitForIdle();
}
/** Select the given menu item, given its path and a component on the same
window.
*/
public void actionSelectMenuItem(Component sameWindow, String path) {
Log.debug("Attempting to select menu item '" + path + "'");
selectMenuItem(sameWindow, path);
waitForIdle();
}
/** Pop up a menu at the center of the given component and
select the given item.
*/
public void actionSelectPopupMenuItem(Component invoker, String path) {
actionSelectPopupMenuItem(invoker, invoker.getWidth()/2,
invoker.getHeight()/2, path);
}
/** Pop up a menu at the given location on the given component and
select the given item.
*/
public void actionSelectPopupMenuItem(Component invoker,
ComponentLocation loc,
String path) {
selectPopupMenuItem(invoker, loc, path);
waitForIdle();
}
/** Pop up a menu at the given coordinates on the given component and
select the given item.
*/
public void actionSelectPopupMenuItem(Component invoker, int x, int y,
String path) {
actionSelectPopupMenuItem(invoker,
new ComponentLocation(new Point(x, y)),
path);
}
/** Pop up a menu in the center of the given component. */
public void actionShowPopupMenu(Component invoker) {
actionShowPopupMenu(invoker, new ComponentLocation());
}
/** Pop up a menu in the center of the given component. */
public void actionShowPopupMenu(Component invoker, ComponentLocation loc) {
Point where = loc.getPoint(invoker);
showPopupMenu(invoker, where.x, where.y);
}
/** Pop up a menu at the given location on the given component.
*/
public void actionShowPopupMenu(Component invoker, int x, int y) {
showPopupMenu(invoker, x, y);
}
/** Click on the center of the component. */
public void actionClick(Component comp) {
actionClick(comp, new ComponentLocation());
}
/** Click on the component at the given location. */
public void actionClick(Component c, ComponentLocation loc) {
actionClick(c, loc, InputEvent.BUTTON1_MASK);
}
/** Click on the component at the given location with the given
modifiers.
*/
public void actionClick(Component c, ComponentLocation loc, int buttons) {
actionClick(c, loc, buttons, 1);
}
/** Click on the component at the given location, with the given
* modifiers and click count.
*/
public void actionClick(final Component c, ComponentLocation loc,
int buttons, int count) {
// Check the component is neabled before clicking on it, wait if required
//
wait(new ConditionEDTDecorator(c,new Condition() {
public boolean test() {
return c.isEnabled();
}
public String toString() {
return Strings.get("tester.Component.not_enabled",
new Object[] { c.toString() });
}
}), componentDelay);
Point where = loc.getPoint(c);
click(c, where.x, where.y, buttons, count);
waitForIdle();
}
/** Click on the component at the given location (mouse button 1).
*/
public void actionClick(Component comp, int x, int y) {
actionClick(comp, new ComponentLocation(new Point(x, y)));
}
/** Click on the component at the given location. The buttons mask
* should be the InputEvent masks for the desired button, e.g.
* {@link InputEvent#BUTTON1_MASK}. ComponentTester also defines
* {@link AWTConstants#POPUP_MASK} and {@link AWTConstants#TERTIARY_MASK} for
* platform-independent masks for those buttons. Key modifiers other
* than {@link InputEvent#ALT_MASK} and {@link InputEvent#META_MASK} may
* also be used as a convenience.
*/
public void actionClick(Component comp, int x, int y, int buttons) {
actionClick(comp, x, y, buttons, 1);
}
/** Click on the component at the given location, specifying buttons and
* the number of clicks. The buttons mask should be the InputEvent mask
* for the desired button, e.g.
* {@link InputEvent#BUTTON1_MASK}. ComponentTester also defines
* {@link AWTConstants#POPUP_MASK} and {@link AWTConstants#TERTIARY_MASK} for
* platform-independent masks for those buttons. Key modifiers other
* than {@link InputEvent#ALT_MASK} and {@link InputEvent#META_MASK} may
* also be used as a convenience.
*/
public void actionClick(Component comp, int x, int y,
int buttons, int count) {
actionClick(comp, new ComponentLocation(new Point(x, y)),
buttons, count);
}
/** Send a key press event for the given virtual key code to the given
Component.
*/
public void actionKeyPress(Component comp, int keyCode) {
actionFocus(comp);
actionKeyPress(keyCode);
}
/** Generate a key press event for the given virtual key code. */
public void actionKeyPress(int keyCode) {
keyPress(keyCode);
waitForIdle();
}
/** Generate a key release event sent to the given component. */
public void actionKeyRelease(Component comp, int keyCode) {
actionFocus(comp);
actionKeyRelease(keyCode);
}
/** Generate a key release event. */
public void actionKeyRelease(int keyCode) {
keyRelease(keyCode);
waitForIdle();
}
/** Set the state of the given modifier keys. */
public void actionSetModifiers(int mask, boolean pressed) {
setModifiers(mask, pressed);
waitForIdle();
}
/**
* Send the given keystroke, which must be the KeyEvent field name of a
* KeyEvent VK_ constant to the program. Sends a key down/up, with no
* modifiers. The focus is changed to the target component.
*/
public void actionKeyStroke(Component c, int keyCode) {
actionFocus(c);
actionKeyStroke(keyCode, 0);
}
/**
* Send the given keystroke, which must be the KeyEvent field name of a
* KeyEvent VK_ constant. Sends a key press and key release, with no
* modifiers. Note that this method does not affect the current focus.
*/
public void actionKeyStroke(int keyCode) {
actionKeyStroke(keyCode, 0);
}
/**
* Send the given keystroke, which must be the KeyEvent field name of a
* KeyEvent VK_ constant to the program. Sends a key down/up, with the
* given modifiers, which should be the InputEvent field name modifier
* masks optionally ORed together with "|". The focus is changed to the
* target component.<p>
*/
public void actionKeyStroke(Component c, int keyCode, int modifiers) {
actionFocus(c);
actionKeyStroke(keyCode, modifiers);
}
/**
* Send the given keystroke, which must be the KeyEvent field name of a
* KeyEvent VK_ constant to the program. Sends a key down/up, with the
* given modifiers, which should be the InputEvent field name modifier
* masks optionally ORed together with "|". Note that this does not
* affect the current focus.<p>
*/
public void actionKeyStroke(int keyCode, int modifiers) {
if (Bugs.hasKeyStrokeGenerationBug()) {
int oldDelay = getAutoDelay();
setAutoDelay(50);
key(keyCode, modifiers);
setAutoDelay(oldDelay);
delay(100);
}
else {
key(keyCode, modifiers);
}
waitForIdle();
}
/** Send events required to generate the given string on the given
* component. This version is preferred over
* {@link #actionKeyString(String)}.
*/
public void actionKeyString(Component c, String string) {
actionFocus(c);
actionKeyString(string);
}
/** Send events required to generate the given string. */
public void actionKeyString(String string) {
keyString(string);
// FIXME waitForIdle isn't always sufficient on OSX with key events
if (Bugs.hasKeyStrokeGenerationBug()) {
delay(100);
}
waitForIdle();
}
/** Set the focus on to the given component. */
public void actionFocus(Component comp) {
focus(comp, true);
}
/** Move the mouse/pointer to the given location. */
public void actionMouseMove(Component comp, ComponentLocation loc) {
Point where = loc.getPoint(comp);
mouseMove(comp, where.x, where.y);
waitForIdle();
}
/** Press mouse button 1 at the given location. */
public void actionMousePress(Component comp, ComponentLocation loc) {
actionMousePress(comp, loc, InputEvent.BUTTON1_MASK);
}
/** Press mouse buttons corresponding to the given mask at the given
location.
*/
public void actionMousePress(Component comp, ComponentLocation loc,
int mask) {
Point where = loc.getPoint(comp);
mousePress(comp, where.x, where.y, mask);
waitForIdle();
}
/** Release any currently held mouse buttons. */
public void actionMouseRelease() {
mouseRelease();
waitForIdle();
}
/** Perform a drag action. Derived classes may provide more specific
* identifiers for what is being dragged simply by deriving a new class
* from ComponentLocation which identifies the appropriate substructure.
* For instance, a {@link JTreeLocation} might encapsulate the expansion
* control location for the path [root, node A, child B].
*/
public void actionDrag(Component dragSource, ComponentLocation loc) {
actionDrag(dragSource, loc, "BUTTON1_MASK");
}
/** Perform a drag action. Grabs the center of the given component. */
public void actionDrag(Component dragSource) {
actionDrag(dragSource, new ComponentLocation());
}
/** Perform a drag action with the given modifiers.
* @param dragSource source of the drag
* @param loc identifies where on the given {@link Component} to begin the
* drag.
* @param buttons a <code>String</code> representation of key modifiers,
* e.g. "ALT|SHIFT", based on the {@link InputEvent#ALT_MASK InputEvent
* <code>_MASK</code> fields}.
* @deprecated Use the
* {@link #actionDrag(Component,ComponentLocation,int) integer modifier mask}
* version instead.
*/
public void actionDrag(Component dragSource, ComponentLocation loc,
String buttons) {
actionDrag(dragSource, loc, AWT.getModifiers(buttons));
}
/** Perform a drag action with the given modifiers.
* @param dragSource source of the drag
* @param loc identifies where on the given {@link Component} to begin the
* drag.
* @param buttons one or more of the
* {@link InputEvent#BUTTON1_MASK InputEvent <code>BUTTONN_MASK</code>
* fields}.
*/
public void actionDrag(Component dragSource, ComponentLocation loc,
int buttons) {
Point where = loc.getPoint(dragSource);
drag(dragSource, where.x, where.y, buttons);
waitForIdle();
}
/** Perform a drag action. Grabs at the given explicit location. */
public void actionDrag(Component dragSource, int sx, int sy) {
actionDrag(dragSource, new ComponentLocation(new Point(sx, sy)));
}
/** Perform a drag action. Grabs at the given location with the given
* modifiers.
* @param dragSource source of the drag
* @param sx X coordinate
* @param sy Y coordinate
* @param buttons a <code>String</code> representation of key modifiers,
* e.g. "ALT|SHIFT", based on the {@link InputEvent#ALT_MASK InputEvent
* <code>_MASK</code> fields}.
* @deprecated Use the
* {@link #actionDrag(Component,ComponentLocation,int) ComponentLocation/
* integer modifier mask} version instead.
*/
public void actionDrag(Component dragSource, int sx, int sy,
String buttons) {
actionDrag(dragSource, new ComponentLocation(new Point(sx, sy)),
buttons);
}
/** Drag the current dragged object over the given component. */
public void actionDragOver(Component target) {
actionDragOver(target, new ComponentLocation());
}
/** Drag the current dragged object over the given target/location. */
public void actionDragOver(Component target, ComponentLocation where) {
Point loc = where.getPoint(target);
dragOver(target, loc.x, loc.y);
waitForIdle();
}
/** Perform a basic drop action (implicitly causing preceding mouse
* drag motion). Drops in the center of the component.
*/
public void actionDrop(Component dropTarget) {
actionDrop(dropTarget, new ComponentLocation());
}
/** Perform a basic drop action (implicitly causing preceding mouse
* drag motion).
*/
public void actionDrop(Component dropTarget, ComponentLocation loc) {
Point where = loc.getPoint(dropTarget);
drop(dropTarget, where.x, where.y);
waitForIdle();
}
/** Perform a basic drop action (implicitly causing preceding mouse
* drag motion). The modifiers represents the set of active modifiers
* when the drop is made.
*/
public void actionDrop(Component dropTarget, int x, int y) {
drop(dropTarget, x, y);
waitForIdle();
}
/** Return whether the component's contents matches the given image. */
public boolean assertImage(Component comp, java.io.File fileImage,
boolean ignoreBorder) {
java.awt.image.BufferedImage img = capture(comp, ignoreBorder);
return new ImageComparator().compare(img, fileImage) == 0;
}
/** Returns whether a Window corresponding to the given String is
* showing. The string may be a plain String or regular expression and
* may match either the window title (for Frames or Dialogs) or the
* value of {@link Component#getName}.
*/
public boolean assertFrameShowing(Hierarchy h, String id) {
try {
ComponentFinder finder = new BasicFinder(h);
return finder.find(new WindowMatcher(id, true)) != null;
}
catch(ComponentNotFoundException e) {
return false;
}
catch(MultipleComponentsFoundException m) {
// Might not be the one you want, but that's what the docs say
return true;
}
}
/** Returns whether a Window corresponding to the given String is
* showing. The string may be a plain String or regular expression and
* may match either the window title (for Frames or Dialogs) or the value
* of {@link Component#getName}.
* @deprecated This method does not specify the proper context for the
* lookup. Use {@link #assertFrameShowing(Hierarchy,String)} instead.
*/
public boolean assertFrameShowing(String id) {
return assertFrameShowing(AWTHierarchy.getDefault(), id);
}
/** Convenience wait for a window to be displayed. The given string may
* be a plain String or regular expression and may match either the window
* title (for Frames and Dialogs) or the value of {@link Component#getName}.
* This method is provided as a convenience for hand-coded tests, since
* scripts will use a wait step instead.<p>
* The property <code>abbot.robot.component_delay</code> affects the
* default timeout.
*/
public void waitForFrameShowing(final Hierarchy h, final String identifier) {
wait(new Condition() {
public boolean test() {
return assertFrameShowing(h, identifier);
}
public String toString() {
return Strings.get("tester.Component.show_wait",
new Object[] { identifier });
}
}, componentDelay);
}
/** Convenience wait for a window to be displayed. The given string may
* be a plain String or regular expression and may match either the window
* title (for Frames and Dialogs) or the value of {@link Component#getName}.
* This method is provided as a convenience for hand-coded tests, since
* scripts will use a wait step instead.<p>
* The property abbot.robot.component_delay affects the default timeout.
* @deprecated This method does not provide sufficient context to reliably
* find a component. Use {@link #waitForFrameShowing(Hierarchy,String)}
* instead.
*/
public void waitForFrameShowing(final String identifier) {
waitForFrameShowing(AWTHierarchy.getDefault(), identifier);
}
/** Return whether the Component represented by the given
ComponentReference is available.
*/
public boolean assertComponentShowing(ComponentReference ref) {
try {
Component c = ref.getComponent();
return isReadyForInput(c);
}
catch(ComponentSearchException e) {
return false;
}
}
/** Wait for the Component represented by the given ComponentReference to
become available. The timeout is affected by
abbot.robot.component_delay, which defaults to 30s.
*/
public void waitForComponentShowing(final ComponentReference ref) {
wait(new Condition() {
public boolean test() {
return assertComponentShowing(ref);
}
public String toString() {
return Strings.get("tester.Component.show_wait",
new Object[] { ref });
}
}, componentDelay);
}
private Method[] cachedMethods = null;
/** Look up methods with the given prefix. Facilitates auto-scanning by
* scripts and the script editor.
*/
private Method[] getMethods(String prefix, Class returnType,
boolean componentArgument) {
if (cachedMethods == null) {
cachedMethods = getClass().getMethods();
}
ArrayList methods = new ArrayList();
// Only save one Method for each unique name
HashSet names = new HashSet(IGNORED_METHODS);
Method[] mlist = cachedMethods;
for (int i=0;i < mlist.length;i++) {
String name = mlist[i].getName();
if (names.contains(name) || !name.startsWith(prefix))
continue;
Class[] params = mlist[i].getParameterTypes();
if ((returnType == null
|| returnType.equals(mlist[i].getReturnType()))
&& ((params.length == 0 && !componentArgument)
|| (params.length > 0
&& (Component.class.isAssignableFrom(params[0])
== componentArgument)))) {
methods.add(mlist[i]);
names.add(name);
}
}
return (Method[])methods.toArray(new Method[methods.size()]);
}
private Method[] cachedActions = null;
/** Return a list of all actions defined by this class that don't depend
* on a component argument.
*/
public Method[] getActions() {
if (cachedActions == null) {
cachedActions = getMethods("action", void.class, false);
}
return cachedActions;
}
private Method[] cachedComponentActions = null;
/** Return a list of all actions defined by this class that require
* a component argument.
*/
public Method[] getComponentActions() {
if (cachedComponentActions == null) {
cachedComponentActions = getMethods("action", void.class, true);
}
return cachedComponentActions;
}
private Method[] cachedPropertyMethods = null;
/** Return an array of all property check methods defined by this class.
* The first argument <b>must</b> be a Component.
*/
public Method[] getPropertyMethods() {
if (cachedPropertyMethods == null) {
ArrayList all = new ArrayList();
all.addAll(Arrays.asList(getMethods("is", boolean.class, true)));
all.addAll(Arrays.asList(getMethods("has", boolean.class, true)));
all.addAll(Arrays.asList(getMethods("get", null, true)));
cachedPropertyMethods =
(Method[])all.toArray(new Method[all.size()]);
}
return cachedPropertyMethods;
}
private Method[] cachedAssertMethods = null;
/** Return a list of all assertions defined by this class that don't
* depend on a component argument.
*/
public Method[] getAssertMethods() {
if (cachedAssertMethods == null) {
cachedAssertMethods = getMethods("assert", boolean.class, false);
}
return cachedAssertMethods;
}
private Method[] cachedComponentAssertMethods = null;
/** Return a list of all assertions defined by this class that require a
* component argument.
*/
public Method[] getComponentAssertMethods() {
if (cachedComponentAssertMethods == null) {
cachedComponentAssertMethods =
getMethods("assert", boolean.class, true);
}
return cachedComponentAssertMethods;
}
/** Quick and dirty strip raw text from html, for getting the basic text
from html-formatted labels and buttons. Behavior is undefined for
badly formatted html.
*/
public static String stripHTML(String str) {
if (str != null
&& (str.startsWith("<html>")
|| str.startsWith("<HTML>"))) {
while (str.startsWith("<")) {
int right = str.indexOf(">");
if (right == -1)
break;
str = str.substring(right + 1);
}
while (str.endsWith(">")) {
int right = str.lastIndexOf("<");
if (right == -1)
break;
str = str.substring(0, right);
}
}
return str;
}
/** Wait for the given condition, throwing an ActionFailedException if it
* times out.
*/
protected void waitAction(String desc, Condition cond)
throws ActionFailedException {
try { Robot.wait(cond); }
catch(WaitTimedOutException wto) {
throw new ActionFailedException(desc);
}
}
/** Return the Component class that corresponds to this
* <tt>ComponentTester</tt>
* class. For example,
* <tt>JComponentTester.getTestedClass(JLabel.class)</tt>
* would return <tt>JComponent.class</tt>.
*/
public Class getTestedClass(Class cls) {
while (getTester(cls.getSuperclass()) == this) {
cls = cls.getSuperclass();
}
return cls;
}
/** Parse the String representation of a <tt>ComponentLocation</tt> into
* the actual <tt>ComponentLocation</tt> object.
*/
public ComponentLocation parseLocation(String encoded) {
return new ComponentLocation().parse(encoded);
}
/** Return a ComponentLocation for the given Point. Derived classes may
* provide something more suitable than an (x, y) coordinate. A
* {@link javax.swing.JTree}, for example, might provide a
* {@link JTreeLocation}
* indicating a path or row in the tree.
*/
public ComponentLocation getLocation(Component c, Point where) {
return new ComponentLocation(where);
}
private class AWTMenuListener implements AWTEventListener {
public volatile boolean eventFired;
public void eventDispatched(AWTEvent e) {
if (e.getID() == ActionEvent.ACTION_PERFORMED) {
eventFired = true;
}
}
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/ContainerTester.java
|
package abbot.tester;
/** Hierarchy placeholder for Container. Provides no additional user
* actions.
*/
public class ContainerTester extends ComponentTester {
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/DialogTester.java
|
package abbot.tester;
import java.awt.*;
public class DialogTester extends WindowTester {
/** Return a unique tag to help identify the given component. */
public String deriveTag(Component comp) {
// If the component class is custom, don't provide a tag
if (isCustom(comp.getClass()))
return null;
String tag = ((Dialog)comp).getTitle();
if (tag == null || "".equals(tag)) {
tag = super.deriveTag(comp);
}
return tag;
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/FailedException.java
|
package abbot.tester;
import java.awt.Component;
import java.awt.Frame;
import java.awt.KeyboardFocusManager;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.List;
/**
* An exception to note that a process has failed in Abbot and we want to presever
* the system state.
*/
public class FailedException
extends RuntimeException
{
public FailedException(Throwable cause) {
super(cause);
systemState = dumpSystemState();
}
public FailedException(String msg, Throwable cause) {
super(msg, cause);
if (cause instanceof FailedException) {
// Don't make a copy of the system state use the one in cause
// as that will be closer to where it happened
systemState = ((FailedException)cause).getSystemState();
}
else {
systemState = dumpSystemState();
}
}
public FailedException(String msg) {
super(msg);
systemState = dumpSystemState();
}
/**
* @return The a string which represents the state of the system at the time of the failure
* in particular thread conditions and the current swing tree.
*/
public String getSystemState()
{
return systemState;
}
@Override
public void printStackTrace(PrintWriter s)
{
super.printStackTrace(s);
s.print(systemState);
}
@Override
public void printStackTrace(PrintStream s)
{
super.printStackTrace(s);
s.print(systemState);
}
/**
* Dump the stacks at the point of failure
*/
private static String dumpSystemState()
{
StringWriter sw = new StringWriter();
PrintWriter ps = new PrintWriter(sw);
ps.println("\n\n[TOC Focus, AWT Tree, Stack Traces] \n\n");
// Stack traces
ps.println("\n\n[[[Dumping Focus]]] \n\n");
KeyboardFocusManager currentManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
Component next = currentManager.getFocusOwner();
List<Component> tree = new ArrayList<Component>();
while (next!=null) {
tree.add(0, next);
next = next.getParent();
}
ps.printf("Focus owner %s\nFocus root %s\n", tree, currentManager.getCurrentFocusCycleRoot());
ps.println("\n\n[[[Dumping Windows]]] \n\n");
for (Frame frame: Frame.getFrames())
{
ps.println("Dumping frame " + frame);
frame.list(ps, 2);
}
ps.println("\n\n[[[Dumping Stack Traces]]] \n\n");
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
for (ThreadInfo ti: threadMXBean.dumpAllThreads(true, true))
{
ps.print(ti);
// ThreadInfo only prints out the first n lines, so make sure
// we write out the rest
StackTraceElement ste[] = ti.getStackTrace();
if (ste.length > 8)
{
ps.println("[Extra stack]");
for (int element = 8; element < ste.length; element++)
{
ps.println("\tat " + ste[element]);
for (MonitorInfo mi : ti.getLockedMonitors()) {
if (mi.getLockedStackDepth() == element) {
ps.append("\t- locked " + mi);
ps.append('\n');
}
}
}
ps.println("[Extra stack]");
}
ps.println();
}
long deadlock[] = threadMXBean.findDeadlockedThreads();
if (deadlock != null && deadlock.length > 0)
{
ps.println("Deadlocked threads : ");
for (long d: deadlock)
{
ps.println(threadMXBean.getThreadInfo(d));
}
ps.println();
}
long monitorLocked[] = threadMXBean.findMonitorDeadlockedThreads();
if (monitorLocked != null && monitorLocked.length > 0)
{
ps.println("Monitor locked threads : ");
for (long d: monitorLocked)
{
ps.println(threadMXBean.getThreadInfo(d));
}
ps.println();
}
return sw.toString();
}
protected static String systemState;
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/FileComparator.java
|
package abbot.tester;
import java.io.*;
/**
* Compare two files or filenames. Original concept contributed by A. Smith
* Montebello.
* @author asmithmb
* @version 1.0
*/
public class FileComparator implements java.util.Comparator {
/**
* Read files into streams and call byte by byte comparison method
* @param f1 First File or filename to compare.
* @param f2 Second File or filename to compare.
*/
public int compare(Object f1, Object f2) {
if ((f1 == f2) || (f1 != null && f1.equals(f2)))
return 0;
// Call null < object
if (f1 == null)
return -1;
// Call object > null
if (f2 == null)
return 1;
File file1, file2;
if (f1 instanceof File) {
file1 = (File)f1;
}
else if (f1 instanceof String) {
file1 = new File((String)f1);
}
else {
throw new IllegalArgumentException("Expecting a File or String");
}
if (f2 instanceof File) {
file2 = (File)f2;
}
else if (f2 instanceof String) {
file2 = new File((String)f2);
}
else {
throw new IllegalArgumentException("Expecting a File or String");
}
if (file1.equals(file2)) {
return 0;
}
if (!file1.exists() || !file1.isFile()) {
throw new IllegalArgumentException("File '" + file1 + "' does not exist");
}
if (!file2.exists() || !file2.isFile()) {
throw new IllegalArgumentException("File '" + file2 + "' does not exist");
}
if (file1.length() != file2.length()) {
return (int)(file1.length() - file2.length());
}
InputStream is1 = null;
InputStream is2 = null;
try {
is1 = new BufferedInputStream(new FileInputStream(file1));
is2 = new BufferedInputStream(new FileInputStream(file2));
int b1 = -2;
int b2 = -2;
try {
while ((b1 = is1.read()) != -1
&& (b2 = is2.read()) != -1) {
if (b1 != b2)
return b1 - b2;
b1 = b2 = -2;
}
}
catch(IOException io) {
return b1 == -2 ? -1 : 1;
}
finally {
is1.close(); is1 = null;
is2.close(); is2 = null;
}
return 0;
}
catch(FileNotFoundException fnf) {
return is1 == null ? -1 : 1;
}
catch(IOException io) {
return is1 == null ? -1 : 1;
}
}
/** Comparators are equal if they're the same class. */
public boolean equals(Object obj) {
return obj == this
|| (obj != null && obj.getClass().equals(getClass()));
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/FileDialogTester.java
|
package abbot.tester;
import java.awt.*;
import java.awt.event.*;
import abbot.*;
import abbot.util.Bugs;
/**
* Tester for the java.awt.FileDialog.
*
* @author Vrata Venet, European Space Agency, Madrid-Spain ([email protected])
* @author Tim Wall (twall:users.sf.net)
* NOTE: different platforms do different things when the dialog is hidden.
* w32 returns null for the file if FileDialog.hide is invoked; other
* platforms may leave the file as is. OSX (as of 1.4.2) won't let you hide
* the dialog.
*/
public class FileDialogTester extends DialogTester {
/**
* This sets the file path for the fd
*/
public void actionSetFile(Component comp, final String file) {
if (null == file || "".equals(file))
throw new IllegalArgumentException("File name in FileDialog should be non-null and non-empty");
final FileDialog dialog = (FileDialog) comp;
invokeAndWait(new Runnable() {
public void run() {
dialog.setFile(file);
}
});
}
public void actionSetDirectory(Component comp, final String dir) {
if (null == dir || "".equals(dir))
throw new IllegalArgumentException("File name in FileDialog should be non-null and non-empty");
final FileDialog dialog = (FileDialog) comp;
invokeAndWait(new Runnable() {
public void run() {
dialog.setDirectory(dir);
}
});
}
/** Accept the currently selected file. */
public void actionAccept(Component comp){
Log.debug("accept");
final FileDialog fd = (FileDialog)comp;
final String file = fd.getFile();
if (file == null)
throw new ActionFailedException("No file selected");
// HACK:
// sun.awt.windows.WFileDialogPeer posts an InvocationEvent which sets
// the FileDialog's file to null when Dialog.hide is called.
// Install an event queue which can catch the posted event and ignore
// it. Only fully tested against sun.awt.windows.WFileDialogPeer.
FileDialogQueue queue = new FileDialogQueue();
// OSX disposes the FileDialog after hide, which is an event we
// can spot
fd.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
fd.setFile(file);
fd.removeWindowListener(this);
}
});
try {
fd.getToolkit().getSystemEventQueue().push(queue);
// 1.4.2 bug workaround: FileDialog.hide doesn't work
if (Bugs.fileDialogRequiresDismiss()) {
actionKeyStroke(KeyEvent.VK_ESCAPE);
}
invokeAndWait(new Runnable() {
public void run() {
fd.setVisible(false);
}
});
fd.setFile(file);
}
finally {
queue.dispose();
}
}
private class FileDialogQueue extends EventQueue {
private boolean disposed = false;
private boolean installed = false;
public void dispose() {
boolean remove = false;
synchronized(this) {
if (!disposed) {
disposed = true;
remove = true;
}
}
if (remove) {
try { pop(); }
catch(java.util.EmptyStackException e) {
Log.warn(e);
}
}
}
protected void dispatchEvent(AWTEvent e) {
synchronized(this) {
if (!installed) {
installed = true;
String name = Thread.currentThread().getName();
Thread.currentThread().setName(name + " (abbot FileDialogTester)");
}
}
// Ignore FileDialogPeer events while disposing the dialog
if (e.paramString().indexOf("FileDialogPeer") != -1) {
Log.debug("ignoring peer event: " + e);
// Nothing else to handle, restore the original queue
dispose();
}
else {
super.dispatchEvent(e);
}
}
}
/** Close the file dialog without selecting a file. */
public void actionCancel(Component comp) {
final FileDialog fd = (FileDialog)comp;
if (Platform.isOSX()) {
// bug in OSX 1.4.2: activate causes another dialog to appear!
//activate(fd);
// Assume dialog has focus
actionKeyStroke(KeyEvent.VK_ESCAPE);
}
else {
// the w32 native peer sets the file to null on dialog hide, but
// other platforms might not, so do it explicitly.
fd.setFile(null);
invokeAndWait(new Runnable() {
public void run() {
fd.setVisible(false);
}
});
}
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/FrameTester.java
|
package abbot.tester;
import java.awt.*;
public class FrameTester extends WindowTester {
/** Return a unique tag to help identify the given component. */
public String deriveTag(java.awt.Component comp) {
// If the component class is custom, don't provide a tag
if (isCustom(comp.getClass()))
return null;
String tag = ((java.awt.Frame)comp).getTitle();
if (tag == null || "".equals(tag)) {
tag = super.deriveTag(comp);
}
return tag;
}
/** Iconify the given Frame. */
public void actionIconify(Component comp) {
iconify((Frame)comp);
waitForIdle();
}
/** Deiconify the given Frame. */
public void actionDeiconify(Component comp) {
deiconify((Frame)comp);
waitForIdle();
}
/** Maximize the given Frame. */
public void actionMaximize(Component comp) {
maximize((Frame)comp);
waitForIdle();
}
/** Normalize the given Frame. Note that on 1.3.1 systems this may have
* no effect after a maximize.
*/
public void actionNormalize(Component comp) {
normalize((Frame)comp);
waitForIdle();
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/ImageComparator.java
|
package abbot.tester;
import abbot.InterruptedAbbotException;
import java.awt.Image;
import java.awt.image.*;
import java.io.*;
import javax.swing.ImageIcon;
import abbot.Log;
import java.net.URL;
import javax.imageio.ImageIO;
/**
This code expects the availability of the com.sun.image.codec.jpeg
extensions from the Sun JDK 1.3 or JRE.
Original comparison code contributed by asmithmb.
author: [email protected], twall
*/
public class ImageComparator implements java.util.Comparator {
public static String IMAGE_SUFFIX;
static {
// TODO: figure out how to do PNG stuff under 1.3 (w/o ImageIO)
try {
Class.forName("javax.imageio.ImageIO");
IMAGE_SUFFIX = ".png";
}
catch(ClassNotFoundException e) {
IMAGE_SUFFIX = ".jpg";
}
}
private static Image convertToImage(Object obj) throws IOException {
if (obj instanceof String) {
obj = new File((String)obj);
}
if (obj instanceof BufferedImage) {
// Convert to file and back to avoid unexplained
// memory-only BufferedImage differences
File tmp = File.createTempFile("ImageComparator", IMAGE_SUFFIX);
tmp.deleteOnExit();
writeImage(tmp, (BufferedImage)obj);
obj = tmp;
}
if (obj instanceof File) {
obj = new ImageIcon(((File)obj).toURI().toURL()).getImage();
}
if (obj instanceof URL) {
obj = new ImageIcon((URL)obj).getImage();
}
if (obj instanceof Image) {
return (Image)obj;
}
return null;
}
public static void writeImage(File file, BufferedImage img)
throws IOException {
if (".png".equals(IMAGE_SUFFIX))
writePNG(file, img);
else
writeJPEG(file, img);
}
public static void writePNG(File file, BufferedImage img)
throws IOException {
javax.imageio.ImageIO.write(img, "png", file);
}
/** Write the given buffered image to disk. */
public static void writeJPEG(File file, BufferedImage img)
throws IOException {
FileOutputStream os = new FileOutputStream(file);
// Replace code with JDK clean code
ImageIO.write(img, "jpeg", os);
os.close();
}
/**
Compare two images. May be BufferedImages or File arguments.
*/
public int compare(Object obj1, Object obj2) {
try {
obj1 = convertToImage(obj1);
}
catch(IOException io) {
throw new IllegalArgumentException("Object is not convertable to an Image: " + obj1);
}
try {
obj2 = convertToImage(obj2);
}
catch(IOException io) {
throw new IllegalArgumentException("Object is not convertable to an Image: " + obj2);
}
Log.debug("Comparing " + obj1 + " and " + obj2);
Image image1 = (Image)obj1;
int w = image1.getWidth(null);
int h = image1.getHeight(null);
Image image2 = (Image)obj2;
int w2 = image2.getWidth(null);
int h2 = image2.getHeight(null);
if (w*h != w2*h2) {
return w*h - w2*h2;
}
int[] pixels1 = new int[w*h];
int[] pixels2 = new int[w*h];
PixelGrabber pg1 = new PixelGrabber(image1, 0, 0, w, h, pixels1, 0, w);
PixelGrabber pg2 = new PixelGrabber(image2, 0, 0, w, h, pixels2, 0, w);
try {
pg1.grabPixels();
pg2.grabPixels();
for (int i=0;i < w*h;i++) {
if (pixels1[i] != pixels2[i]) {
return pixels1[i] - pixels2[i];
}
}
}
catch(InterruptedException e) {
throw new InterruptedAbbotException("Interrupted when comparing images");
}
return 0;
}
/** Comparators are equal if they're the same class. */
public boolean equals(Object obj) {
return obj == this
|| (obj != null && obj.getClass().equals(getClass()));
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/InputState.java
|
package abbot.tester;
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.lang.reflect.*;
import java.lang.ref.WeakReference;
import java.util.Stack;
import javax.swing.SwingUtilities;
import abbot.Log;
import abbot.util.*;
/** Class to keep track of a given input state. Includes mouse/pointer
* position and keyboard modifier key state.<p>
* Synchronization assumes that any given instance might be called from more
* than one event dispatch thread.<p>
* NOTE: Java 1.5 introduces MouseState, which provides current mouse coords
*/
// TODO: add a BitSet with the full keyboard key press state
public class InputState {
private static final int BUTTON_MASK = (MouseEvent.BUTTON1_MASK
|MouseEvent.BUTTON2_MASK
|MouseEvent.BUTTON3_MASK);
/** Current mouse position, in component coordinates. */
private Point mouseLocation = new Point(0, 0);
/** Current mouse position, in screen coordinates. */
private Point mouseLocationOnScreen = new Point(0, 0);
/** Keep a stack of mouse-entered components. Note that the pointer is
still considered within a frame when the mouse enters a contained
component.
*/
private Stack componentStack = new Stack();
private Stack locationStack = new Stack();
private Stack screenLocationStack = new Stack();
private int buttonsDown;
private int modifiersDown;
private long lastEventTime;
private int clickCount;
private Component dragSource;
private int dragX, dragY;
private EventNormalizer normalizer;
public InputState() {
long mask = MouseEvent.MOUSE_MOTION_EVENT_MASK
|MouseEvent.MOUSE_EVENT_MASK|KeyEvent.KEY_EVENT_MASK;
AWTEventListener listener = new SingleThreadedEventListener() {
protected void processEvent(AWTEvent event) {
update(event);
}
};
normalizer = new EventNormalizer();
normalizer.startListening(listener, mask);
}
public synchronized void clear() {
componentStack.clear();
locationStack.clear();
buttonsDown = 0;
modifiersDown = 0;
lastEventTime = 0;
clickCount = 0;
dragSource = null;
}
public void dispose() {
normalizer.stopListening();
normalizer = null;
}
/** Explicitly update the internal state. Allows Robot to update the
* state with events it has just posted.
*/
void update(AWTEvent event) {
if (event instanceof MouseEvent) {
updateState((MouseEvent)event);
}
else if (event instanceof KeyEvent) {
updateState((KeyEvent)event);
}
}
protected void updateState(KeyEvent ke) {
// Ignore "old" events
if (ke.getWhen() < lastEventTime)
return;
synchronized(this) {
setLastEventTime(ke.getWhen());
setModifiers(ke.getModifiers());
// FIXME add state of individual keys
}
}
protected void updateState(MouseEvent me){
// Ignore "old" events
if (me.getWhen() < lastEventTime) {
if (Log.isClassDebugEnabled(getClass()))
Log.debug("Ignoring " + Robot.toString(me));
return;
}
Point where = me.getPoint();
// getComponentAt and getLocationOnScreen want the tree lock, so be
// careful not to use any additional locks at the same time to avoid
// deadlock.
Point eventScreenLoc = null;
boolean screenLocationFound = true;
// Determine the current mouse position in screen coordinates
try {
eventScreenLoc = AWT.getLocationOnScreen(me.getComponent());
}
catch(IllegalComponentStateException e) {
// component might be hidden by the time we process this event
screenLocationFound = false;
}
synchronized(this) {
setLastEventTime(me.getWhen());
// When a button is released, only that button appears in the
// modifier mask
int whichButton = me.getModifiers() & BUTTON_MASK;
if (me.getID() == MouseEvent.MOUSE_RELEASED) {
buttonsDown &= ~whichButton;
modifiersDown &= ~whichButton;
}
else if (me.getID() == MouseEvent.MOUSE_PRESSED) {
buttonsDown |= whichButton;
modifiersDown |= whichButton;
}
clickCount = me.getClickCount();
if (me.getID() == MouseEvent.MOUSE_PRESSED) {
dragSource = me.getComponent();
dragX = me.getX();
dragY = me.getY();
}
else if (me.getID() == MouseEvent.MOUSE_RELEASED
|| me.getID() == MouseEvent.MOUSE_MOVED) {
dragSource = null;
}
if (me.getID() == MouseEvent.MOUSE_ENTERED) {
componentStack.push(new WeakReference(me.getComponent()));
locationStack.push(me.getPoint());
screenLocationStack.push(screenLocationFound
? eventScreenLoc : me.getPoint());
}
else if (me.getID() == MouseEvent.MOUSE_EXITED) {
if (componentStack.empty()) {
if (Log.isClassDebugEnabled(getClass()))
Log.debug("Got " + Robot.toString(me)
+ " but component not on stack");
}
else {
componentStack.pop();
locationStack.pop();
screenLocationStack.pop();
}
}
if (screenLocationFound) {
if (componentStack.empty()) {
mouseLocation = null;
}
else {
mouseLocation = new Point(where);
}
mouseLocationOnScreen.setLocation(eventScreenLoc);
mouseLocationOnScreen.translate(where.x, where.y);
}
}
}
/** Return the component under the given coordinates in the given parent
component. Events are often generated only for the outermost
container, so we have to determine if the pointer is actually within a
child. Basically the same as Component.getComponentAt, but recurses
to the lowest-level component instead of only one level. Point is in
component coordinates.<p>
The default Component.getComponentAt can return invisible components
(JRootPane has an invisible JPanel (glass pane?) which will otherwise
swallow everything).<p>
NOTE: getComponentAt grabs the TreeLock, so this should *only* be
invoked on the event dispatch thread, preferably with no other locks
held. Use it elsewhere at your own risk.<p>
NOTE: What about drags outside a component?
*/
public static Component getComponentAt(Component parent, Point p) {
Log.debug("Checking " + p + " in " + Robot.toString(parent));
Component c = SwingUtilities.getDeepestComponentAt(parent, p.x, p.y);
Log.debug("Deepest is " + Robot.toString(c));
return c;
}
/** Return the most deeply nested component which currently contains the
* pointer.
*/
public synchronized Component getUltimateMouseComponent() {
Component c = getMouseComponent();
if (c != null) {
Point p = getMouseLocation();
c = getComponentAt(c, p);
}
return c;
}
/** Return the last known Component to contain the pointer, or null if
none. Note that this may not correspond to the component that
actually shows up in AWTEvents.
*/
public synchronized Component getMouseComponent() {
Component comp = null;
if (!componentStack.empty()) {
WeakReference ref = (WeakReference)componentStack.peek();
comp = (Component)ref.get();
// Make sure we don't return a component that has gone away.
if (comp == null || !comp.isShowing()) {
Log.debug("Discarding unavailable component");
componentStack.pop();
locationStack.pop();
screenLocationStack.pop();
comp = getMouseComponent();
if (comp != null) {
mouseLocation = (Point)locationStack.peek();
mouseLocationOnScreen = (Point)screenLocationStack.peek();
}
}
}
if (Log.isClassDebugEnabled(getClass()))
Log.debug("Current component is " + Robot.toString(comp));
return comp;
}
public synchronized boolean isDragging() { return dragSource != null; }
public synchronized Component getDragSource() { return dragSource; }
public synchronized void setDragSource(Component c) {
dragSource = c;
}
public synchronized Point getDragOrigin() {
return new Point(dragX, dragY);
}
public synchronized int getClickCount() { return clickCount; }
protected synchronized void setClickCount(int count) {
clickCount = count;
}
public synchronized long getLastEventTime() { return lastEventTime; }
protected synchronized void setLastEventTime(long t) { lastEventTime = t; }
/** Returns all currently active modifiers. */
public synchronized int getModifiers() { return modifiersDown; }
protected synchronized void setModifiers(int m) { modifiersDown = m; }
/** Returns the currently pressed key modifiers. */
public synchronized int getKeyModifiers() {
return modifiersDown & ~BUTTON_MASK;
}
public synchronized int getButtons() { return buttonsDown; }
protected synchronized void setButtons(int b) { buttonsDown = b; }
/** Returns the mouse location relative to the component that currently
contains the pointer, or null if outside all components.
*/
public synchronized Point getMouseLocation() {
return mouseLocation != null ? new Point(mouseLocation) : null;
}
/** Returns the last known mouse location. */
public synchronized Point getMouseLocationOnScreen() {
return new Point(mouseLocationOnScreen);
}
/** Return whether there is a native drag/drop operation in progress. */
public boolean isNativeDragActive() {
try {
Class cls = Class.forName("sun.awt.dnd.SunDragSourceContextPeer");
Method m = cls.getMethod("checkDragDropInProgress");
try {
m.invoke(null);
return false;
}
catch(InvocationTargetException e) {
if (e.getTargetException() instanceof
InvalidDnDOperationException) {
return true;
}
}
}
catch(Exception e) {
}
return false;
}
}
|
0 |
java-sources/abbot/abbot/1.4.0/abbot
|
java-sources/abbot/abbot/1.4.0/abbot/tester/JButtonTester.java
|
package abbot.tester;
import javax.swing.JButton;
/**
* Provides action methods and assertions for {@link JButton}s.
*
* @author tlroche
* @version $Id: JButtonTester.java 1419 2005-01-05 18:34:48Z twall $
*/
public class JButtonTester extends AbstractButtonTester {
}
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 21