Jemmy2/0000755000175000017500000000000011572745222010774 5ustar tonytonyJemmy2/nbproject/0000755000175000017500000000000011572745222012762 5ustar tonytonyJemmy2/nbproject/build/0000755000175000017500000000000011572745222014061 5ustar tonytonyJemmy2/nbproject/build/classes/0000755000175000017500000000000011572745222015516 5ustar tonytonyJemmy2/nbproject/TEST-org.netbeans.jemmy.WaiterTest.xml0000644000175000017500000003013011064436407022053 0ustar tonytony Jemmy2/nbproject/nbproject/0000755000175000017500000000000011572745222014750 5ustar tonytonyJemmy2/nbproject/nbproject/ide-file-targets.xml0000644000175000017500000000400411064436407020613 0ustar tonytony Must set property 'run.class' Must set property 'debug.class' Jemmy2/nbproject/nbproject/project.xml0000644000175000017500000001527711446273577017165 0ustar tonytony org.netbeans.modules.ant.freeform JemmyNbProject JemmyNbProject ../build.xml ../src ../test . UTF-8 java ../src UTF-8 java ../test UTF-8 ../build/classes ../build/jemmy.jar compile javadoc test -Dtest.output=true clean clean compile run-selected-file-in-test run.class ../test \.java$ java-name debug-selected-file-in-test debug.class ../test \.java$ java-name version jar ../build/jemmy.jar compile folder ../build/classes compile ../src ../test ${ant.script} jar compile-tests ../src ../build/classes:../test ../build/jemmy.jar 1.5 ../test ../../lib/junit-4.1.jar:../src:../test:../build/classes ../build/classes 1.5 Jemmy2/nbproject/nbproject/private/0000755000175000017500000000000011572745222016422 5ustar tonytonyJemmy2/nbproject/TEST-${test}.xml0000644000175000017500000003061311064436407015675 0ustar tonytony java.lang.ClassNotFoundException: ${test} at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:316) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:280) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:374) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:164) Jemmy2/build.xml0000644000175000017500000001427611301504166012615 0ustar tonytony Jemmy2/src/0000755000175000017500000000000011572745222011563 5ustar tonytonyJemmy2/src/org/0000755000175000017500000000000011572745222012352 5ustar tonytonyJemmy2/src/org/netbeans/0000755000175000017500000000000011572745222014151 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/0000755000175000017500000000000011572745223015273 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/JemmyInputException.java0000644000175000017500000000564711245712237022126 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.awt.Component; /** * * Exception can be thrown as a result of incorrect input operations. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class JemmyInputException extends JemmyException { /** * Constructor. * @param comp Component regarding which exception is thrown. */ public JemmyInputException(Component comp) { super("Input exception", comp); } /** * Constructor. * @param message A descriptive message. * @param comp Component regarding which exception is thrown. */ public JemmyInputException(String message, Component comp) { super(message, comp); } /** * Returns component. * @return the Component associated with the exception. */ public Component getComponent() { return((Component)getObject()); } } Jemmy2/src/org/netbeans/jemmy/util/0000755000175000017500000000000011572745223016250 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/util/NameComponentChooser.java0000644000175000017500000000673711245712237023212 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import java.awt.Component; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.operators.Operator; /** * * Specifies criteria for component lookup basing on component name. * * By default uses new Operator.DefaultStringComparator(true, true) compa * * @author Nathan Paris (Nathan_Paris@adp.com) * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class NameComponentChooser implements ComponentChooser { private String name; private Operator.StringComparator comparator; /** * Creates an instance to search for a component by name. * @param name Expecten component name pattern. * @param comparator Comparator for a comparision of a component name with a pattern. */ public NameComponentChooser(String name, Operator.StringComparator comparator) { this.name = name; this.comparator = comparator; } /** * Creates an instance to search for a component by name using exact comparision. * @param name Expecten component name pattern. */ public NameComponentChooser(String name) { this(name, new Operator.DefaultStringComparator(true, true)); } public boolean checkComponent(Component component) { return(comparator.equals(component.getName(), name)); } public String getDescription() { return("Component having \"" + name + "\" name."); } } Jemmy2/src/org/netbeans/jemmy/util/Dumper.java0000644000175000017500000002720611245712237020352 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import java.awt.Component; import java.awt.Container; import java.awt.Frame; import java.awt.Window; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Hashtable; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.QueueTool.QueueAction; import org.netbeans.jemmy.operators.Operator; /** * Allows to "dump" current GUI state into XML file. * Uses operators' getDump methods to gather the information. * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class Dumper { /** * Prints XML DTD information. * @param writer a writer to write to. */ public static void printDTD(PrintWriter writer) { printDTD(writer, ""); } /** * Prints XML DTD information. * @param writer a stream to write to. */ public static void printDTD(PrintStream writer) { printDTD(new PrintWriter(writer)); } /** * Prints XML DTD information into file. * @param fileName a file to write to. * @throws FileNotFoundException */ public static void printDTD(String fileName) throws FileNotFoundException { printDTD(new PrintWriter(new FileOutputStream(fileName))); } /** * Prints component hierarchy (GUI dump) * starting from comp component. * @param comp a component to get information from. * @param writer a writer to write to. */ public static void dumpComponent(Component comp, final PrintWriter writer, final DumpController listener) { QueueTool qt = new QueueTool(); Component[] comps; if(comp != null) { comps = new Component[1]; comps[0] = comp; } else { comps = Frame.getFrames(); } final Component[] comps_final = comps; qt.invokeAndWait(new QueueAction("dumpComponent") { public Object launch() throws Exception { printHeader(writer); dumpSome("dump", comps_final, writer, "", listener); writer.flush(); return null; } }); } public static void dumpComponent(Component comp, PrintWriter writer) { dumpComponent(comp, writer, new DumpController() { public boolean onComponentDump(Component comp) { return(true); } public boolean onPropertyDump(Component comp, String name, String value) { return(true); } }); } /** * Prints component hierarchy (GUI dump). * starting from comp component. * @param comp a component to get information from. * @param writer a stream to write to. */ public static void dumpComponent(Component comp, PrintStream writer) { dumpComponent(comp, new PrintWriter(writer)); } public static void dumpComponent(Component comp, PrintStream writer, DumpController listener) { dumpComponent(comp, new PrintWriter(writer), listener); } /** * Prints component hierarchy (GUI dump) into file. * @param comp a component to get information from. * @param fileName a file to write to. * @throws FileNotFoundException */ public static void dumpComponent(Component comp, String fileName) throws FileNotFoundException { dumpComponent(comp, new PrintWriter(new FileOutputStream(fileName))); } public static void dumpComponent(Component comp, String fileName, DumpController listener) throws FileNotFoundException { dumpComponent(comp, new PrintWriter(new FileOutputStream(fileName)), listener); } /** * Prints all component hierarchy (GUI dump). * @param writer a writer to write to. */ public static void dumpAll(PrintWriter writer) { dumpComponent(null, writer); } public static void dumpAll(PrintWriter writer, DumpController listener) { dumpComponent(null, writer, listener); } /** * Prints all component hierarchy (GUI dump). * @param writer a stream to write to. */ public static void dumpAll(PrintStream writer) { dumpAll(new PrintWriter(writer)); } public static void dumpAll(PrintStream writer, DumpController listener) { dumpAll(new PrintWriter(writer), listener); } /** * Prints component hierarchy (GUI dump) into file. * @param fileName a file to write to. * @throws FileNotFoundException */ public static void dumpAll(String fileName) throws FileNotFoundException { dumpAll(new PrintWriter(new FileOutputStream(fileName))); } public static void dumpAll(String fileName, DumpController listener) throws FileNotFoundException { dumpAll(new PrintWriter(new FileOutputStream(fileName)), listener); } private static final String tabIncrease = " "; private static void printTagStart(PrintWriter writer, String tag, String tab) { writer.println(tab + "<" + tag + ">"); } private static void printTagOpening(PrintWriter writer, String tag, String tab) { writer.print(tab + "<" + tag); } private static void printTagClosing(PrintWriter writer, String tag) { writer.println(">"); } private static void printTagEnd(PrintWriter writer, String tag, String tab) { writer.println(tab + ""); } private static void printEmptyTagOpening(PrintWriter writer, String tag, String tab) { writer.print(tab + "<" + tag); } private static void printEmptyTagClosing(PrintWriter writer, String tag) { writer.println("/>"); } private static void dumpSome(String tag, Component[] comps, PrintWriter writer, String tab, DumpController listener) { if(comps.length > 0) { printTagStart(writer, tag, tab); for(int i = 0; i < comps.length; i++) { dumpOne(comps[i], writer, tab + tabIncrease, listener); } printTagEnd(writer, tag, tab); } } private static void dumpOne(Component component, PrintWriter writer, String tab, DumpController listener) { //whether to dump at all boolean toDump = listener.onComponentDump(component); if(toDump) { try { Operator oper = Operator.createOperator(component); Hashtable componentDump = oper.getDump(); printTagOpening(writer, "component", tab); writer.print(" operator=\"" + oper.getClass().getName() + "\""); printTagClosing(writer, "component"); Object[] keys = componentDump.keySet().toArray(); Arrays.sort(keys); String name, value; for(int i = 0; i < keys.length; i++) { name = (String)keys[i]; value = ((String)componentDump.get(keys[i])); if(listener.onPropertyDump(component, name, value)) { printEmptyTagOpening(writer, "property", tab + tabIncrease); writer.print(" name=\"" + escape(name) + "\" value=\"" + escape(value) + "\""); printEmptyTagClosing(writer, "property"); } } } catch(Exception e) { JemmyProperties.getCurrentOutput().printStackTrace(e); printTagStart(writer, "component", tab); printEmptyTagOpening(writer, "exception", tab + tabIncrease); writer.print(" toString=\"" + escape(e.toString()) + "\""); printEmptyTagClosing(writer, "exception"); } } if(component instanceof Window) { dumpSome("subwindows", ((Window)component).getOwnedWindows(), writer, tab + tabIncrease, listener); } if(component instanceof Container) { dumpSome("subcomponents", ((Container)component).getComponents(), writer, tab + tabIncrease, listener); } if(toDump) { printTagEnd(writer, "component", tab); } } private static void printHeader(PrintWriter writer) { writer.println(""); writer.println(""); } private static void printDTD(PrintWriter writer, String tab) { writer.println(tab + ""); writer.println(tab + ""); writer.println(tab + ""); writer.println(tab + ""); writer.println(tab + ""); writer.println(tab + ""); writer.println(tab + ""); writer.println(tab + ""); writer.println(tab + ""); } public static String escape(String str) { return str.replaceAll("&", "&").replaceAll("<", "<") .replaceAll(">", ">").replaceAll("\"", """); } } Jemmy2/src/org/netbeans/jemmy/util/WindowJob.java0000644000175000017500000000530711245712237021016 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import java.awt.Component; import org.netbeans.jemmy.Action; import org.netbeans.jemmy.ComponentChooser; /** * * Supposed to be used to perform some periodical job. * * @see WindowManager * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface WindowJob extends ComponentChooser, Action { /** * Perform necessary actions. */ public Object launch(Object obj); /** * Checks if window is what we want to do something with. */ public boolean checkComponent(Component comp); /** * Job description. */ public String getDescription(); } Jemmy2/src/org/netbeans/jemmy/util/DumpController.java0000644000175000017500000000443611064436407022070 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.jemmy.util; import java.awt.Component; /** * * @author shura */ public interface DumpController { public boolean onComponentDump(Component comp); public boolean onPropertyDump(Component comp, String name, String value); } Jemmy2/src/org/netbeans/jemmy/util/RegExComparator.java0000644000175000017500000001571011245712237022155 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import java.lang.reflect.InvocationTargetException; import org.netbeans.jemmy.ClassReference; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.operators.Operator.StringComparator; /** * Be executed under 1.4 uses java.util.regex.Pattern functionality. * Otherwise understands only "." and "*" simbols, i.e. regexprs like ".*Ques.ion.*". */ public class RegExComparator implements StringComparator { private static final int ANY_SIMBOL = -1; private static final int IGNORE_SIMBOL = -999; public boolean equals(String caption, String match) { if(match == null) { return(true); } if(caption == null) { return(false); } if(System.getProperty("java.specification.version").compareTo("1.3") > 0) { try { Object result = new ClassReference("java.util.regex.Pattern"). invokeMethod("matches", new Object[] {match, (caption == null) ? "" : caption}, new Class[] {String.class, Class.forName("java.lang.CharSequence")}); return(((Boolean)result).booleanValue()); } catch(InvocationTargetException e) { throw(new JemmyException("Exception during regexpr using", e)); } catch(ClassNotFoundException e) { throw(new JemmyException("Exception during regexpr using", e)); } catch(NoSuchMethodException e) { throw(new JemmyException("Exception during regexpr using", e)); } catch(IllegalAccessException e) { throw(new JemmyException("Exception during regexpr using", e)); } } else { return(parse(new String(caption), new String(match))); } } /** * Checks that caption matshes the pattern. * Understands only "." (any symbol) and "*" (repeat symbol). * Used for 1.3 and earclier javas, starting from 1.4 * java.util.regex.Pattern class is used. * @param caption a caption to compare with the pattern. * @param match a pattern * @return true if the caption matches the pattern. */ public boolean parse(String caption, String match) { if(match.length() == 0 && caption.length() == 0) { return(true); } else if(match.length() == 0) { return(false); } int c0 = match.charAt(0); int c1 = IGNORE_SIMBOL; if(match.length() > 1) { c1 = match.charAt(1); } int shift = 1; switch(c0) { case '\\': if(match.length() == 1) { throw(new RegExParsingException("\\ is not appropriate")); } c0 = match.charAt(1); if(match.length() > 2) { c1 = match.charAt(2); } else { c1 = IGNORE_SIMBOL; } shift = 2; break; case '.': c0 = ANY_SIMBOL; break; case '*': throw(new RegExParsingException("* is not appropriate")); } if(c1 == '*') { shift = shift + 1; int i = 0; while(i <= caption.length()) { if(i == 0 || checkOne(caption.substring(i-1), c0)) { if(parse(caption.substring(i), match.substring(shift))) { return(true); } } else { return(false); } i++; } return(false); } else { if(caption.length() == 0) { return(false); } if(checkOne(caption, c0)) { return(parse(caption.substring(1), match.substring(shift))); } else { return(false); } } } private boolean checkOne(String caption, int simbol) { return(simbol == ANY_SIMBOL || simbol == caption.charAt(0)); } /** * Thrown in case of parsing error. */ public static class RegExParsingException extends JemmyException { /** * Constructs a RegExComparator$RegExParsingException object. * @param message an error message */ public RegExParsingException(String message) { super(message); } /** * Constructs a RegExComparator$RegExParsingException object. * @param message an error message * @param innerException a parsing exception. */ public RegExParsingException(String message, Exception innerException) { super(message, innerException); } } } Jemmy2/src/org/netbeans/jemmy/util/PropChooser.java0000644000175000017500000001662411245712237021363 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import java.awt.Component; import java.lang.reflect.InvocationTargetException; import org.netbeans.jemmy.ClassReference; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; /** * * Implementation of org.netbeans.jemmy.ComponentChooser interface. * Class can be used to find component by its field/methods values.
* Example: *
 * 	    String[] methods = {"getClientProperty"};
 * 	    Object[][] params = {{"classname"}};
 * 	    Class[][] classes = {{Object.class}};
 * 	    Object[] results = {"javax.swing.JCheckBox"};
 * 
 * 	    JCheckBox box = JCheckBoxOperator.findJCheckBox(frm0, new PropChooser(methods, params, classes, results));
 * 
* Or: *
 * 	    String[] methods = {"getText"};
 * 	    Object[] results = {"Open"};
 * 
 * 	    JButtonOperator box = new JButtonOperator(containerOperator, new PropChooser(fields, results));
 * 
* * @author Alexandre Iline (alexandre.iline@sun.com) */ public class PropChooser implements ComponentChooser, Outputable{ /** * Names of methods to check. */ protected String[] propNames; /** * Methods parameters. */ protected Object[][] params; /** * Classes of parameters. */ protected Class[][] classes; /** * Expected results of methods. */ protected Object[] results; private TestOut output; /** * Constructs a PropChooser object. * @param propNames Names of methods/fields * @param params Parameters values for methods.
* params[0] is an array of parameters for propNames[0] methods.
* If propNames[0] is a field, params[0] is ignored. * @param classes Parameters classes. * @param results Objects to compare method/field values to.
* A value of propNames[0] method/field should be equal to results[0] object. */ public PropChooser(String[] propNames, Object[][] params, Class[][] classes, Object[] results) { this.propNames = propNames; this.results = results; if(params != null) { this.params = params; } else { this.params = new Object[propNames.length][0]; } if(classes != null) { this.classes = classes; } else { this.classes = new Class[this.params.length][0]; for(int i = 0; i < this.params.length; i++) { Class[] clsss = new Class[this.params[i].length]; for(int j = 0; j < this.params[i].length; j++) { clsss[j] = this.params[i][j].getClass(); } this.classes[i] = clsss; } } setOutput(JemmyProperties.getCurrentOutput()); } /** * Constructs a PropChooser object for checking of methods * with no parameters. * @param propNames Names of methods/fields * @param results Objects to compare method/field values to. */ public PropChooser(String[] propNames, Object[] results) { this(propNames, null, null, results); } public void setOutput(TestOut output) { this.output = output; } public TestOut getOutput() { return(output); } public boolean checkComponent(Component comp) { try { String propName = null; Object value; ClassReference disp = new ClassReference(comp); for(int i = 0; i < propNames.length; i++) { propName = propNames[i]; if(propName != null) { if(isField(comp, propName, classes[i])) { try { value = disp.getField(propName); } catch(IllegalStateException e) { output.printStackTrace(e); return(false); } catch(NoSuchFieldException e) { output.printStackTrace(e); return(false); } catch(IllegalAccessException e) { output.printStackTrace(e); return(false); } } else { try { value = disp.invokeMethod(propName, params[i], classes[i]); } catch(InvocationTargetException e) { output.printStackTrace(e); return(false); } catch(IllegalStateException e) { output.printStackTrace(e); return(false); } catch(NoSuchMethodException e) { output.printStackTrace(e); return(false); } catch(IllegalAccessException e) { output.printStackTrace(e); return(false); } } if(!checkProperty(value, results[i])) { return(false); } } } return(true); } catch (SecurityException e) { output.printStackTrace(e); return(false); } } public String getDescription() { String result = ""; for(int i = 0; i < propNames.length; i++) { result = result + " " + propNames[i]; } return("Component by properties array\n :" + result); } /** * Method to check one method result with an etalon. * Can be overrided by a subclass. * @param value Method/field value * @param etalon Object to compare to. * @return true if the value matches the etalon. */ protected boolean checkProperty(Object value, Object etalon) { return(value.equals(etalon)); } /* try to define if propName is a field or method*/ private boolean isField(Component comp, String propName, Class[] params) throws SecurityException { try { comp.getClass().getField(propName); comp.getClass().getMethod(propName, params); } catch(NoSuchMethodException e) { return(true); } catch(NoSuchFieldException e) { return(false); } return(true); } } Jemmy2/src/org/netbeans/jemmy/util/WindowManager.java0000644000175000017500000001327311245712237021657 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import java.awt.Component; import java.awt.Dialog; import java.awt.Window; import java.util.Vector; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.WindowWaiter; import org.netbeans.jemmy.operators.WindowOperator; /** * Class allows to make periodical window jobs like error window closing. * @see WindowJob * @author Alexandre Iline (alexandre.iline@sun.com) */ public class WindowManager implements Timeoutable, Outputable { /** * Default value for WindowManager.TimeDelta timeout. */ private static long TIME_DELTA = 1000; private static WindowManager manager; private Vector jobs; private Timeouts timeouts; private TestOut output; private WindowManager() { super(); setTimeouts(JemmyProperties.getCurrentTimeouts()); setOutput(JemmyProperties.getCurrentOutput()); jobs = new Vector(); } /** * Adds job to list. * @param job a job to perform. */ public static void addJob(WindowJob job) { manager.add(job); } /** * Removes job from list. * @param job a job to remove. */ public static void removeJob(WindowJob job) { manager.remove(job); } public static void performJob(WindowJob job) { while(manager.performJobOnce(job)) { } } static { Timeouts.initDefault("WindowManager.TimeDelta", TIME_DELTA); manager = new WindowManager(); } public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut output) { this.output = output; } public TestOut getOutput() { return(output); } /** * Adds job to list. * @param job a job to perform. */ public void add(WindowJob job) { output.printLine("Starting job \"" + job.getDescription() + "\""); synchronized(jobs) { JobThread thread = new JobThread(job); jobs.add(thread); thread.start(); } } /** * Removes job from list. * @param job a job to remove. */ public void remove(WindowJob job) { output.printLine("Killing job \"" + job.getDescription() + "\""); synchronized(jobs) { for(int i = 0; i < jobs.size(); i++) { if(((JobThread)jobs.get(i)).job == job) { ((JobThread)jobs.get(i)).needStop = true; jobs.remove(i); } } } } private boolean performJobOnce(WindowJob job) { Window win = WindowWaiter.getWindow(job); if(win != null) { job.launch(win); return(true); } else { return(false); } } public static class ModalDialogChoosingJob implements WindowJob { public boolean checkComponent(Component comp) { return(comp instanceof Dialog && ((Dialog)comp).isModal()); } public Object launch(Object obj) { new WindowOperator((Window)obj).close(); return(null); } public String getDescription() { return("A job of closing modal dialogs"); } } private static class JobThread extends Thread { WindowJob job; boolean needStop = false; public JobThread(WindowJob job) { this.job = job; } private boolean getNS() { synchronized(this) { return(needStop); } } public void run() { while(!getNS()) { manager.performJobOnce(job); manager.timeouts.sleep("WindowManager.TimeDelta"); } } } } Jemmy2/src/org/netbeans/jemmy/util/MouseVisualizer.java0000644000175000017500000001445111245712347022264 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import java.awt.Dialog; import java.awt.Frame; import java.awt.Point; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.input.MouseRobotDriver; import org.netbeans.jemmy.operators.Operator; import org.netbeans.jemmy.operators.WindowOperator; /** * * Does super.activate(org.netbeans.jemmy.operators.WindowOperator). * Then, if java version is appropriate (1.3 or later) activates windows by robot mouse click on border. * * @see org.netbeans.jemmy.operators.Operator#setVisualizer(Operator.ComponentVisualizer) * @see org.netbeans.jemmy.operators.Operator.ComponentVisualizer * *

Timeouts used:
* MouseVisualiser.BeforeClickTimeout - time to let a window manager to move a window as it wants
* * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class MouseVisualizer extends DefaultVisualizer { private static final long BEFORE_CLICK = 100; /** * A constant used to inform that window activating click * needs to performed on the top side of frame. * @see #MouseVisualizer() */ public static int TOP = 0; /** * A constant used to inform that window activating click * needs to performed on the botton side of frame. * @see #MouseVisualizer() */ public static int BOTTOM = 1; /** * A constant used to inform that window activating click * needs to performed on the left side of frame. * @see #MouseVisualizer() */ public static int LEFT = 2; /** * A constant used to inform that window activating click * needs to performed on the right side of frame. * @see #MouseVisualizer() */ public static int RIGHT = 3; private int place = 0; private double pointLocation = 0; private int depth = 0; /** * Creates a visualizer which clicks on (0, 0) window coords. */ public MouseVisualizer() { } /** * Creates a visualizer which clicks on window boder. * In case if place == BOTTOM, for example * clicks on (width * pointLocation, height - depth) coordinates. * @param place One of the predefined value: TOP, BOTTOM, LEFT, RIGHT * @param pointLocation Proportial coordinates to click. * @param depth Distance from the border. * @param checkMouse Check if there is any java component under mouse (currently ignored) */ public MouseVisualizer(int place, double pointLocation, int depth, boolean checkMouse) { this.place = place; this.pointLocation = pointLocation; this.depth = depth; } static { Timeouts.initDefault("MouseVisualiser.BeforeClickTimeout", BEFORE_CLICK); } protected boolean isWindowActive(WindowOperator winOper) { return(super.isWindowActive(winOper) && (winOper.getSource() instanceof Frame || winOper.getSource() instanceof Dialog)); } protected void makeWindowActive(WindowOperator winOper) { JemmyProperties.getCurrentTimeouts(). create("MouseVisualiser.BeforeClickTimeout").sleep(); super.makeWindowActive(winOper); if(!System.getProperty("java.version").startsWith("1.2")) { Point p = getClickPoint(winOper); new MouseRobotDriver(winOper.getTimeouts().create("EventDispatcher.RobotAutoDelay")). clickMouse(winOper, p.x, p.y, 1, winOper.getDefaultMouseButton(), 0, winOper.getTimeouts().create("ComponentOperator.MouseClickTimeout")); } } private Point getClickPoint(WindowOperator win) { int x, y; if(place == LEFT || place == RIGHT) { y = ((int)(win.getHeight() * pointLocation - 1)); if(place == RIGHT) { x = win.getWidth() - 1 - depth; } else { x = depth; } } else { x = ((int)(win.getWidth() * pointLocation - 1)); if(place == BOTTOM) { y = win.getHeight() - 1 - depth; } else { y = depth; } } if(x < 0) { x = 0; } if(x >= win.getWidth()) { x = win.getWidth() - 1; } if(y < 0) { y = 0; } if(y >= win.getHeight()) { y = win.getHeight() - 1; } return(new Point(x, y)); } } Jemmy2/src/org/netbeans/jemmy/util/package.html0000644000175000017500000000054711064436407020534 0ustar tonytony Util package

Util package

Contains different util classes and additional implementations of some Jemmy interfaces.
@since 02/28/2002
Jemmy2/src/org/netbeans/jemmy/util/StringPropChooser.java0000644000175000017500000002721311245712304022541 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import java.util.StringTokenizer; import org.netbeans.jemmy.operators.Operator.DefaultStringComparator; import org.netbeans.jemmy.operators.Operator.StringComparator; /** * * Implementation of org.netbeans.jemmy.ComponentChooser interface. * Class can be used to find component by its field/methods values converted to String.
* * Example: *
 *	    JLabel label = JLabelOperator.findJLabel(frm0, new StringPropChooser("getText=JLabel",
 *										 false, true));
 * 
* @author Alexandre Iline (alexandre.iline@sun.com) */ public class StringPropChooser extends PropChooser{ private StringComparator comparator; /** * Constructs a StringPropChooser object. * @param propNames Names of methods/fields * @param params Parameters values for methods.
* @param classes Parameters classes. * @param results Objects to compare converted to String method/field values to. * @param comparator Defines string comparision criteria. */ public StringPropChooser(String[] propNames, Object[][] params, Class[][] classes, String[] results, StringComparator comparator) { super(propNames, params, classes, results); this.comparator = comparator; } /** * Constructs a StringPropChooser object. * @param propNames Names of methods/fields * @param params Parameters values for methods.
* @param classes Parameters classes. * @param results Objects to compare converted to String method/field values to. * @param ce Compare exactly.
* If true, compare exactly (.toString().equals())
* If false, compare as substring (.toString().indexOf() != -1) * @param ccs Compare case sensitive.
* if false convert both .toString() and to uppercase before comparison. */ public StringPropChooser(String[] propNames, Object[][] params, Class[][] classes, String[] results, boolean ce, boolean ccs) { this(propNames, params, classes, results, new DefaultStringComparator(ce, ccs)); } /** * Constructs a StringPropChooser object. * @param propNames Names of methods/fields * @param results Objects to compare converted to String method/field values to. * @param comparator Defines string comparision criteria. */ public StringPropChooser(String[] propNames, String[] results, StringComparator comparator) { this(propNames, (Object[][])null, (Class[][])null, results, comparator); } /** * Constructs a StringPropChooser object. * @param propNames Names of methods/fields * @param results Objects to compare converted to String method/field values to. * @param ce Compare exactly. * @param ccs Compare case sensitive. * @deprecated Use constructors with StringComparator parameters. */ public StringPropChooser(String[] propNames, String[] results, boolean ce, boolean ccs) { this(propNames, (Object[][])null, (Class[][])null, results, ce, ccs); } /** * Constructs a StringPropChooser object. * @param props Method/field names && values
* Like "getText=button;isVisible=true" * @param semicolonChar Method(field) names separator. * @param equalChar Method(field) name - expected value separator. * @param params Parameters values for methods. * @param classes Parameters classes. * @param comparator Defines string comparision criteria. */ public StringPropChooser(String props, String semicolonChar, String equalChar, Object[][] params, Class[][] classes, StringComparator comparator) { this(cutToArray(props, semicolonChar, equalChar, true), params, classes, cutToArray(props, semicolonChar, equalChar, false), comparator); } /** * Constructs a StringPropChooser object. * @param props Method/field names && values
* Like "getText=button;isVisible=true" * @param semicolonChar Method(field) names separator. * @param equalChar Method(field) name - expected value separator. * @param params Parameters values for methods. * @param classes Parameters classes. * @param ce Compare exactly. * @param ccs Compare case sensitive. * @deprecated Use constructors with StringComparator parameters. */ public StringPropChooser(String props, String semicolonChar, String equalChar, Object[][] params, Class[][] classes, boolean ce, boolean ccs) { this(cutToArray(props, semicolonChar, equalChar, true), params, classes, cutToArray(props, semicolonChar, equalChar, false), ce, ccs); } /** * Constructs a StringPropChooser object. * @param props Method/field names && values * @param semicolonChar Method(field) names separator. * @param equalChar Method(field) name - expected value separator. * @param comparator Defines string comparision criteria. */ public StringPropChooser(String props, String semicolonChar, String equalChar, StringComparator comparator) { this(props, semicolonChar, equalChar, (Object[][])null, (Class[][])null, comparator); } /** * Constructs a StringPropChooser object. * @param props Method/field names && values * @param semicolonChar Method(field) names separator. * @param equalChar Method(field) name - expected value separator. * @param ce Compare exactly. * @param ccs Compare case sensitive. * @deprecated Use constructors with StringComparator parameters. */ public StringPropChooser(String props, String semicolonChar, String equalChar, boolean ce, boolean ccs) { this(props, semicolonChar, equalChar, (Object[][])null, (Class[][])null, ce, ccs); } /** * Constructs a StringPropChooser object. * @param props Method/field names && values
* ";" is used as a method(field) names separator.
* "=" is used as a method(field) name - expected value separator. * @param params Parameters values for methods. * @param classes Parameters classes. * @param comparator Defines string comparision criteria. */ public StringPropChooser(String props, Object[][] params, Class[][] classes, StringComparator comparator) { this(props, ";", "=", params, classes, comparator); } /** * Constructs a StringPropChooser object. * @param props Method/field names && values
* ";" is used as a method(field) names separator.
* "=" is used as a method(field) name - expected value separator. * @param params Parameters values for methods. * @param classes Parameters classes. * @param ce Compare exactly. * @param ccs Compare case sensitive. * @deprecated Use constructors with StringComparator parameters. */ public StringPropChooser(String props, Object[][] params, Class[][] classes, boolean ce, boolean ccs) { this(props, ";", "=", params, classes, ce, ccs); } /** * Constructs a StringPropChooser object. * @param props Method/field names && values * ";" is used as a method(field) names separator.
* "=" is used as a method(field) name - expected value separator. * @param comparator Defines string comparision criteria. */ public StringPropChooser(String props, StringComparator comparator) { this(props, (Object[][])null, (Class[][])null, comparator); } /** * Constructs a StringPropChooser object. * @param props Method/field names && values * ";" is used as a method(field) names separator.
* "=" is used as a method(field) name - expected value separator. * @param ce Compare exactly. * @param ccs Compare case sensitive. * @deprecated Use constructors with StringComparator parameters. */ public StringPropChooser(String props, boolean ce, boolean ccs) { this(props, (Object[][])null, (Class[][])null, ce, ccs); } /** * @see org.netbeans.jemmy.ComponentChooser */ public String getDescription() { String result = ""; for(int i = 0; i < propNames.length; i++) { if(!result.equals("")) { result = result + ";"; } result = result + propNames[i] + "=" + (String)results[i]; } return("Component by properties array\n : " + result); } /** * Method to check property. * Compares "value".toString() to (String)etalon according ce and ccs constructor parameters. * @param value Method/field value * @param etalon Object to compare to. * @return true if the value matches the etalon. */ protected boolean checkProperty(Object value, Object etalon) { return(comparator.equals(value.toString(), (String)etalon)); } /*split string to array*/ private static String[] cutToArray(String resources, String semicolon, String equal, boolean names) { StringTokenizer token = new StringTokenizer(resources, semicolon); String[] props = new String[token.countTokens()]; String nextProp; int ind = 0; while(token.hasMoreTokens()) { nextProp = token.nextToken(); StringTokenizer subtoken = new StringTokenizer(nextProp, equal); if(subtoken.countTokens() == 2) { props[ind] = subtoken.nextToken(); if(!names) { props[ind] = subtoken.nextToken(); } } else { props[ind] = null; } ind++; } return(props); } } Jemmy2/src/org/netbeans/jemmy/util/EmptyVisualizer.java0000644000175000017500000000523311245712237022266 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.Operator; import org.netbeans.jemmy.operators.Operator.ComponentVisualizer; /** * * Being used bas visualizer does nothing. * * @see org.netbeans.jemmy.operators.Operator#setVisualizer(Operator.ComponentVisualizer) * @see org.netbeans.jemmy.operators.Operator.ComponentVisualizer * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class EmptyVisualizer implements ComponentVisualizer { public void makeVisible(ComponentOperator compOper) { } } Jemmy2/src/org/netbeans/jemmy/util/AbstractTextStyleChooser.java0000644000175000017500000000643511245712237024073 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.StyledDocument; import org.netbeans.jemmy.operators.JTextComponentOperator.TextChooser; /** * Makes easier to implement searching criteria for javax.swing.text.StyledDocument * JTextComponentOperator.getPositionByText(String, JTextComponentOperator.TextChooser, int). * * @author Alexandre Iline (alexandre.iline@sun.com) */ public abstract class AbstractTextStyleChooser implements TextChooser { /** * Constructor. */ public AbstractTextStyleChooser() { } /** * Should return true if position fulfils criteria. * @param doc a styled document to be searched. * @param element an element to be checked. * @param offset checked position. * @return true if position fits the criteria. */ public abstract boolean checkElement(StyledDocument doc, Element element, int offset); public abstract String getDescription(); public final boolean checkPosition(Document document, int offset) { return(checkElement(((StyledDocument)document), ((StyledDocument)document).getCharacterElement(offset), offset)); } } Jemmy2/src/org/netbeans/jemmy/util/PNGDecoder.java0000644000175000017500000001774611245712237021040 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.DataFormatException; import java.util.zip.Inflater; import org.netbeans.jemmy.JemmyException; /** * Allows to load PNG graphical file. * @author Alexandre Iline */ public class PNGDecoder extends Object { InputStream in; /** * Constructs a PNGDecoder object. * @param in input stream to read PNG image from. */ public PNGDecoder(InputStream in) { this.in = in; } byte read() throws IOException { byte b = (byte)in.read(); return(b); } int readInt() throws IOException { byte b[] = read(4); return(((b[0]&0xff)<<24) + ((b[1]&0xff)<<16) + ((b[2]&0xff)<<8) + ((b[3]&0xff))); } byte[] read(int count) throws IOException { byte[] result = new byte[count]; for(int i = 0; i < count; i++) { result[i] = read(); } return(result); } boolean compare(byte[] b1, byte[] b2) { if(b1.length != b2.length) { return(false); } for(int i = 0; i < b1.length; i++) { if(b1[i] != b2[i]) { return(false); } } return(true); } void checkEquality(byte[] b1, byte[] b2) { if(!compare(b1, b2)) { throw(new JemmyException("Format error")); } } /** * Decodes image from an input stream passed into constructor. * @return a BufferedImage object * @throws IOException */ public BufferedImage decode() throws IOException { byte[] id = read(12); checkEquality(id, new byte[] {-119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13}); byte[] ihdr = read(4); checkEquality(ihdr, "IHDR".getBytes()); int width = readInt(); int height = readInt(); BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); byte[] head = read(5); int mode; if(compare(head, new byte[]{1, 0, 0, 0, 0})) { mode = PNGEncoder.BW_MODE; } else if(compare(head, new byte[]{8, 0, 0, 0, 0})) { mode = PNGEncoder.GREYSCALE_MODE; } else if(compare(head, new byte[]{8, 2, 0, 0, 0})) { mode = PNGEncoder.COLOR_MODE; } else { throw(new JemmyException("Format error")); } readInt();//!!crc int size = readInt(); byte[] idat = read(4); checkEquality(idat, "IDAT".getBytes()); byte[] data = read(size); Inflater inflater = new Inflater(); inflater.setInput(data, 0, size); int color; try { switch (mode) { case PNGEncoder.BW_MODE: { int bytes = (int)(width / 8); if((width % 8) != 0) { bytes++; } byte colorset; byte[] row = new byte[bytes]; for (int y = 0; y < height; y++) { inflater.inflate(new byte[1]); inflater.inflate(row); for (int x = 0; x < bytes; x++) { colorset = row[x]; for (int sh = 0; sh < 8; sh++) { if(x * 8 + sh >= width) { break; } if((colorset & 0x80) == 0x80) { result.setRGB(x * 8 + sh, y, Color.white.getRGB()); } else { result.setRGB(x * 8 + sh, y, Color.black.getRGB()); } colorset <<= 1; } } } } break; case PNGEncoder.GREYSCALE_MODE: { byte[] row = new byte[width]; for (int y = 0; y < height; y++) { inflater.inflate(new byte[1]); inflater.inflate(row); for (int x = 0; x < width; x++) { color = row[x]; result.setRGB(x, y, (color << 16) + (color << 8) + color); } } } break; case PNGEncoder.COLOR_MODE: { byte[] row = new byte[width * 3]; for (int y = 0; y < height; y++) { inflater.inflate(new byte[1]); inflater.inflate(row); for (int x = 0; x < width; x++) { result.setRGB(x, y, ((row[x * 3 + 0]&0xff) << 16) + ((row[x * 3 + 1]&0xff) << 8) + ((row[x * 3 + 2]&0xff))); } } } } } catch(DataFormatException e) { throw(new JemmyException("ZIP error", e)); } readInt();//!!crc readInt();//0 byte[] iend = read(4); checkEquality(iend, "IEND".getBytes()); readInt();//!!crc in.close(); return(result); } /** * Decodes image from file. * @param fileName a file to read image from * @return a BufferedImage instance. */ public static BufferedImage decode(String fileName) { try { return(new PNGDecoder(new FileInputStream(fileName)).decode()); } catch(IOException e) { throw(new JemmyException("IOException during image reading", e)); } } } Jemmy2/src/org/netbeans/jemmy/util/DefaultVisualizer.java0000644000175000017500000002210111245712237022545 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import javax.swing.JInternalFrame; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyInputException; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JDialogOperator; import org.netbeans.jemmy.operators.JInternalFrameOperator; import org.netbeans.jemmy.operators.JScrollPaneOperator; import org.netbeans.jemmy.operators.JTabbedPaneOperator; import org.netbeans.jemmy.operators.Operator; import org.netbeans.jemmy.operators.WindowOperator; import org.netbeans.jemmy.operators.Operator.ComponentVisualizer; /** * * Used as component visualizer by default. * * @see org.netbeans.jemmy.operators.Operator#setVisualizer(Operator.ComponentVisualizer) * @see org.netbeans.jemmy.operators.Operator.ComponentVisualizer * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class DefaultVisualizer implements ComponentVisualizer, Cloneable { private boolean window = true; private boolean internalFrame = true; private boolean scroll = false; private boolean switchTab = false; private boolean modal = false; public DefaultVisualizer() { } /** * Forces vizualizer to check that component is * on the top modal dialog or no modal dialog * displayed. * @param yesOrNo If true, JemmyInputException will be throught * if component is not on the top modal dialog and a modal dialog * is dislayed. */ public void checkForModal(boolean yesOrNo) { modal = yesOrNo; } /** * Informs that a window contained component should be activated. * @param yesOrNo true if windows need to be activated. */ public void activateWindow(boolean yesOrNo) { window = yesOrNo; } /** * Informs that an internal frame contained component * should be activated. * @param yesOrNo true if internal frames need to be activated. */ public void activateInternalFrame(boolean yesOrNo) { internalFrame = yesOrNo; } /** * Informs that scrolling should be made. * @param yesOrNo true if scroll panes need to be scrolled. */ public void scroll(boolean yesOrNo) { scroll = yesOrNo; } /** * Informs that tab switching should be made. * @param yesOrNo true if tabbed panes need to be switched. */ public void switchTab(boolean yesOrNo) { switchTab = yesOrNo; } /** * Returns true if window is active. * @param winOper an operator representing the window. * @return true is window is active. */ protected boolean isWindowActive(WindowOperator winOper) { return(winOper.isFocused() && winOper.isActive()); } /** * Performs an atomic window-activization precedure. * A window is sopposed to be prepared for the activization * (i.e. put "to front"). * @param winOper an operator representing the window. */ protected void makeWindowActive(WindowOperator winOper) { winOper.activate(); } /** * Activates a window. Uses makeWindowActive if necessary. * @param winOper an operator representing the window. * @see #makeWindowActive */ protected void activate(WindowOperator winOper) { boolean active = isWindowActive(winOper); winOper.toFront(); if(!active) { makeWindowActive(winOper); } } /** * Inits an internal frame. * @param intOper an operator representing the frame. */ protected void initInternalFrame(JInternalFrameOperator intOper) { if(!intOper.isSelected()) { intOper.activate(); } } /** * Scrolls JScrollPane to make the component visible. * @param scrollOper an operator representing a scroll pane. * @param target a component - target to be made visible. */ protected void scroll(JScrollPaneOperator scrollOper, Component target) { if(!scrollOper.checkInside(target)) { scrollOper.scrollToComponent(target); } } /** * Switches tabs to make the component visible. * @param tabOper an operator representing a tabbed pane. * @param target a component - target to be made visible. */ protected void switchTab(JTabbedPaneOperator tabOper, Component target) { int tabInd = 0; for(int j = 0; j < tabOper.getTabCount(); j++) { if(target == tabOper.getComponentAt(j)) { tabInd = j; break; } } if(tabOper.getSelectedIndex() != tabInd) { tabOper.selectPage(tabInd); } } /** * Prepares the component for user input. * @param compOper an operator representing the component. * @throws JemmyInputException * @see #checkForModal(boolean) */ public void makeVisible(ComponentOperator compOper) { try { if(modal) { Dialog modalDialog = JDialogOperator.getTopModalDialog(); if(modalDialog != null && compOper.getWindow() != modalDialog) { throw(new JemmyInputException("Component is not on top modal dialog.", compOper.getSource())); } } WindowOperator winOper = new WindowOperator(compOper.getWindow()); if(window) { winOper.copyEnvironment(compOper); winOper.setVisualizer(new EmptyVisualizer()); activate(winOper); } if(internalFrame && compOper instanceof JInternalFrameOperator) { initInternalFrame((JInternalFrameOperator)compOper); } Container[] conts = compOper.getContainers(); for(int i = conts.length - 1; i >=0 ; i--) { if (internalFrame && conts[i] instanceof JInternalFrame) { JInternalFrameOperator intOper = new JInternalFrameOperator((JInternalFrame)conts[i]); intOper.copyEnvironment(compOper); intOper.setVisualizer(new EmptyVisualizer()); initInternalFrame(intOper); } else if(scroll && conts[i] instanceof JScrollPane) { JScrollPaneOperator scrollOper = new JScrollPaneOperator((JScrollPane)conts[i]); scrollOper.copyEnvironment(compOper); scrollOper.setVisualizer(new EmptyVisualizer()); scroll(scrollOper, compOper.getSource()); } else if(switchTab && conts[i] instanceof JTabbedPane) { JTabbedPaneOperator tabOper = new JTabbedPaneOperator((JTabbedPane)conts[i]); tabOper.copyEnvironment(compOper); tabOper.setVisualizer(new EmptyVisualizer()); switchTab(tabOper, i == 0 ? compOper.getSource() : conts[i - 1]); } } } catch(TimeoutExpiredException e) { JemmyProperties.getProperties().getOutput().printStackTrace(e); } } /** * Creates an exact copy of this visualizer. * @return new instance. */ public DefaultVisualizer cloneThis() { try { return((DefaultVisualizer)super.clone()); } catch(CloneNotSupportedException e) { //that's impossible throw(new JemmyException("Even impossible happens :)", e)); } } } Jemmy2/src/org/netbeans/jemmy/util/PNGEncoder.java0000644000175000017500000002460611245712237021043 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import java.awt.AWTException; import java.awt.Component; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.zip.CRC32; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; /** This class allows to encode BufferedImage into B/W, greyscale or true color PNG * image format with maximum compression.
* It also provides complete functionality for capturing full screen, part of * screen or single component, encoding and saving captured image info PNG file. * @author Adam Sotona * @version 1.0 */ public class PNGEncoder extends Object { /** black and white image mode. */ public static final byte BW_MODE = 0; /** grey scale image mode. */ public static final byte GREYSCALE_MODE = 1; /** full color image mode. */ public static final byte COLOR_MODE = 2; OutputStream out; CRC32 crc; byte mode; /** public constructor of PNGEncoder class with greyscale mode by default. * @param out output stream for PNG image format to write into */ public PNGEncoder(OutputStream out) { this(out, GREYSCALE_MODE); } /** public constructor of PNGEncoder class. * @param out output stream for PNG image format to write into * @param mode BW_MODE, GREYSCALE_MODE or COLOR_MODE */ public PNGEncoder(OutputStream out, byte mode) { crc=new CRC32(); this.out = out; if (mode<0 || mode>2) throw new IllegalArgumentException("Unknown color mode"); this.mode = mode; } void write(int i) throws IOException { byte b[]={(byte)((i>>24)&0xff),(byte)((i>>16)&0xff),(byte)((i>>8)&0xff),(byte)(i&0xff)}; write(b); } void write(byte b[]) throws IOException { out.write(b); crc.update(b); } /** main encoding method (stays blocked till encoding is finished). * @param image BufferedImage to encode * @throws IOException IOException */ public void encode(BufferedImage image) throws IOException { int width = image.getWidth(null); int height = image.getHeight(null); final byte id[] = {-119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13}; write(id); crc.reset(); write("IHDR".getBytes()); write(width); write(height); byte head[]=null; switch (mode) { case BW_MODE: head=new byte[]{1, 0, 0, 0, 0}; break; case GREYSCALE_MODE: head=new byte[]{8, 0, 0, 0, 0}; break; case COLOR_MODE: head=new byte[]{8, 2, 0, 0, 0}; break; } write(head); write((int) crc.getValue()); ByteArrayOutputStream compressed = new ByteArrayOutputStream(65536); BufferedOutputStream bos = new BufferedOutputStream( new DeflaterOutputStream(compressed, new Deflater(9))); int pixel; int color; int colorset; switch (mode) { case BW_MODE: int rest=width%8; int bytes=width/8; for (int y=0;y> 16) & 0xff); color+=((pixel >> 8) & 0xff); color+=(pixel & 0xff); colorset<<=1; if (color>=3*128) colorset|=1; } bos.write((byte)colorset); } if (rest>0) { colorset=0; for (int sh=0; sh> 16) & 0xff); color+=((pixel >> 8) & 0xff); color+=(pixel & 0xff); colorset<<=1; if (color>=3*128) colorset|=1; } colorset<<=8-rest; bos.write((byte)colorset); } } break; case GREYSCALE_MODE: for (int y=0;y> 16) & 0xff); color+=((pixel >> 8) & 0xff); color+=(pixel & 0xff); bos.write((byte)(color/3)); } } break; case COLOR_MODE: for (int y=0;y> 16) & 0xff)); bos.write((byte)((pixel >> 8) & 0xff)); bos.write((byte)(pixel & 0xff)); } } break; } bos.close(); write(compressed.size()); crc.reset(); write("IDAT".getBytes()); write(compressed.toByteArray()); write((int) crc.getValue()); write(0); crc.reset(); write("IEND".getBytes()); write((int) crc.getValue()); out.close(); } /** Static method performing screen capture into PNG image format file with given fileName. * @param rect Rectangle of screen to be captured * @param fileName file name for screen capture PNG image file */ public static void captureScreen(Rectangle rect, String fileName) { captureScreen(rect, fileName, GREYSCALE_MODE); } /** Static method performing screen capture into PNG image format file with given fileName. * @param rect Rectangle of screen to be captured * @param mode image color mode * @param fileName file name for screen capture PNG image file */ public static void captureScreen(Rectangle rect, String fileName, byte mode) { try { BufferedImage capture=new Robot().createScreenCapture(rect); BufferedOutputStream file=new BufferedOutputStream(new FileOutputStream(fileName)); PNGEncoder encoder=new PNGEncoder(file, mode); encoder.encode(capture); } catch (AWTException awte) { awte.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } /** Static method performing one component screen capture into PNG image format file with given fileName. * @param comp Component to be captured * @param fileName String image target filename */ public static void captureScreen(Component comp, String fileName) { captureScreen(comp, fileName, GREYSCALE_MODE); } /** Static method performing one component screen capture into PNG image format file with given fileName. * @param comp Component to be captured * @param fileName String image target filename * @param mode image color mode */ public static void captureScreen(Component comp, String fileName, byte mode) { captureScreen(new Rectangle(comp.getLocationOnScreen(), comp.getSize()), fileName, mode); } /** Static method performing whole screen capture into PNG image format file with given fileName. * @param fileName String image target filename */ public static void captureScreen(String fileName) { captureScreen(fileName, GREYSCALE_MODE); } /** Static method performing whole screen capture into PNG image format file with given fileName. * @param fileName String image target filename * @param mode image color mode */ public static void captureScreen(String fileName, byte mode) { captureScreen(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()), fileName, mode); } } Jemmy2/src/org/netbeans/jemmy/util/TextStyleChooser.java0000644000175000017500000002054711245712237022407 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.util; import java.awt.Color; import javax.swing.text.Element; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; /** * Defines searching criteria for javax.swing.text.StyledDocument * JTextComponentOperator.getPositionByText(String, JTextComponentOperator.TextChooser, int). * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class TextStyleChooser extends AbstractTextStyleChooser { Boolean bold = null; Boolean italic = null; Boolean strike = null; Boolean understrike = null; Integer fontSize = null; String fontFamily = null; Integer alignment = null; Color background = null; Color foreground = null; /** * Constructor. */ public TextStyleChooser() { super(); } /** * Adds boldness checking to the criteria. * @param bold Specifies if font needs to be bold. */ public void setBold(boolean bold) { this.bold = bold ? Boolean.TRUE : Boolean.FALSE; } /** * Removes boldness checking from the criteria. */ public void unsetBold() { this.bold = null; } /** * Adds italic style checking to the criteria. * @param italic Specifies if font needs to be italic. */ public void setItalic(boolean italic) { this.italic = italic ? Boolean.TRUE : Boolean.FALSE; } /** * Removes italic style checking from the criteria. */ public void unsetItalic() { this.italic = null; } /** * Adds strikeness checking to the criteria. * @param strike Specifies if font needs to be striked. */ public void setStrike(boolean strike) { this.strike = strike ? Boolean.TRUE : Boolean.FALSE; } /** * Removes strikeness checking from the criteria. */ public void unsetStrike() { this.strike = null; } /** * Adds understrikeness checking to the criteria. * @param understrike Specifies if font needs to be understriked. */ public void setUnderstrike(boolean understrike) { this.understrike = understrike ? Boolean.TRUE : Boolean.FALSE; } /** * Removes understrikeness checking from the criteria. */ public void unsetUnderstrike() { this.understrike = null; } /** * Adds font size checking to the criteria. * @param fontSize Specifies a font size. */ public void setFontSize(int fontSize) { this.fontSize = new Integer(fontSize); } /** * Removes font size checking from the criteria. */ public void unsetFontSize() { this.fontSize = null; } /** * Adds alignment checking to the criteria. * @param alignment Specifies a text alignment. */ public void setAlignment(int alignment) { this.alignment = new Integer(alignment); } /** * Removes alignment checking from the criteria. */ public void unsetAlignment() { this.alignment = null; } /** * Adds font family checking to the criteria. * @param fontFamily Specifies a font family. */ public void setFontFamily(String fontFamily) { this.fontFamily = fontFamily; } /** * Removes font family checking from the criteria. */ public void unsetFontFamily() { this.fontFamily = null; } /** * Adds backgroung color checking to the criteria. * @param background Specifies a background color. */ public void setBackground(Color background) { this.background = background; } /** * Removes backgroung color checking from the criteria. */ public void unsetBackground() { this.background = null; } /** * Adds foregroung color checking to the criteria. * @param foreground Specifies a foreground color. */ public void setForeground(Color foreground) { this.foreground = foreground; } /** * Removes foregroung color checking from the criteria. */ public void unsetForeground() { this.foreground = null; } public boolean checkElement(StyledDocument doc, Element element, int offset) { if(bold != null) { if(StyleConstants.isBold(element.getAttributes()) != bold.booleanValue()) { return(false); } } if(italic != null) { if(StyleConstants.isItalic(element.getAttributes()) != italic.booleanValue()) { return(false); } } if(strike != null) { if(StyleConstants.isStrikeThrough(element.getAttributes()) != strike.booleanValue()) { return(false); } } if(understrike != null) { if(StyleConstants.isUnderline(element.getAttributes()) != understrike.booleanValue()) { return(false); } } if(fontSize != null) { if(StyleConstants.getFontSize(element.getAttributes()) != fontSize.intValue()) { return(false); } } if(alignment != null) { if(StyleConstants.getAlignment(element.getAttributes()) != alignment.intValue()) { return(false); } } if(fontFamily != null) { if(!StyleConstants.getFontFamily(element.getAttributes()).equals(fontFamily)) { return(false); } } if(background != null) { if(!StyleConstants.getBackground(element.getAttributes()).equals(background)) { return(false); } } if(foreground != null) { if(!StyleConstants.getForeground(element.getAttributes()).equals(foreground)) { return(false); } } return(true); } public String getDescription() { String result = ""; if(bold != null) { result = result + (bold.booleanValue() ? "" : "not ") + "bold, "; } if(italic != null) { result = result + (italic.booleanValue() ? "" : "not ") + "italic, "; } if(strike != null) { result = result + (strike.booleanValue() ? "" : "not ") + "strike, "; } if(understrike != null) { result = result + (understrike.booleanValue() ? "" : "not ") + "understrike, "; } if(fontSize != null) { result = result + fontSize.toString() + " size, "; } if(alignment != null) { result = result + alignment.toString() + " alignment, "; } if(fontFamily != null) { result = result + "\"" + fontFamily + "\" font family, "; } if(background != null) { result = result + background.toString() + " background, "; } if(foreground != null) { result = result + foreground.toString() + " foreground, "; } if(result.equals("")) { result = "any, "; } return(result.substring(0, result.length() - 2) + " font"); } } Jemmy2/src/org/netbeans/jemmy/Bundle.java0000644000175000017500000001210211245712237017337 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.util.Enumeration; import java.util.Properties; import java.util.jar.JarFile; import java.util.zip.ZipException; import java.util.zip.ZipFile; /** * * Load string resources from file. * Resources should be stored in name=value format. * * @see org.netbeans.jemmy.BundleManager * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class Bundle extends Object { private Properties resources; /** * Bunble constructor. */ public Bundle() { resources = new Properties(); } /** * Loads resources from an input stream. * * @param stream Stream to load resources from. * @exception IOException */ public void load(InputStream stream) throws IOException { resources.load(stream); } /** * Loads resources from a simple file. * * @param fileName Name of the file to load resources from. * @exception IOException * @exception FileNotFoundException */ public void loadFromFile(String fileName) throws IOException, FileNotFoundException { load(new FileInputStream(fileName)); } /** * Loads resources from a file in a jar archive. * * @param fileName Name of the jar archive. * @param entryName ?enryName? Name of the file to load resources from. * @exception IOException * @exception FileNotFoundException */ public void loadFromJar(String fileName, String entryName) throws IOException, FileNotFoundException { JarFile jFile = new JarFile(fileName); load(jFile.getInputStream(jFile.getEntry(entryName))); } /** * Loads resources from a file in a zip archive. * * @param fileName Name of the zip archive. * @param entryName ?enryName? Name of the file to load resources from. * @exception ZipException * @exception IOException * @exception FileNotFoundException */ public void loadFromZip(String fileName, String entryName) throws IOException, FileNotFoundException, ZipException { ZipFile zFile = new ZipFile(fileName); load(zFile.getInputStream(zFile.getEntry(entryName))); } /** * Prints bundle contents. * @param writer Writer to print data in. */ public void print(PrintWriter writer) { Enumeration keys = resources.keys(); while(keys.hasMoreElements()) { String key = (String)keys.nextElement(); writer.println(key + "=" + getResource(key)); } } /** * Prints bundle contents. * @param stream Stream to print data in. */ public void print(PrintStream stream) { print(new PrintWriter(stream)); } /** * Gets resource by key. * @param key Resource key * @return Resource value or null if resource was not found. */ public String getResource(String key) { return(resources.getProperty(key)); } } Jemmy2/src/org/netbeans/jemmy/Action.java0000644000175000017500000000552411064436407017356 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; /** * * Defines an action to be executed by ActionProducer instance. * @see org.netbeans.jemmy.ActionProducer * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface Action{ /** * Executes this action. * @param obj action argument. This argument might be the method * parameter in an invocation of * ActionProducer.produceAction(Object). This argument * might be a java.lang.String[] that lists the * command line arguments used to execute a test (or not). * @return action result. */ public Object launch(Object obj); /** * Returns the description value. * @return Action description. */ public String getDescription(); } Jemmy2/src/org/netbeans/jemmy/JemmyException.java0000644000175000017500000001217711064436407021103 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.io.PrintStream; import java.io.PrintWriter; /** * * Parent of all Jemmy exceptions. * Exception can be throught from inside jemmy methods, * if some exception occurs from code invoked from jemmy. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class JemmyException extends RuntimeException{ private Throwable innerException = null; private Object object = null; /** * Constructor. * @param description An exception description. */ public JemmyException(String description) { super(description); } /** * Constructor. * @param description An exception description. * @param innerException Exception from code invoked from jemmy. */ public JemmyException(String description, Throwable innerException) { this(description); this.innerException = innerException; } /** * Constructor. * @param description An exception description. * @param object Object regarding which exception is thrown. */ public JemmyException(String description, Object object) { this(description); this.object = object; } /** * Constructor. * @param description An exception description. * @param innerException Exception from code invoked from jemmy. * @param object Object regarding which exception is thrown. */ public JemmyException(String description, Throwable innerException, Object object) { this(description, innerException); this.object = object; } /** * Returns "object" constructor parameter. * @return the Object value associated with the exception. */ public Object getObject() { return(object); } /** * Returns inner exception. * @return An inner exception. * @deprecated Use getInnerThrowable() */ public Exception getInnerException() { if(innerException instanceof Exception) { return((Exception)innerException); } else { return(null); } } /** * Returns inner throwable. * @return An inner throwable. */ public Throwable getInnerThrowable() { return(innerException); } /** * Prints stack trace into System.out. */ public void printStackTrace() { printStackTrace(System.out); } /** * Prints stack trace. * @param ps PrintStream to print stack trace into. */ public void printStackTrace(PrintStream ps) { super.printStackTrace(ps); if(innerException != null) { ps.println("Inner exception:"); innerException.printStackTrace(ps); } if(object != null) { ps.println("Object:"); ps.println(object.toString());; } } /** * Prints stack trace. * * @param pw PrintWriter to print stack trace into. * */ public void printStackTrace(PrintWriter pw) { super.printStackTrace(pw); if(innerException != null) { pw.println("Inner exception:"); innerException.printStackTrace(pw); } if(object != null) { pw.println("Object:"); pw.println(object.toString());; } } } Jemmy2/src/org/netbeans/jemmy/ComponentIsNotFocusedException.java0000644000175000017500000000513711064436407024250 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.awt.Component; /** * * Exception can be thrown as a result of attempt to produce a key operation * for a component which does not have focus. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class ComponentIsNotFocusedException extends JemmyInputException { /** * Constructs a ComponentIsNotFocusedException object. * @param comp a Component. */ public ComponentIsNotFocusedException(Component comp) { super("Component do not have focus", comp); } } Jemmy2/src/org/netbeans/jemmy/Timeout.java0000644000175000017500000000732411064436407017567 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; /** * Represents one timeout. * @author Alexandre Iline (alexandre.iline@sun.com) */ public class Timeout extends Object { private String name; private long value; private long startTime; /** * Constructor. * @param name Timeout name. * @param value Timeout value in milliseconds. */ public Timeout(String name, long value) { this.name = name; this.value = value; } /** * Returns timeout name. * @return timeout name. */ public String getName() { return(name); } /** * Returns timeout value. * @return timeout value. */ public long getValue() { return(value); } /** * Sleeps for timeout value. */ public void sleep() { if(getValue()>0) { try { Thread.currentThread().sleep(getValue()); } catch(InterruptedException e) { throw(new JemmyException("Sleep " + getName() + " was interrupted!", e)); } } } /** * Starts timeout measuring. */ public void start() { startTime = System.currentTimeMillis(); } /** * Checks if timeout has been expired after start() invocation. * @return true if timeout has been expired. */ public boolean expired() { return(System.currentTimeMillis() - startTime > getValue()); } /** * Throws a TimeoutExpiredException exception if timeout has been expired. * @throws TimeoutExpiredException if timeout has been expired after start() invocation. */ public void check() { if(expired()) { throw(new TimeoutExpiredException(getName() + " timeout expired!")); } } } Jemmy2/src/org/netbeans/jemmy/EventTool.java0000644000175000017500000004014411245712237020054 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.awt.AWTEvent; import java.awt.Toolkit; import java.awt.event.AWTEventListener; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Vector; /** * * Provides methods to check last dispatched events, * to wait for events of specific types, or to guarantee that events * of specific types are not dispatched during some time frame. *

* All possible listeners are added during this class initialization * in case if "jemmy.event_listening" system property is not equal to "no", * so, by default, all events are listened. * * Uses timeouts:
* EventTool.WaitEventTimeout - time to wait for AWT events.
* EventTool.WaitNoEventTimeout - when checking for the absence of incoming AWT * events.
* EventTool.EventCheckingDelta - time delta between checks for AWT events. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class EventTool implements Timeoutable, Outputable { private static final long WAIT_EVENT_TIMEOUT = 60000; private static final long WAIT_NO_EVENT_TIMEOUT = 180000; private static final long EVENT_CHECKING_DELTA = 10; private static ListenerSet listenerSet; private static long currentEventMask = 0; private TestOut output; private Timeouts timeouts; /** * Constructor. */ public EventTool() { setOutput(JemmyProperties.getProperties().getOutput()); setTimeouts(JemmyProperties.getProperties().getTimeouts()); } /** * Returns time of the last dispatched event under mask. * @param eventMask Events types to be searched. AWTEvent.*_EVENT_MASK fields combination. * @return time in milliseconds * @see #addListeners(long) */ public static long getLastEventTime(long eventMask) { return(listenerSet.getLastEventTime(eventMask)); } /** * Returns last dispatched event under mask. * @param eventMask Events types to be searched. AWTEvent.*_EVENT_MASK fields combination. * @return AWTEvent * @see #addListeners(long) */ public static AWTEvent getLastEvent(long eventMask) { return(listenerSet.getLastEvent(eventMask)); } /** * Returns time of the last dispatched event. * @return time in milliseconds * @see #addListeners(long) */ public static long getLastEventTime() { return(getLastEventTime(listenerSet.getTheWholeMask())); } /** * Returns last dispatched event. * @return AWTEvent * @see #addListeners(long) */ public static AWTEvent getLastEvent() { return(getLastEvent(listenerSet.getTheWholeMask())); } /** * Adds listeners to listen events under mask. * Invokes removeListeners() first, so any event history is lost. * @param eventMask Mask to listen events under. AWTEvent.*_EVENT_MASK fields combination. * @see #addListeners() * @see #removeListeners() */ public static void addListeners(long eventMask) { removeListeners(); listenerSet.addListeners(eventMask); currentEventMask = eventMask; } /** * Adds listeners to listen all types of events. * Invokes removeListeners() first, so any event history is lost. * This method is invoked during static section of this class. * @see #addListeners(long) * @see #removeListeners() * @see #getTheWholeEventMask() */ public static void addListeners() { addListeners(listenerSet.getTheWholeMask()); } /** * Removes all listeners. * @see #addListeners(long) * @see #addListeners() */ public static void removeListeners() { listenerSet.removeListeners(); } /** * Returns event mask last time used by addListeners(long) method. * In case if addListeners() method was used last, * getTheWholeEventMask() result is returned. * @return a long representing the current event mask value * @see #getTheWholeEventMask() */ public static long getCurrentEventMask() { return(currentEventMask); } /** * Returns a combination of all AWTEvent.*_EVENT_MASK fields.. * @return a combination of all AWTEvent.*_EVENT_MASK fields. */ public static long getTheWholeEventMask() { return(listenerSet.getTheWholeMask()); } static { Timeouts.initDefault("EventTool.WaitEventTimeout", WAIT_EVENT_TIMEOUT); Timeouts.initDefault("EventTool.WaitNoEventTimeout", WAIT_NO_EVENT_TIMEOUT); Timeouts.initDefault("EventTool.EventCheckingDelta", EVENT_CHECKING_DELTA); listenerSet = new ListenerSet(); if(System.getProperty("jemmy.event_listening") == null || !System.getProperty("jemmy.event_listening").equals("no")) { listenerSet.addListeners(); } } /** * Defines current timeouts. * * @param ts ?t? A collection of timeout assignments. * @see org.netbeans.jemmy.Timeouts * @see org.netbeans.jemmy.Timeoutable * @see #getTimeouts */ public void setTimeouts(Timeouts ts) { timeouts = ts; } /** * Return current timeouts. * @return the collection of current timeout assignments. * @see org.netbeans.jemmy.Timeouts * @see org.netbeans.jemmy.Timeoutable * @see #setTimeouts */ public Timeouts getTimeouts() { return(timeouts); } /** * Defines print output streams or writers. * @param out Identify the streams or writers used for print output. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #getOutput */ public void setOutput(TestOut out) { output = out; } /** * Returns print output streams or writers. * @return an object that contains references to objects for * printing to output and err streams. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #setOutput */ public TestOut getOutput() { return(output); } /** * Waits for the first event under mask. * Waits during EventTool.WaitEventTimeout milliseconds. * @param eventMask Mask to wait events under. * AWTEvent.*_EVENT_MASK fields combination. * @return an AWTEvent object * @see #waitEvent() * @throws TimeoutExpiredException */ public AWTEvent waitEvent(long eventMask) { return(waitEvent(eventMask, timeouts.getTimeout("EventTool.WaitEventTimeout"), output.createErrorOutput())); } /** * Waits for the first event. * Waits during EventTool.WaitEventTimeout milliseconds. * @return an AWTEvent object * @see #waitEvent(long) * @see #getTheWholeEventMask() * @throws TimeoutExpiredException */ public AWTEvent waitEvent() { return(waitEvent(listenerSet.getTheWholeMask())); } /** * Check that no event under mask will be dispatched * during time specified. * @param eventMask Mask to wait events under. * AWTEvent.*_EVENT_MASK fields combination. * @param waitTime Quiet time (millisecons). * @return true if no event ahs found. * @see #checkNoEvent(long) */ public boolean checkNoEvent(long eventMask, long waitTime) { return(checkNoEvent(eventMask, waitTime, output)); } /** * Check that no event will be dispatched during time specified. * @param waitTime Quiet time (millisecons). * @return true if no event ahs found. * @see #checkNoEvent(long, long) * @see #getTheWholeEventMask() */ public boolean checkNoEvent(long waitTime) { return(checkNoEvent(listenerSet.getTheWholeMask(), waitTime)); } /** * During EventTool.WaitNoEventTimeout time waits for * true result of checkNoEvent(long, long) method. * @param eventMask Mask to wait events under. * AWTEvent.*_EVENT_MASK fields combination. * @param waitTime Quiet time (millisecons). * @see #checkNoEvent(long, long) * @see #waitNoEvent(long) * @throws TimeoutExpiredException */ public void waitNoEvent(long eventMask, long waitTime) { NoEventWaiter waiter = new NoEventWaiter(eventMask, waitTime); waiter.setTimeouts(timeouts.cloneThis()); waiter.getTimeouts(). setTimeout("Waiter.WaitingTime", timeouts.getTimeout("EventTool.WaitNoEventTimeout")); waiter.getTimeouts(). setTimeout("Waiter.TimeDelta", timeouts.getTimeout("EventTool.EventCheckingDelta")); try { waiter.waitAction(null); } catch(InterruptedException e) { output.printStackTrace(e); } } /** * During EventTool.WaitNoEventTimeout time waits for * true result of checkNoEvent(long) method. * @param waitTime Quiet time (millisecons). * @see #checkNoEvent(long) * @see #waitNoEvent(long, long) * @throws TimeoutExpiredException */ public void waitNoEvent(long waitTime) { ListenerSet ls = listenerSet; if (ls != null) { // surprisingly this field can be null in case of massive // garbage collecting efforts like in NbTestCase.assertGC waitNoEvent(ls.getTheWholeMask(), waitTime); } } private AWTEvent waitEvent(long eventMask, long waitTime, TestOut waiterOutput) { EventWaiter waiter = new EventWaiter(eventMask); waiter.setTimeouts(timeouts.cloneThis()); waiter.setOutput(waiterOutput); waiter.getTimeouts(). setTimeout("Waiter.WaitingTime", waitTime); waiter.getTimeouts(). setTimeout("Waiter.TimeDelta", timeouts.getTimeout("EventTool.EventCheckingDelta")); try { return((AWTEvent)waiter.waitAction(null)); } catch(InterruptedException e) { output.printStackTrace(e); return(null); } } private boolean checkNoEvent(long eventMask, long waitTime, TestOut waiterOutput) { try { AWTEvent event = waitEvent(eventMask, waitTime, TestOut.getNullOutput()); waiterOutput.printLine("AWT event was produced during waiting: "); // used instead of event.toString() because it is not thread safe waiterOutput.printLine(event.getClass().getName()); return(false); } catch(TimeoutExpiredException e) { return(true); } } private static class EventType implements AWTEventListener { long eventMask; long eventTime; private Reference eventRef; public EventType(long eventMask) { this.eventMask = eventMask; eventRef = new WeakReference(null); eventTime = -1; } public void eventDispatched(AWTEvent event) { eventRef = new WeakReference(event); eventTime = System.currentTimeMillis(); } public AWTEvent getEvent() { return (AWTEvent)eventRef.get(); } public long getTime() { return(eventTime); } public long getEventMask() { return(eventMask); } } private static class ListenerSet { private Vector eventTypes; private long theWholeMask; public ListenerSet() { eventTypes = new Vector(); try { Class eventClass = Class.forName("java.awt.AWTEvent"); Field[] fields = eventClass.getFields(); theWholeMask = 0; long eventMask; for(int i = 0; i < fields.length; i++) { if((fields[i].getModifiers() & (Modifier.PUBLIC | Modifier.STATIC)) != 0 && fields[i].getType().equals(Long.TYPE) && fields[i].getName().endsWith("_EVENT_MASK")) { eventMask = ((Long)fields[i].get(null)).longValue(); eventTypes.add(new EventType(eventMask)); theWholeMask = theWholeMask | eventMask; } } } catch(ClassNotFoundException e) { JemmyProperties.getCurrentOutput().printStackTrace(e); } catch(IllegalAccessException e) { JemmyProperties.getCurrentOutput().printStackTrace(e); } } public void addListeners(long eventMask) { Toolkit dtk = Toolkit.getDefaultToolkit(); for(int i = 0; i < eventTypes.size(); i++) { EventType et = (EventType)eventTypes.get(i); if((et.getEventMask() & eventMask) != 0) { dtk.addAWTEventListener(et, et.getEventMask()); } } } public void addListeners() { addListeners(getTheWholeMask()); } public void removeListeners() { Toolkit dtk = Toolkit.getDefaultToolkit(); for(int i = 0; i < eventTypes.size(); i++) { dtk.removeAWTEventListener((EventType)eventTypes.get(i)); } } public long getTheWholeMask() { return(theWholeMask); } public long getLastEventTime(long eventMask) { EventType et = getLastEventType(eventMask); return((et == null) ? -1 : et.getTime()); } public AWTEvent getLastEvent(long eventMask) { EventType et = getLastEventType(eventMask); return((et == null) ? null : et.getEvent()); } private EventType getLastEventType(long eventMask) { long maxTime = -1; EventType maxType = null; for(int i = 0; i < eventTypes.size(); i++) { EventType et = (EventType)eventTypes.get(i); if((eventMask & et.getEventMask()) != 0 && et.getTime() > maxTime) { maxType = et; maxTime = maxType.getTime(); } } return(maxType); } } private class EventWaiter extends Waiter { long eventMask; long startTime; public EventWaiter(long eventMask) { this.eventMask = eventMask; startTime = getLastEventTime(eventMask); } public Object actionProduced(Object obj) { EventType et = listenerSet.getLastEventType(eventMask); if(et != null && et.getTime() > startTime) { return(et.getEvent()); } else { return(null); } } public String getDescription() { return("Last event under " + Long.toString(eventMask, 2) + " event mask"); } } private class NoEventWaiter extends Waiter { long eventMask; long waitTime; public NoEventWaiter(long eventMask, long waitTime) { this.eventMask = eventMask; this.waitTime = waitTime; } public Object actionProduced(Object obj) { return(checkNoEvent(eventMask, waitTime, TestOut.getNullOutput()) ? "Reached!" : null); } public String getDescription() { return("No event under " + Long.toString(eventMask, 2) + " event mask during " + Long.toString(waitTime) + " milliseconds"); } } } Jemmy2/src/org/netbeans/jemmy/TestCompletedException.java0000644000175000017500000000612011245712237022564 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; /** * * Exception is throught as a result of test. * either test failed or passed. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class TestCompletedException extends JemmyException { private int status; /** * Constructor. * @param st Exit status. * @param ex Exception provoked test failure. */ public TestCompletedException(int st, Exception ex) { super("Test " + ((st == 0) ? "passed" : "failed with status " + Integer.toString(st)), ex); status = st; } /** * Constructor. * @param st Exit status. * @param description Failure reason */ public TestCompletedException(int st, String description) { super("Test " + ((st == 0) ? "passed" : "failed with status " + Integer.toString(st) + "\n" + description)); status = st; } /** * Returns status. * @return test status */ public int getStatus() { return(status); } } Jemmy2/src/org/netbeans/jemmy/BundleManager.java0000644000175000017500000002271711245712237020647 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.util.Enumeration; import java.util.Hashtable; import java.util.zip.ZipException; /** * * Provides functionality to work with a bunch of resource files.
* * @see org.netbeans.jemmy.Bundle * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class BundleManager extends Object { private Hashtable bundles; /** * Bundle manager constructor. */ public BundleManager() { bundles = new Hashtable(); try { load(); } catch(IOException e) { } } /** * Adds a Bundle to the managed collection of resource files. * @param bundle Bundle object * @param ID Symbolic bundle id * @return First parameter or null if bundle with ID already exists. * @see org.netbeans.jemmy.Bundle */ public Bundle addBundle(Bundle bundle, String ID) { if(getBundle(ID) != null) { return(null); } else { bundles.put(ID, bundle); return(bundle); } } /** * Removes a Bundle from the managed collection of resource files. * @param ID Symbolic bundle id * @return Removed bundle or null if no bundle ID is. */ public Bundle removeBundle(String ID) { Bundle value = getBundle(ID); bundles.remove(ID); return(value); } /** * Returns a Bundle given it's symbolic ID. * @param ID Symbolic bundle ID * @return the Bundle. A null reference is returned if * no bundle with the symbolic ID was found. */ public Bundle getBundle(String ID) { return((Bundle)bundles.get(ID)); } /** * Create a new Bundle, load resources from a simple text file, * and add the bundle. * Load resources from a text file to a new Bundle object. The new * Bundle is added to the collection of objects managed by this * BundleManager. * * @param fileName Name of a file to load resources from. * @param ID Symbolic bundle ID used to identify the new bundle used * to manage the resources from the file. * @return a newly created bundle. * @exception IOException * @exception FileNotFoundException */ public Bundle loadBundleFromFile(String fileName, String ID) throws IOException, FileNotFoundException { if(getBundle(ID) != null) { return(null); } Bundle bundle = new Bundle(); bundle.loadFromFile(fileName); return(addBundle(bundle, ID)); } public Bundle loadBundleFromStream(InputStream stream, String ID) throws IOException, FileNotFoundException { if(getBundle(ID) != null) { return(null); } Bundle bundle = new Bundle(); bundle.load(stream); return(addBundle(bundle, ID)); } public Bundle loadBundleFromResource(ClassLoader cl, String resource, String ID) throws IOException, FileNotFoundException { return loadBundleFromStream(cl.getResourceAsStream(resource), ID); } /** * Loads resources from simple text file pointed by jemmy.resources system property. * The resources are loaded into the Bundle with ID "". * Does not do anything if jemmy.resources has not been set or is empty. * * @return a newly created bundle. * @exception IOException * @exception FileNotFoundException */ public Bundle load() throws IOException, FileNotFoundException { if(System.getProperty("jemmy.resources") != null && !System.getProperty("jemmy.resources").equals("")) { return(loadBundleFromFile(System.getProperty("jemmy.resources"), "")); } return(null); } /** * Loads resources from file in jar archive into new Bundle object and adds it. * * @param fileName Name of jar file. * @param entryName ?enryName? Name of file to load resources from. * @param ID Symbolic bundle id * @return a newly created bundle. * @exception IOException * @exception FileNotFoundException */ public Bundle loadBundleFromJar(String fileName, String entryName, String ID) throws IOException, FileNotFoundException { if(getBundle(ID) != null) { return(null); } Bundle bundle = new Bundle(); bundle.loadFromJar(fileName, entryName); return(addBundle(bundle, ID)); } /** * Loads resources from file in zip archive into new Bundle object and adds it. * * @param fileName Name of jar file. * @param entryName ?enryName? Name of file to load resources from. * @param ID Symbolic bundle id * @return a newly created bundle. * @exception ZipException * @exception IOException * @exception FileNotFoundException */ public Bundle loadBundleFromZip(String fileName, String entryName, String ID) throws IOException, FileNotFoundException, ZipException { if(getBundle(ID) != null) { return(null); } Bundle bundle = new Bundle(); bundle.loadFromZip(fileName, entryName); return(addBundle(bundle, ID)); } /** * Prints bundles contents. * @param writer Writer to print data in. */ public void print(PrintWriter writer) { Enumeration keys = bundles.keys(); Bundle bundle; String key; while (keys.hasMoreElements()) { key = (String)keys.nextElement(); writer.println("\"" + key + "\" bundle contents"); bundle = getBundle(key); bundle.print(writer); } } /** * Prints bundles contents. * @param stream Stream to print data in. */ public void print(PrintStream stream) { print(new PrintWriter(stream)); } /** * Returns resource from ID bundle. * @param bundleID Bundle ID. * @param key Resource key. * @return the resource value. If the bundle ID does not exist * if the resource with the given key cannot be found, a null * reference is returned. */ public String getResource(String bundleID, String key) { Bundle bundle = getBundle(bundleID); if(bundle != null) { return(bundle.getResource(key)); } return(null); } /** * Searches for a resource in all the managed Bundles. * @param key Resource key. * @return first resource value found that is indexed by the given key. * If no resource is found, return a null reference. */ public String getResource(String key) { Enumeration data = bundles.elements(); String value; while (data.hasMoreElements()) { value = ((Bundle)data.nextElement()).getResource(key); if(value != null) { return(value); } } return(null); } /** * Counts the number of resource occurences in all the managed Bundles. * @param key Resource key * @return the number of resource occurences with the given key among * all the Bundles managed by this BundleManager. */ public int calculateResources(String key) { Enumeration data = bundles.elements(); int count = 0; while (data.hasMoreElements()) { if(((Bundle)data.nextElement()).getResource(key) != null) { count++;; } } return(count); } /** * Creates a shallow copy of this BundleManager. * Does not copy bundles, only their references. * @return a copy of this BundleManager. */ public BundleManager cloneThis() { BundleManager result = new BundleManager(); Enumeration keys = bundles.keys(); Enumeration elements = bundles.elements(); while(keys.hasMoreElements()) { result.bundles.put(keys.nextElement(), elements.nextElement()); } return(result); } } Jemmy2/src/org/netbeans/jemmy/NoComponentUnderMouseException.java0000644000175000017500000000475111245712237024266 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; /** * * Exception can be throwht as a result of attempt to produce a mouse pressing * when mouse is not over the java component. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class NoComponentUnderMouseException extends RuntimeException { /** * Constructor. */ public NoComponentUnderMouseException() { super("No component under the mouse!"); } } Jemmy2/src/org/netbeans/jemmy/WindowWaiter.java0000644000175000017500000004112311245712447020561 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.awt.Component; import java.awt.Frame; import java.awt.Window; /** * A WindowWaiter is a utility class used to look or wait for Windows. * It contains methods to search for a Window among the currently * showing Windows as well as methods that wait for a Window to show * within an allotted time period. * * Searches and waits always involve search criteria applied by a * ComponentChooser instance. Searches and waits can both be restricted * to windows owned by a given window. * *
Timeouts used:
* WindowWaiter.WaitWindowTimeout - time to wait window displayed
* WindowWaiter.AfterWindowTimeout - time to sleep after window has been dispayed
* * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class WindowWaiter extends Waiter implements Timeoutable { private final static long WAIT_TIME = 60000; private final static long AFTER_WAIT_TIME = 0; private ComponentChooser chooser; private Window owner = null; private int index = 0; private Timeouts timeouts; /** * Constructor. */ public WindowWaiter() { super(); setTimeouts(JemmyProperties.getProperties().getTimeouts()); } /** * Searches for a window. * The search proceeds among the currently showing windows * for the index+1'th window that is both owned by the * java.awt.Window owner and that meets the * criteria defined and applied by the ComponentChooser parameter. * @param owner The owner window of all the windows to be searched. * @param cc A component chooser used to define and apply the search criteria. * @param index The ordinal index of the window in the set of currently displayed * windows with the proper window ownership and a suitable title. The first * index is 0. * @return a reference to the index+1'th window that is showing, * has the proper window ownership, and that meets the search criteria. * If there are fewer than index+1 windows, a null * reference is returned. */ public static Window getWindow(Window owner, ComponentChooser cc, int index) { return(getAWindow(owner, new IndexChooser(cc, index))); } /** * Searches for a window. * Search among the currently showing windows for the first that is both * owned by the java.awt.Window owner and that * meets the search criteria applied by the ComponentChooser * parameter. * @param owner The owner window of the windows to be searched. * @param cc A component chooser used to define and apply the search criteria. * @return a reference to the first window that is showing, has a proper * owner window, and that meets the search criteria. If no such window * can be found, a null reference is returned. */ public static Window getWindow(Window owner, ComponentChooser cc) { return(getWindow(owner, cc, 0)); } /** * Searches for a window. * The search proceeds among the currently showing windows for the * index+1'th window that meets the criteria defined and * applied by the ComonentChooser parameter. * @param cc A component chooser used to define and apply the search criteria. * @param index The ordinal index of the window in the set of currently displayed * windows. The first index is 0. * @return a reference to the index+1'th window that is showing * and that meets the search criteria. If there are fewer than * index+1 windows, a null reference is returned. */ public static Window getWindow(ComponentChooser cc, int index) { return(getAWindow(new IndexChooser(cc, index))); } /** * Searches for a window. * Search among the currently showing windows for one that meets the search * criteria applied by the ComponentChooser parameter. * @param cc A component chooser used to define and apply the search criteria. * @return a reference to the first window that is showing and that * meets the search criteria. If no such window can be found, a * null reference is returned. */ public static Window getWindow(ComponentChooser cc) { return(getWindow(cc, 0)); } static { Timeouts.initDefault("WindowWaiter.WaitWindowTimeout", WAIT_TIME); Timeouts.initDefault("WindowWaiter.AfterWindowTimeout", AFTER_WAIT_TIME); } /** * Defines current timeouts. * @param timeouts A collection of timeout assignments. * @see org.netbeans.jemmy.Timeoutable * @see org.netbeans.jemmy.Timeouts * @see #getTimeouts */ public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; Timeouts times = timeouts.cloneThis(); times.setTimeout("Waiter.WaitingTime", timeouts.getTimeout("WindowWaiter.WaitWindowTimeout")); times.setTimeout("Waiter.AfterWaitingTime", timeouts.getTimeout("WindowWaiter.AfterWindowTimeout")); setWaitingTimeOrigin("WindowWaiter.WaitWindowTimeout"); super.setTimeouts(times); } /** * Return current timeouts. * @return the collection of current timeout assignments. * @see org.netbeans.jemmy.Timeoutable * @see org.netbeans.jemmy.Timeouts * @see #setTimeouts */ public Timeouts getTimeouts() { return(timeouts); } /** * Action producer--get a window. * Get a window. The search uses constraints on window ownership, * ordinal index, and search criteria defined by an instance of * org.netbeans.jemmy.ComponentChooser. * @param obj Not used. * @return the window waited upon. If a window cannot be found * then a null reference is returned. * @see org.netbeans.jemmy.Action */ public Object actionProduced(Object obj) { return(WindowWaiter.getWindow(owner, chooser, index)); } /** * Waits for a window to show. * Wait for the index+1'th window that meets the criteria * defined and applied by the ComonentChooser parameter to * show up. * * @param ch A component chooser used to define and apply the search criteria. * @param index The ordinal index of the window in the set of currently displayed * windows. The first index is 0. * @return a reference to the index+1'th window that shows * and that meets the search criteria. If fewer than * index+1 windows show up in the allotted time period then * a null reference is returned. * @throws TimeoutExpiredException * @see #actionProduced(Object) * @exception InterruptedException */ public Window waitWindow(ComponentChooser ch, int index) throws InterruptedException { chooser = ch; owner = null; this.index = index; return(waitWindow()); } /** * Waits for a window to show. * Wait for a window that meets the search criteria applied by the * ComponentChooser parameter to show up. * * @param ch A component chooser used to define and apply the search criteria. * @return a reference to the first window that shows and that * meets the search criteria. If no such window can be found within the * time period allotted, a null reference is returned. * @throws TimeoutExpiredException * @see #actionProduced(Object) * @exception InterruptedException */ public Window waitWindow(ComponentChooser ch) throws InterruptedException { return(waitWindow(ch, 0)); } /** * Waits for a window to show. * Wait for the index+1'th window to show that is both owned by the * java.awt.Window o and that meets the * criteria defined and applied by the ComponentChooser parameter. * * @param o The owner window of all the windows to be searched. * @param ch A component chooser used to define and apply the search criteria. * @param index The ordinal index of the window in the set of currently displayed * windows with the proper window ownership and a suitable title. The first * index is 0. * @return a reference to the index+1'th window to show that * has the proper window ownership, and that meets the search criteria. * If there are fewer than index+1 windows, a null * reference is returned. * @throws TimeoutExpiredException * @see #actionProduced(Object) * @exception InterruptedException */ public Window waitWindow(Window o, ComponentChooser ch, int index) throws InterruptedException { owner = o; chooser = ch; this.index = index; return((Window)waitAction(null)); } /** * Waits for a window to show. * Wait for the first window to show that is both owned by the * java.awt.Window o and that meets the * criteria defined and applied by the ComponentChooser parameter. * * @param o The owner window of all the windows to be searched. * @param ch A component chooser used to define and apply the search criteria. * @return a reference to the first window to show that * has the proper window ownership, and that meets the search criteria. * If there is no such window, a null reference is returned. * @throws TimeoutExpiredException * @see #actionProduced(Object) * @exception InterruptedException */ public Window waitWindow(Window o, ComponentChooser ch) throws InterruptedException { return(waitWindow(o, ch, 0)); } public String getDescription() { return(chooser.getDescription()); } /** * Method can be used by a subclass to define chooser. * @param ch a chooser specifying searching criteria. * @see #getComponentChooser */ protected void setComponentChooser(ComponentChooser ch) { chooser = ch; } /** * Method can be used by a subclass to define chooser. * @return a chooser specifying searching criteria. * @see #setComponentChooser */ protected ComponentChooser getComponentChooser() { return(chooser); } /** * Method can be used by a subclass to define window owner. * @param owner Window-owner of the set of windows. * @see #getOwner */ protected void setOwner(Window owner) { this.owner = owner; } /** * Method can be used by a subclass to define window owner. * @return Window-owner of the set of windows. * @see #setOwner */ protected Window getOwner() { return(owner); } /** * @see org.netbeans.jemmy.Waiter#getWaitingStartedMessage() */ protected String getWaitingStartedMessage() { return("Start to wait window \"" + chooser.getDescription() + "\" opened"); } /** * Overrides Waiter.getTimeoutExpiredMessage. * @see org.netbeans.jemmy.Waiter#getTimeoutExpiredMessage(long) * @param timeSpent time from waiting start (milliseconds) * @return a message. */ protected String getTimeoutExpiredMessage(long timeSpent) { return("Window \"" + chooser.getDescription() + "\" has not been opened in " + (new Long(timeSpent)).toString() + " milliseconds"); } /** * Overrides Waiter.getActionProducedMessage. * @see org.netbeans.jemmy.Waiter#getActionProducedMessage(long, Object) * @param timeSpent time from waiting start (milliseconds) * @param result result of Waitable.actionproduced method. * @return a message. */ protected String getActionProducedMessage(long timeSpent, final Object result) { String resultToString; if(result instanceof Component) { // run toString in dispatch thread resultToString = (String)new QueueTool().invokeSmoothly( new QueueTool.QueueAction("result.toString()") { public Object launch() { return result.toString(); } } ); } else { resultToString = result.toString(); } return("Window \"" + chooser.getDescription() + "\" has been opened in " + (new Long(timeSpent)).toString() + " milliseconds" + "\n " + resultToString); } /** * @return a message. * @see org.netbeans.jemmy.Waiter#getGoldenWaitingStartedMessage() */ protected String getGoldenWaitingStartedMessage() { return("Start to wait window \"" + chooser.getDescription() + "\" opened"); } /** * @return a message. * @see org.netbeans.jemmy.Waiter#getGoldenTimeoutExpiredMessage() */ protected String getGoldenTimeoutExpiredMessage() { return("Window \"" + chooser.getDescription() + "\" has not been opened"); } /** * @return a message. * @see org.netbeans.jemmy.Waiter#getGoldenActionProducedMessage() */ protected String getGoldenActionProducedMessage() { return("Window \"" + chooser.getDescription() + "\" has been opened"); } private static Window getAWindow(Window owner, ComponentChooser cc) { if(owner == null) { return(WindowWaiter.getAWindow(cc)); } else { Window result = null; Window[] windows = owner.getOwnedWindows(); for(int i = 0; i < windows.length; i++) { if(cc.checkComponent(windows[i])) { return(windows[i]); } if((result = WindowWaiter.getWindow(windows[i], cc)) != null) { return(result); } } return(null); } } private static Window getAWindow(ComponentChooser cc) { Window result = null; Frame[] frames = Frame.getFrames(); for(int i = 0; i < frames.length; i++) { if(cc.checkComponent(frames[i])) { return(frames[i]); } if((result = WindowWaiter.getWindow(frames[i], cc)) != null) { return(result); } } return(null); } private Window waitWindow() throws InterruptedException { return((Window)waitAction(null)); } private static class IndexChooser implements ComponentChooser { private int curIndex = 0; private int index; private ComponentChooser chooser; public IndexChooser(ComponentChooser ch, int i) { index = i; chooser = ch; curIndex = 0; } public boolean checkComponent(Component comp) { if(comp.isShowing() && comp.isVisible() && chooser.checkComponent(comp)) { if(curIndex == index) { return(true); } curIndex++; } return(false); } public String getDescription() { return(chooser.getDescription()); } } } Jemmy2/src/org/netbeans/jemmy/ClassReference.java0000644000175000017500000002065611245712237021027 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * * Allows access to classes by reflection. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class ClassReference{ private Class cl; private Object instance; /** * Constructor. * @param o Object to work with. */ public ClassReference(Object o) { super(); instance = o; cl = o.getClass(); } /** * Contructor. * The object created by this constructor can be used * to access static methods and fields only. * * @param className name of class * @exception ClassNotFoundException */ public ClassReference(String className) throws ClassNotFoundException { super(); cl = Class.forName(className); instance = null; } /** * Executes class's main(java.lang.String[]) method * with a zero-length java.lang.String array * as a parameter. * * @exception NoSuchMethodException * @exception InvocationTargetException */ public void startApplication() throws InvocationTargetException, NoSuchMethodException { String[] params = new String[0]; startApplication(params); } /** * Executes class's main(java.lang.String[]) method. * * @param params The java.lang.String array to pass * to main(java.lang.String[]). * @exception NoSuchMethodException * @exception InvocationTargetException */ public void startApplication(String[] params) throws InvocationTargetException, NoSuchMethodException { String[] real_params; if(params == null) { real_params = new String[0]; } else { real_params = params; } String[][] methodParams = {real_params}; Class[] classes = {real_params.getClass()}; try { invokeMethod("main", methodParams, classes); } catch(IllegalAccessException e) { e.printStackTrace(); } catch(IllegalStateException e) { e.printStackTrace(); } } /** * Locates method by name and parameter types and executes it. * * @param method_name Name of method. * @param params Method parameters. * @param params_classes Method parameters types. * @return the return value from an invocation of the Method.
* If method_name method is void, null is returned.
* If method_name method returns a primitive type, then * return wrapper class instance. * @throws InvocationTargetException when the invoked method throws an exception. * @throws NoSuchMethodException when the method cannot be found. * @throws IllegalAccessException when access to the class or method is lacking. * @throws SecurityException if access to the package or method is denied. * @exception IllegalAccessException * @exception NoSuchMethodException * @exception InvocationTargetException */ public Object invokeMethod(String method_name, Object[] params, Class[] params_classes) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { if(params == null) { params = new Object[0]; } if(params_classes == null) { params_classes = new Class[0]; } Method method = cl.getMethod(method_name, params_classes); return(method.invoke(instance, params)); } /** * Locates constructor by parameter types and creates an instance. * * @param params An array of Method parameters. * @param params_classes An array of Method parameter types. * @return a new class instance. * @throws InvocationTargetException when the invoked constructor throws an exception. * @throws NoSuchMethodException when the constructor cannot be found. * @throws IllegalAccessException when access to the class or constructor is lacking. * @throws InstantiationException when the constructor is for an abstract class. * @throws SecurityException if access to the package or constructor is denied. * @exception IllegalAccessException * @exception NoSuchMethodException * @exception InstantiationException * @exception InvocationTargetException */ public Object newInstance(Object[] params, Class[] params_classes) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, InstantiationException { if(params == null) { params = new Object[0]; } if(params_classes == null) { params_classes = new Class[0]; } Constructor constructor = cl.getConstructor(params_classes); return(constructor.newInstance(params)); } /** * Returns the field value. * @param field_name The name of the field. * @return the field value * @see #setField * @throws NoSuchFieldException when the field cannot be found. * @throws IllegalAccessException when access to the class or constructor is lacking. * @throws SecurityException if access to the package or field is denied. * @exception IllegalAccessException * @exception NoSuchFieldException */ public Object getField(String field_name) throws NoSuchFieldException, IllegalAccessException { return(cl.getField(field_name).get(instance)); } /** * Change a field's value. * * @param field_name The name of the field. * @param newValue The fields new value. * @see #getField * @throws NoSuchFieldException when the field cannot be found. * @throws IllegalAccessException when access to the class or constructor is lacking. * @throws SecurityException if access to the package or field is denied. * @exception IllegalAccessException * @exception NoSuchFieldException */ public void setField(String field_name, Object newValue) throws NoSuchFieldException, IllegalAccessException { cl.getField(field_name).set(instance, newValue); } /** * Returns all superclasses. * @return an array of superclasses, starting with the reference class * and ending with java.lang.Object. */ public Class[] getClasses() { Class cls = cl; int count = 0; do { count++; cls = cls.getSuperclass(); } while(cls != null); Class[] result = new Class[count]; cls = cl; for(int i = 0; i < count; i++) { result[i] = cls; cls = cls.getSuperclass(); } return(result); } } Jemmy2/src/org/netbeans/jemmy/TestOut.java0000644000175000017500000002142211245712237017542 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; /** * * Test output. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class TestOut { private InputStream input; private PrintWriter output; private PrintWriter errput; private PrintWriter golden_output; private BufferedReader buffInput; private boolean autoFlushMode = true; /** * Constructor. * @param in Input stream * @param out Output stream * @param err Errput stream */ public TestOut(InputStream in, PrintStream out, PrintStream err) { this(in, out, err, null); } /** * Constructor. * @param in Input stream * @param out Output stream * @param err Errput stream * @param golden Golgen output stream */ public TestOut(InputStream in, PrintStream out, PrintStream err, PrintStream golden) { super(); PrintWriter tout = null; if(out != null) { tout = new PrintWriter(out); } PrintWriter terr = null; if(err != null) { terr = new PrintWriter(err); } PrintWriter tgolden = null; if(golden != null) { tgolden = new PrintWriter(golden); } initStreams(in, tout, terr, tgolden); } /** * Constructor. * @param in Input stream * @param out Output stream * @param err Errput stream */ public TestOut(InputStream in, PrintWriter out, PrintWriter err) { this(in, out, err, null); } /** * Constructor. * @param in Input stream * @param out Output stream * @param err Errput stream * @param golden Golgen output stream */ public TestOut(InputStream in, PrintWriter out, PrintWriter err, PrintWriter golden) { super(); initStreams(in, out, err, golden); autoFlushMode = true; } /** * Creates unstance using System.in, System.out and System.err streams. */ public TestOut() { this(System.in, new PrintWriter(System.out), new PrintWriter(System.err), null); } /** * Creates output which does not print any message anywhere. * @return a TestOut object which does not print any message anywhere. */ public static TestOut getNullOutput() { return(new TestOut((InputStream)null, (PrintWriter)null, (PrintWriter)null)); } /** * Specifies either flush is invoked after each output. * @param autoFlushMode If true flush is invoking after each output. * @return Old value of the auto flush mode. * @see #getAutoFlushMode */ public boolean setAutoFlushMode(boolean autoFlushMode) { boolean oldValue = getAutoFlushMode(); this.autoFlushMode = autoFlushMode; return(oldValue); } /** * Says if flush is invoked after each output. * @return Value of the auto flush mode. * @see #setAutoFlushMode */ public boolean getAutoFlushMode() { return(autoFlushMode); } /** * Read one byte from input. * @return an int from input stream. * @exception IOException */ public int read() throws IOException{ if(input != null) { return(input.read()); } else { return(-1); } } /** * Read a line from input. * @return a line from input stream. * @exception IOException */ public String readLine() throws IOException{ if(buffInput != null) { return(buffInput.readLine()); } else { return(null); } } /** * Prints a line into output. * @param line a string to print into output stream. */ public void print(String line) { if(output != null) { output.print(line); } } /** * Prints a line and then terminate the line by writing the line separator string. * @param line a string to print into output stream. */ public void printLine(String line) { if(output != null) { output.println(line); if(autoFlushMode) { output.flush(); } } } /** * Prints a line into golden output. * @param line a string to print into golden output stream. */ public void printGolden(String line) { if(golden_output != null) { golden_output.println(line); if(autoFlushMode) { golden_output.flush(); } } } /** * Prints a line into error output. * @param line a string to print into error output stream. */ public void printErrLine(String line) { if(errput != null) { errput.println(line); if(autoFlushMode) { errput.flush(); } } } /** * Prints a line into either output or errput. * @param toOut If true prints a line into output. * @param line a string to print. */ public void printLine(boolean toOut, String line) { if(toOut) { printLine(line); } else { printErrLine(line); } } /** * Prints a trace line. * @param text a trace text. */ public void printTrace(String text) { printLine("Trace:"); printLine(text); } /** * Prints a error line. * @param text a error text. */ public void printError(String text) { printErrLine("Error:"); printErrLine(text); } /** * Prints an exception stack trace into error stream. * @param e exception */ public void printStackTrace(Throwable e) { if(errput != null) { e.printStackTrace(errput); if(autoFlushMode) { errput.flush(); } } } /** * Returns input stream. * @return an input stream */ public InputStream getInput() { return(input); } /** * Returns output writer. * @return an output stream */ public PrintWriter getOutput() { return(output); } /** * Returns errput writer. * @return a error stream */ public PrintWriter getErrput() { return(errput); } /** * Returns golden output writer. * @return a golden output stream */ public PrintWriter getGolden() { return(golden_output); } /** * Creates an output which prints only error messages. * @return a TestOut instance which has only error stream. */ public TestOut createErrorOutput() { return(new TestOut(null, null, getErrput())); } /** * Flushes all output threads. */ public void flush() { if(output != null) { output.flush(); } if(errput != null) { errput.flush(); } if(golden_output != null) { golden_output.flush(); } } private void initStreams(InputStream in, PrintWriter out, PrintWriter err, PrintWriter golden) { input = in; output = out; errput = err; golden_output = golden; if(input != null) { buffInput = new BufferedReader(new InputStreamReader(in)); } else { buffInput = null; } } } Jemmy2/src/org/netbeans/jemmy/package.html0000644000175000017500000000055611064436407017557 0ustar tonytony Main Jemmy package

Main Jemmy package

Contains basic Jemmy classes.

Low-level classes to find/wait components, classes to perform waitings, time resricted actions and so on.
@since 02/23/2002
Jemmy2/src/org/netbeans/jemmy/Waitable.java0000644000175000017500000000512211064436407017663 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; /** * * Defines criteria for waiting. * @see org.netbeans.jemmy.Waiter * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface Waitable{ /** * Checks if wait criteria have been met. * @param obj optional waiting parameter. * @return null is criteria have not been met. */ public Object actionProduced(Object obj); /** * Returns description. * @return a description of the wait criteria. */ public String getDescription(); } Jemmy2/src/org/netbeans/jemmy/Outputable.java0000644000175000017500000000557111064436407020267 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; /** * Communicate the identity of the output streams or writers * used by the application. Communicate the identity of the input * stream, too. Any object with methods that generates print output * should implement this interface. * * @see org.netbeans.jemmy.TestOut * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface Outputable { /** * Defines print output streams or writers. * @param out Identify the streams or writers used for print output. * @see #getOutput */ public void setOutput(TestOut out); /** * Returns print output streams or writers. * @return an object that contains references to objects for * printing to output and err streams. * @see #setOutput */ public TestOut getOutput(); } Jemmy2/src/org/netbeans/jemmy/ComponentIsNotVisibleException.java0000644000175000017500000000513111064436407024247 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.awt.Component; /** * * Exception can be thrown as a result of attempt to produce a mouse operation * for a component which is not visible. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class ComponentIsNotVisibleException extends JemmyInputException { /** * Constructs a ComponentIsNotVisibleException object. * @param comp a Component. */ public ComponentIsNotVisibleException(Component comp) { super("Component is not visible", comp); } } Jemmy2/src/org/netbeans/jemmy/DialogWaiter.java0000644000175000017500000007207611245712347020523 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.awt.Component; import java.awt.Dialog; import java.awt.Window; /** * A DialogWaiter is a utility class used to look or wait for Dialogs. * It contains methods to search for a Dialog among the currently * showing Dialogs as well as methods that wait for a Diaog to show * within an allotted time period. * * Searches and waits can either involve search criteria applied by a * ComponentChooser instance or a search criteria based on the Dialog * title. Searches and waits can both be restricted to dialogs owned * by a given window. * *

Timeouts used:
* DialogWaiter.WaitDialogTimeout - time to wait dialog displayed
* DialogWaiter.AfterDialogTimeout - time to sleep after dialog has been dispayed
* * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class DialogWaiter extends WindowWaiter implements Timeoutable, Outputable { private final static long WAIT_TIME = 60000; private final static long AFTER_WAIT_TIME = 0; private Timeouts timeouts; private TestOut output; /** * Constructor. */ public DialogWaiter() { super(); setTimeouts(JemmyProperties.getProperties().getTimeouts()); } /** * Searches for a dialog. * Search among the currently showing dialogs for one that meets the search * criteria applied by the ComponentChooser parameter. * @param cc A component chooser used to define and apply the search criteria. * @return a reference to the first dialog that is showing and that * meets the search criteria. If no such dialog can be found, a * null reference is returned. */ public static Dialog getDialog(ComponentChooser cc) { return((Dialog)WindowWaiter.getWindow(new DialogSubChooser(cc))); } /** * Searches for a dialog. * The search proceeds among the currently showing dialogs for the * index+1'th dialog that meets the criteria defined and * applied by the ComonentChooser parameter. * @param cc A component chooser used to define and apply the search criteria. * @param index The ordinal index of the dialog in the set of currently displayed * dialogs. The first index is 0. * @return a reference to the index+1'th dialog that is showing * and that meets the search criteria. If there are fewer than * index+1 dialogs, a null reference is returned. */ public static Dialog getDialog(ComponentChooser cc, int index) { return((Dialog)WindowWaiter.getWindow(new DialogSubChooser(cc), index)); } /** * Searches for a dialog by title. * The search proceeds among the currently showing dialogs for the first * with a suitable title. * @param title Dialog title or subtitle. * @param ce If true and the search is case sensitive, then a * match occurs when the title argument is a substring of a * dialog title. If false and the search is case sensitive, * then the title argument and the dialog title must be the same. * If true and the search is case insensitive, then a match occurs * when the title argument is a substring of the dialog title after * changing both to upper case. If false and the search is case * insensitive, then a match occurs when the title argument is a * substring of the dialog title after changing both to upper case. * @param cc If true the search is case sensitive; otherwise, the * search is case insensitive. * @return a reference to the first dialog that is showing and that has a * suitable title. If no such dialog can be found, a null * reference is returned. */ public static Dialog getDialog(String title, boolean ce, boolean cc) { return((Dialog)WindowWaiter.getWindow(new DialogByTitleChooser(title, ce, cc))); } /** * Searches for a dialog by title. * The search is for the index+1'th dialog among the currently * showing dialogs that possess a suitable title. * * @param title Dialog title or subtitle. * @param ce If true and the search is case sensitive, then a * match occurs when the title argument is a substring of a * dialog title. If false and the search is case sensitive, * then the title argument and the dialog title must be the same. * If true and the search is case insensitive, then a match occurs * when the title argument is a substring of the dialog title after * changing both to upper case. If false and the search is case * insensitive, then a match occurs when the title argument is a * substring of the dialog title after changing both to upper case. * @param cc If true the search is case sensitive; otherwise, the * search is case insensitive. * @param index Ordinal index between appropriate dialogs * @return a reference to the index+1'th dialog that is showing * and that has a suitable title. If there are fewer than * index+1 dialogs, a null reference is returned. */ public static Dialog getDialog(String title, boolean ce, boolean cc, int index) { return(getDialog(new DialogByTitleChooser(title, ce, cc), index)); } /** * Searches for a dialog. * Search among the currently showing dialogs for the first that is both * owned by the java.awt.Window owner and that * meets the search criteria applied by the ComponentChooser * parameter. * @param owner The owner window of the dialogs to be searched. * @param cc A component chooser used to define and apply the search criteria. * @return a reference to the first dialog that is showing, has a proper * owner window, and that meets the search criteria. If no such dialog * can be found, a null reference is returned. */ public static Dialog getDialog(Window owner, ComponentChooser cc) { return((Dialog)WindowWaiter.getWindow(owner, new DialogSubChooser(cc))); } /** * Searches for a dialog. * The search proceeds among the currently showing dialogs * for the index+1'th dialog that is both owned by the * java.awt.Window owner and that meets the * criteria defined and applied by the ComponentChooser parameter. * @param owner The owner window of all the dialogs to be searched. * @param cc A component chooser used to define and apply the search criteria. * @param index Ordinal index between appropriate dialogs * @return a reference to the index+1'th dialog that is showing, * has the proper window ownership, and that meets the search criteria. * If there are fewer than index+1 dialogs, a null * reference is returned. */ public static Dialog getDialog(Window owner, ComponentChooser cc, int index) { return((Dialog)WindowWaiter.getWindow(owner, new DialogSubChooser(cc), index)); } /** * Searches for a dialog by title. * The search proceeds among the currently showing dialogs that are owned * by the java.awt.Window owner for the first with * a suitable title. * @param owner A window - owner of a dialods to be checked. * @param title Dialog title or subtitle. * @param ce If true and the search is case sensitive, then a * match occurs when the title argument is a substring of a * dialog title. If false and the search is case sensitive, * then the title argument and the dialog title must be the same. * If true and the search is case insensitive, then a match occurs * when the title argument is a substring of the dialog title after * changing both to upper case. If false and the search is case * insensitive, then a match occurs when the title argument is a * substring of the dialog title after changing both to upper case. * @param cc If true the search is case sensitive; otherwise, the * search is case insensitive. * @return a reference to the first dialog that is showing, has the proper * window ownership, and a suitable title. If no such dialog can be found, * a null reference is returned. */ public static Dialog getDialog(Window owner, String title, boolean ce, boolean cc) { return((Dialog)WindowWaiter.getWindow(owner, new DialogByTitleChooser(title, ce, cc))); } /** * Searches for a dialog by title. * The search is for the index+1'th dialog among the currently * showing dialogs that are owned by the java.awt.Window * owner and that have a suitable title. * * @param owner ?title? Dialog title or subtitle. * @param title ?ce? If true and the search is case sensitive, then a * match occurs when the title argument is a substring of a * dialog title. If false and the search is case sensitive, * then the title argument and the dialog title must be the same. * If true and the search is case insensitive, then a match occurs * when the title argument is a substring of the dialog title after * changing both to upper case. If false and the search is case * insensitive, then a match occurs when the title argument is a * substring of the dialog title after changing both to upper case. * @param ce ?cc? If true the search is case sensitive; otherwise, the * search is case insensitive. * @param cc ?index? The ordinal index of the dialog in the set of currently displayed * dialogs with the proper window ownership and a suitable title. The * first index is 0. * @param index Ordinal index between appropriate dialogs * @return a reference to the index+1'th dialog that is showing, has * the proper window ownership, and a suitable title. If there are fewer than * index+1 dialogs, a null reference is returned. */ public static Dialog getDialog(Window owner, String title, boolean ce, boolean cc, int index) { return(getDialog(owner, new DialogByTitleChooser(title, ce, cc), index)); } static { Timeouts.initDefault("DialogWaiter.WaitDialogTimeout", WAIT_TIME); Timeouts.initDefault("DialogWaiter.AfterDialogTimeout", AFTER_WAIT_TIME); } /** * Defines current timeouts. * * @param timeouts ?t? A collection of timeout assignments. * @see org.netbeans.jemmy.Timeouts * @see org.netbeans.jemmy.Timeoutable * @see #getTimeouts */ public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; Timeouts times = timeouts.cloneThis(); times.setTimeout("WindowWaiter.WaitWindowTimeout", timeouts.getTimeout("DialogWaiter.WaitDialogTimeout")); times.setTimeout("WindowWaiter.AfterWindowTimeout", timeouts.getTimeout("DialogWaiter.AfterDialogTimeout")); super.setTimeouts(times); } /** * Return current timeouts. * @return the collection of current timeout assignments. * @see org.netbeans.jemmy.Timeouts * @see org.netbeans.jemmy.Timeoutable * @see #setTimeouts */ public Timeouts getTimeouts() { return(timeouts); } /** * Defines print output streams or writers. * * @param output ?out? Identify the streams or writers used for print output. * @see org.netbeans.jemmy.TestOut * @see org.netbeans.jemmy.Outputable * @see #getOutput */ public void setOutput(TestOut output) { this.output = output; super.setOutput(output); } /** * Returns print output streams or writers. * @return an object that contains references to objects for * printing to output and err streams. * @see org.netbeans.jemmy.TestOut * @see org.netbeans.jemmy.Outputable * @see #setOutput */ public TestOut getOutput() { return(output); } /** * Waits for a dialog to show. * Wait for the index+1'th dialog that meets the criteria * defined and applied by the ComonentChooser parameter to * show up. * * @param ch A component chooser used to define and apply the search criteria. * @param index The ordinal index of the dialog in the set of currently displayed * dialogs. The first index is 0. * @return a reference to the index+1'th dialog that shows * and that meets the search criteria. If fewer than * index+1 dialogs show up in the allotted time period then * a null reference is returned. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.WindowWaiter#actionProduced(Object) * @exception InterruptedException */ public Dialog waitDialog(ComponentChooser ch, int index) throws InterruptedException { setTimeouts(timeouts); return((Dialog)waitWindow(new DialogSubChooser(ch), index)); } /** * Waits for a dialog to show. * Wait for a dialog that meets the search criteria applied by the * ComponentChooser parameter to show up. * * @param ch A component chooser used to define and apply the search criteria. * @return a reference to the first dialog that shows and that * meets the search criteria. If no such dialog can be found within the * time period allotted, a null reference is returned. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.WindowWaiter#actionProduced(Object) * @exception InterruptedException */ public Dialog waitDialog(ComponentChooser ch) throws InterruptedException { return(waitDialog(ch, 0)); } /** * Waits for a dialog to show. * Wait for the index+1'th dialog to show with a suitable title. * * @param title Dialog title or subtitle. * @param compareExactly If true and the search is case sensitive, then a * match occurs when the title argument is a substring of a * dialog title. If false and the search is case sensitive, * then the title argument and the dialog title must be the same. * If true and the search is case insensitive, then a match occurs * when the title argument is a substring of the dialog title after * changing both to upper case. If false and the search is case * insensitive, then a match occurs when the title argument is a * substring of the dialog title after changing both to upper case. * @param compareCaseSensitive If true the search is case sensitive; * otherwise, the search is case insensitive. * @param index The ordinal index of the dialog in the set of currently displayed * dialogs with the proper window ownership and a suitable title. The * first index is 0. * @return a reference to the index+1'th dialog to show and that has a * suitable title. If no such dialog can be found within the time period * allotted, a null reference is returned. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.WindowWaiter#actionProduced(Object) * @exception InterruptedException */ public Dialog waitDialog(String title, boolean compareExactly, boolean compareCaseSensitive, int index) throws InterruptedException { return(waitDialog(new DialogByTitleChooser(title, compareExactly, compareCaseSensitive), index)); } /** * Waits for a dialog to show. * Wait for the first dialog to show with a suitable title. * * @param title Dialog title or subtitle. * @param compareExactly If true and the search is case sensitive, then a * match occurs when the title argument is a substring of a * dialog title. If false and the search is case sensitive, * then the title argument and the dialog title must be the same. * If true and the search is case insensitive, then a match occurs * when the title argument is a substring of the dialog title after * changing both to upper case. If false and the search is case * insensitive, then a match occurs when the title argument is a * substring of the dialog title after changing both to upper case. * @param compareCaseSensitive If true the search is case sensitive; * otherwise, the search is case insensitive. * @return a reference to the first dialog to show and that has a * suitable title. If no such dialog can be found within the time period * allotted, a null reference is returned. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.WindowWaiter#actionProduced(Object) * @exception InterruptedException */ public Dialog waitDialog(String title, boolean compareExactly, boolean compareCaseSensitive) throws InterruptedException { return(waitDialog(title, compareExactly, compareCaseSensitive, 0)); } /** * Waits for a dialog to show. * Wait for the index+1'th dialog to show that is both owned by the * java.awt.Window owner and that meets the * criteria defined and applied by the ComponentChooser parameter. * * @param owner The owner window of all the dialogs to be searched. * @param ch A component chooser used to define and apply the search criteria. * @param index The ordinal index of the dialog in the set of currently displayed * dialogs with the proper window ownership and a suitable title. The first * index is 0. * @return a reference to the index+1'th dialog to show that * has the proper window ownership, and that meets the search criteria. * If there are fewer than index+1 dialogs, a null * reference is returned. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.WindowWaiter#actionProduced(Object) * @exception InterruptedException */ public Dialog waitDialog(Window owner, ComponentChooser ch, int index) throws InterruptedException { setTimeouts(timeouts); return((Dialog)waitWindow(owner, new DialogSubChooser(ch), index)); } /** * Waits for a dialog to show. * Wait for the first dialog to show that is both owned by the * java.awt.Window owner and that meets the * criteria defined and applied by the ComponentChooser parameter. * * @param owner The owner window of all the dialogs to be searched. * @param ch A component chooser used to define and apply the search criteria. * @return a reference to the first dialog to show that * has the proper window ownership, and that meets the search criteria. * If there is no such dialog, a null reference is returned. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.WindowWaiter#actionProduced(Object) * @exception InterruptedException */ public Dialog waitDialog(Window owner, ComponentChooser ch) throws InterruptedException { return(waitDialog(owner, ch, 0)); } /** * Waits for a dialog to show. * Wait for the index+1'th dialog to show with the proper owner * and a suitable title. * * @param owner The owner window of all the dialogs to be searched. * @param title Dialog title or subtitle. * @param compareExactly If true and the search is case sensitive, then a * match occurs when the title argument is a substring of a * dialog title. If false and the search is case sensitive, * then the title argument and the dialog title must be the same. * If true and the search is case insensitive, then a match occurs * when the title argument is a substring of the dialog title after * changing both to upper case. If false and the search is case * insensitive, then a match occurs when the title argument is a * substring of the dialog title after changing both to upper case. * @param compareCaseSensitive If true the search is case sensitive; * otherwise, the search is case insensitive. * @param index Ordinal index between appropriate dialogs * @return a reference to the index+1'th dialog to show that has * both the proper owner window and a suitable title. If no such dialog can be found * within the time period allotted, a null reference is returned. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.WindowWaiter#actionProduced(Object) * @exception InterruptedException */ public Dialog waitDialog(Window owner, String title, boolean compareExactly, boolean compareCaseSensitive, int index) throws InterruptedException { return(waitDialog(owner, new DialogByTitleChooser(title, compareExactly, compareCaseSensitive), index)); } /** * Waits for a dialog to show. * Wait for the first dialog to show with the proper owner and a suitable title. * * @see org.netbeans.jemmy.WindowWaiter#actionProduced(Object) * @param owner The owner window of all the dialogs to be searched. * @param title Dialog title or subtitle. * @param compareExactly If true and the search is case sensitive, then a * match occurs when the title argument is a substring of a * dialog title. If false and the search is case sensitive, * then the title argument and the dialog title must be the same. * If true and the search is case insensitive, then a match occurs * when the title argument is a substring of the dialog title after * changing both to upper case. If false and the search is case * insensitive, then a match occurs when the title argument is a * substring of the dialog title after changing both to upper case. * @param compareCaseSensitive If true the search is case sensitive; * otherwise, the search is case insensitive. * @return a reference to the first dialog to show and that has both the proper * owner and a suitable title. If no such dialog can be found within the time period * allotted, a null reference is returned. * @throws TimeoutExpiredException * @exception InterruptedException */ public Dialog waitDialog(Window owner, String title, boolean compareExactly, boolean compareCaseSensitive) throws InterruptedException { return(waitDialog(owner, title, compareExactly, compareCaseSensitive, 0)); } /** * @see org.netbeans.jemmy.Waiter#getWaitingStartedMessage() */ protected String getWaitingStartedMessage() { return("Start to wait dialog \"" + getComponentChooser().getDescription() + "\" opened"); } /** * Overrides WindowWaiter.getTimeoutExpiredMessage. * Returns the timeout expired message value. * @see org.netbeans.jemmy.Waiter#getTimeoutExpiredMessage(long) * @param spendedTime Time spent for waiting * @return A message string. */ protected String getTimeoutExpiredMessage(long spendedTime) { return("Dialog \"" + getComponentChooser().getDescription() + "\" has not been opened in " + (new Long(spendedTime)).toString() + " milliseconds"); } /** * Overrides WindowWaiter.getActionProducedMessage. * Returns the action produced message value. * @see org.netbeans.jemmy.Waiter#getActionProducedMessage(long, Object) * @param spendedTime Time spent for waiting * @param result A result of the action * @return A message string. */ protected String getActionProducedMessage(long spendedTime, final Object result) { String resultToString; if(result instanceof Component) { // run toString in dispatch thread resultToString = (String)new QueueTool().invokeSmoothly( new QueueTool.QueueAction("result.toString()") { public Object launch() { return result.toString(); } } ); } else { resultToString = result.toString(); } return("Dialog \"" + getComponentChooser().getDescription() + "\" has been opened in " + (new Long(spendedTime)).toString() + " milliseconds" + "\n " + resultToString); } /** * @see org.netbeans.jemmy.Waiter#getGoldenWaitingStartedMessage() */ protected String getGoldenWaitingStartedMessage() { return("Start to wait dialog \"" + getComponentChooser().getDescription() + "\" opened"); } /** * @see org.netbeans.jemmy.Waiter#getGoldenTimeoutExpiredMessage() */ protected String getGoldenTimeoutExpiredMessage() { return("Dialog \"" + getComponentChooser().getDescription() + "\" has not been opened"); } /** * @see org.netbeans.jemmy.Waiter#getGoldenActionProducedMessage() */ protected String getGoldenActionProducedMessage() { return("Dialog \"" + getComponentChooser().getDescription() + "\" has been opened"); } private static class DialogSubChooser implements ComponentChooser { private ComponentChooser chooser; public DialogSubChooser(ComponentChooser c) { super(); chooser = c; } public boolean checkComponent(Component comp) { if(comp instanceof Dialog) { return(comp.isShowing() && comp.isVisible() && chooser.checkComponent(comp)); } else { return(false); } } public String getDescription() { return(chooser.getDescription()); } } private static class DialogByTitleChooser implements ComponentChooser { String title; boolean compareExactly; boolean compareCaseSensitive; public DialogByTitleChooser(String t, boolean ce, boolean cc) { super(); title = t; compareExactly = ce; compareCaseSensitive = cc; } public boolean checkComponent(Component comp) { if(comp instanceof Dialog) { if(((Dialog)comp).isShowing() && comp.isVisible() && ((Dialog)comp).getTitle() != null) { String titleToComp = ((Dialog)comp).getTitle(); String contextToComp = title; if(compareCaseSensitive) { titleToComp = titleToComp.toUpperCase(); contextToComp = contextToComp.toUpperCase(); } if(compareExactly) { return(titleToComp.equals(contextToComp)); } else { return(titleToComp.indexOf(contextToComp) != -1); } } } return(false); } public String getDescription() { return(title); } } } Jemmy2/src/org/netbeans/jemmy/demo/0000755000175000017500000000000011572745222016216 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/demo/DemoInterruptedException.java0000644000175000017500000000545311245712237024056 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.demo; import java.io.PrintStream; import org.netbeans.jemmy.TestCompletedException; /** * * Exception is throught if test (demo) execution has been interrupted * (CommentWindow.isInterrupted() returned true). * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class DemoInterruptedException extends TestCompletedException { /** * Constructs a DemoInterruptedException object. * @param description an exception descriptio. */ public DemoInterruptedException(String description) { super(100, description); } public void printStackTrace() { printStackTrace(System.out); } public void printStackTrace(PrintStream ps) { super.printStackTrace(ps); } } Jemmy2/src/org/netbeans/jemmy/demo/CommentWindow.java0000644000175000017500000000666511064436407021666 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.demo; /** * * Interface implementation defines a way to display step comments * during demo or test debug. * * @author Alexandre Iline (alexandre.iline@sun.com) * * */ public interface CommentWindow { /** * Defines either test(demo) has been stopped or not. * @return true if test (demo) execution has been stopped. * Like when user is reading step comments. * false if test execution can be continued. */ public boolean isStopped(); /** * Defines either test execution should be interrupted or not. * @return If true, execution will be interrupted. */ public boolean isInterrupted(); /** * Defines window title. * @param title Title to display. */ public void setTitle(String title); /** * Should display next step comment. * @param stepComment Comments to be displayed. */ public void nextStep(String stepComment); /** * Method is invoked at the end of test(demo). * @param stepComment Comment to be displayed. */ public void showFinalComment(String stepComment); /** * Closes the window. */ public void close(); /** * Returns a message for a case when test needs to be interrupted. * @return Interrupted message if test should be interrupted. */ public String getInterruptMessage(); } Jemmy2/src/org/netbeans/jemmy/demo/DefaultCommentWindow.java0000644000175000017500000001766511245712237023174 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.demo; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import org.netbeans.jemmy.EventDispatcher; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.operators.JButtonOperator; /** * * Default org.netbeans.jemmy.demo.CommentWindow implementation. * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class DefaultCommentWindow extends JDialog implements CommentWindow { JTextArea comments; JButton finishButton; JButton nextStepButton; JButton contButton; boolean stopped = true; boolean continual = false; boolean finished = false; boolean interrupted = false; long readCommentTimeout = 1000; /** * Constructs a DefaultCommentWindow object. * @param modal Display as modal dialog. */ public DefaultCommentWindow(boolean modal) { super(); nextStepButton = new JButton("One step"); nextStepButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hideWindow(); nextStepButton.setEnabled(false); contButton.setEnabled(false); finishButton.setEnabled(false); setStopped(false); } }); contButton = new JButton("All steps"); contButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hideWindow(); nextStepButton.setEnabled(false); contButton.setEnabled(false); finishButton.setEnabled(false); continual = true; setStopped(false); } }); finishButton = new JButton("Interrupt"); finishButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hideWindow(); if(!finished) { setInterrupted(true); } continual = false; setStopped(false); } }); JPanel prepreNavPane = new JPanel(); prepreNavPane.setLayout(new BorderLayout()); prepreNavPane.add(finishButton, BorderLayout.NORTH); JPanel preNavPane = new JPanel(); preNavPane.setLayout(new BorderLayout()); preNavPane.add(contButton, BorderLayout.NORTH); preNavPane.add(prepreNavPane, BorderLayout.CENTER); JPanel navPane = new JPanel(); navPane.setLayout(new BorderLayout()); navPane.add(nextStepButton, BorderLayout.NORTH); navPane.add(preNavPane, BorderLayout.CENTER); comments = new JTextArea(""); comments.setEditable(false); comments.setLineWrap(true); getContentPane().setLayout(new BorderLayout()); getContentPane().add(navPane, BorderLayout.WEST); getContentPane().add(new JScrollPane(comments), BorderLayout.CENTER); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setSize((int)screen.getWidth(), 200); setLocation(0, (int)screen.getHeight() - 200); setModal(modal); } /** * Constructs a DefaultCommentWindow object. */ public DefaultCommentWindow() { this(false); } /** * Specifies the time to display comment. * @param timeout lond value. */ public void setCommentTimeout(long timeout) { readCommentTimeout = timeout; } public boolean isStopped() { return(stopped); } public void nextStep(String stepComment) { comments.setText(stepComment); nextStepButton.setEnabled(true); contButton.setEnabled(true); finishButton.setEnabled(true); setStopped(true); if(!continual) { new Mover(nextStepButton).enter(); } else { new Mover(nextStepButton).push(); } showWindow(); } public void showFinalComment(String stepComment) { setStopped(true); finished = true; continual = false; finishButton.setEnabled(true); finishButton.setText("Finish"); comments.setText(stepComment); new Mover(finishButton).enter(); showWindow(); } public boolean isInterrupted() { return(interrupted); } public String getInterruptMessage() { return("Step comments: \"" + comments.getText() + "\""); } public void close() { setVisible(false); } /** * Perform a mouse action at the end of test step. * If demo is executed in continual mode * (i.e. "All Steps" button has been pushed), * performs "Next" button pushing. * Otherwise simply moves mouse to the "Next" button. */ public class Mover extends Thread { JButtonOperator bo; boolean toPush = false; /** * Creates a Mover object. * @param button a Button */ public Mover(JButton button) { super(); bo = new JButtonOperator(button); Timeouts times = JemmyProperties.getCurrentTimeouts(); times.setTimeout("AbstractButton.PushButtonTimeout", readCommentTimeout); bo.setTimeouts(times); } /** * Pushes the button. */ public void push() { toPush = true; start(); } /** * Moves mouse pointer to the button. */ public void enter() { toPush = false; start(); } public void run() { try { while(!bo.getSource().isShowing()) { Thread.currentThread().sleep(100); } EventDispatcher.waitQueueEmpty(TestOut.getNullOutput(), JemmyProperties.getCurrentTimeouts()); bo.enterMouse(); if(toPush) { Thread.currentThread().sleep(readCommentTimeout); bo.push(); } } catch(InterruptedException e) { e.printStackTrace(); } catch(TimeoutExpiredException e) { e.printStackTrace(); } } } private void hideWindow() { if(isModal()) { hide(); } else { toBack(); } } private void showWindow() { show(); if(!isModal()) { toFront(); } } private void setStopped(boolean value) { stopped = value; } private void setInterrupted(boolean value) { interrupted = value; } } Jemmy2/src/org/netbeans/jemmy/demo/package.html0000644000175000017500000000041211064436407020472 0ustar tonytony Demo package

Demo package

Contains classes alowing to create automated application demoes.
@since 9 Nov 2002
Jemmy2/src/org/netbeans/jemmy/demo/Demonstrator.java0000644000175000017500000001227311064436407021545 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.demo; import org.netbeans.jemmy.EventDispatcher; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; /** * * Class to display step comments. * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class Demonstrator { private static CommentWindow displayer; private static CommentWindow nonDisplayer; /** * Notifies current CommentWindow implementation to change title. * @param title new CommentWindow's title */ public static void setTitle(String title) { displayer.setTitle(title); } /** * Changes current CommentWindow. * @param cw CommentWindow instance. */ public static void setCommentWindow(CommentWindow cw) { displayer = cw; } /** * Notifies current CommentWindow implementation to display comments for a new step. * @param stepComment New step comments */ public static void nextStep(String stepComment) { getDisplayer().nextStep(stepComment); while(getDisplayer().isStopped()) { try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { } } if(getDisplayer() != nonDisplayer) { try { EventDispatcher.waitQueueEmpty(TestOut.getNullOutput(), JemmyProperties.getCurrentTimeouts()); } catch(TimeoutExpiredException e) { e.printStackTrace(); } } if(getDisplayer().isInterrupted()) { getDisplayer().close(); throw(new DemoInterruptedException(getDisplayer().getInterruptMessage())); } } /** * Notifies current CommentWindow implementation to display final comments. * @param stepComment New step comments */ public static void showFinalComment(String stepComment) { getDisplayer().showFinalComment(stepComment); while(getDisplayer().isStopped()) { try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { } } getDisplayer().close(); if(getDisplayer() != nonDisplayer) { try { EventDispatcher.waitQueueEmpty(TestOut.getNullOutput(), JemmyProperties.getCurrentTimeouts()); } catch(TimeoutExpiredException e) { e.printStackTrace(); } } } static { setCommentWindow(new DefaultCommentWindow()); setTitle("Step comments"); nonDisplayer = new NonWindow(); } private static class NonWindow implements CommentWindow { public void setTitle(String title) { } public boolean isStopped() { return(false); } public void nextStep(String stepComment) { JemmyProperties.getCurrentOutput().printLine("Step comments:\n" + stepComment); } public void showFinalComment(String stepComment) { JemmyProperties.getCurrentOutput().printLine("Final comments:\n" + stepComment); } public boolean isInterrupted() { return(false); } public String getInterruptMessage() { return(""); } public void close() { } } private static CommentWindow getDisplayer() { if(System.getProperty("jemmy.demo") != null && System.getProperty("jemmy.demo").equals("on")) { return(displayer); } else { return(nonDisplayer); } } } Jemmy2/src/org/netbeans/jemmy/ComponentSearcher.java0000644000175000017500000002033111064436407021551 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.awt.Component; import java.awt.Container; /** * * Contains methods to search for components below a * a given java.awt.Container in the display containment hierarchy. * Uses a ComponentChooser interface implementation to find a * component. * * @see ComponentChooser * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class ComponentSearcher implements Outputable{ private int ordinalIndex; private Container container; private TestOut out; private QueueTool queueTool; private String containerToString; /** * Contructor. * The search is constrained so that only components that lie below * the given container in the containment hierarchy are considered. * @param c Container to find components in. */ public ComponentSearcher(Container c) { super(); container = c; setOutput(JemmyProperties.getProperties().getOutput()); queueTool = new QueueTool(); } /** * Creates ComponentChooser implementation * whose checkComponent(Component) * method returns true for any component. * @param description Component description. * @return ComponentChooser instance. */ public static ComponentChooser getTrueChooser(String description) { class TrueChooser implements ComponentChooser { private String description; public TrueChooser(String desc) { description = desc; } public boolean checkComponent(Component comp) { return(true); } public String getDescription() { return(description); } } return(new TrueChooser(description)); } /** * Defines print output streams or writers. * * @param output ?out? Identify the streams or writers used for print output. * @see org.netbeans.jemmy.TestOut * @see org.netbeans.jemmy.Outputable * @see #getOutput */ public void setOutput(TestOut output) { out = output; } /** * Returns print output streams or writers. * @return an object that contains references to objects for * printing to output and err streams. * @see org.netbeans.jemmy.TestOut * @see org.netbeans.jemmy.Outputable * @see #setOutput */ public TestOut getOutput() { return(out); } /** Returns container.toString(). It is called in dispatch thread. * @return container.toString() */ private String containerToString() { if(containerToString == null) { containerToString = container == null ? "null" : (String)queueTool.invokeSmoothly( new QueueTool.QueueAction("container.toString()") { public Object launch() { return container.toString(); } } ); } return containerToString; } /** * Searches for a component. * The search for the component proceeds recursively in the component hierarchy * rooted in this ComponentChooser's container. * @param chooser ComponentChooser instance, defining and applying the * search criteria. * @param index Ordinal component index. Indices start at 0. * @return the index'th component from among those components * for which the chooser's checkComponent(Component) method * returns true. * A null reference is returned if there are fewer than * index-1 components meeting the search * criteria exist in the component hierarchy rooted in this * ComponentChooser's container. */ public Component findComponent(ComponentChooser chooser, int index) { ordinalIndex = 0; final Component result = findComponentInContainer(container, chooser, index); if(result != null) { // get result.toString() - run in dispatch thread String resultToString = (String)queueTool.invokeSmoothly( new QueueTool.QueueAction("result.toString()") { public Object launch() { return result.toString(); } } ); out.printTrace("Component " + chooser.getDescription() + "\n was found in container " + containerToString() + "\n " + resultToString); out.printGolden("Component \"" + chooser.getDescription() + "\" was found"); } else { out.printTrace("Component " + chooser.getDescription() + "\n was not found in container " + containerToString()); out.printGolden("Component \"" + chooser.getDescription() + "\" was not found"); } return(result); } /** * Searches for a component. * The search for the component proceeds recursively in the component hierarchy * rooted in this ComponentChooser's container. * @param chooser ComponentChooser instance, defining and applying the * search criteria. * @return the first component for which the chooser's * checkComponent(Component) method returns true. * A null reference is returned if no component meeting the search * criteria exist in the component hierarchy rooted in this * ComponentChooser's container. */ public Component findComponent(ComponentChooser chooser) { return(findComponent(chooser, 0)); } private Component findComponentInContainer(Container cont, ComponentChooser chooser, int index) { Component[] components = cont.getComponents(); Component target; for(int i = 0; i < components.length; i++) { if(components[i] != null) { if(chooser.checkComponent(components[i])) { if(ordinalIndex == index) { return(components[i]); } else { ordinalIndex++; } } if(components[i] instanceof Container) { if((target = findComponentInContainer((Container)components[i], chooser, index)) != null) { return(target); } } } } return(null); } } Jemmy2/src/org/netbeans/jemmy/drivers/0000755000175000017500000000000011572745223016751 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/drivers/tables/0000755000175000017500000000000011572745223020223 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/drivers/tables/package.html0000644000175000017500000000037511064436407022506 0ustar tonytony Table drivers

Table drivers

Different drivers to perform a table operations.
@since 17 Apr 2002
Jemmy2/src/org/netbeans/jemmy/drivers/tables/JTableMouseDriver.java0000644000175000017500000001153511245712237024415 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.tables; import java.awt.Point; import java.awt.event.KeyEvent; import javax.swing.text.JTextComponent; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.TableDriver; import org.netbeans.jemmy.drivers.TextDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JTableOperator; import org.netbeans.jemmy.operators.JTextComponentOperator; /** * TableDriver for javax.swing.JTableDriver component type. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JTableMouseDriver extends LightSupportiveDriver implements TableDriver { QueueTool queueTool; /** * Constructs a JTableMouseDriver. */ public JTableMouseDriver() { super(new String[] {"org.netbeans.jemmy.operators.JTableOperator"});; queueTool = new QueueTool(); } public void selectCell(ComponentOperator oper, int row, int column) { clickOnCell((JTableOperator)oper, row, column, 1); } public void editCell(ComponentOperator oper, int row, int column, Object value) { JTableOperator toper = (JTableOperator)oper; toper.scrollToCell(row, column); if(!toper.isEditing() || toper.getEditingRow() != row || toper.getEditingColumn() != column) { clickOnCell((JTableOperator)oper, row, column, 2); } JTextComponentOperator textoper = new JTextComponentOperator((JTextComponent)toper. waitSubComponent(new JTextComponentOperator. JTextComponentFinder())); TextDriver text = DriverManager.getTextDriver(JTextComponentOperator.class); text.clearText(textoper); text.typeText(textoper, value.toString(), 0); DriverManager.getKeyDriver(oper). pushKey(textoper, KeyEvent.VK_ENTER, 0, oper.getTimeouts(). create("ComponentOperator.PushKeyTimeout")); } /** * Clicks on JTable cell. * @param oper Table operator. * @param row Cell row index. * @param column Cell column index. * @param clickCount Count to click. */ protected void clickOnCell(final JTableOperator oper, final int row, final int column, final int clickCount) { queueTool.invokeSmoothly(new QueueTool.QueueAction("Path selecting") { public Object launch() { Point point = oper.getPointToClick(row, column); DriverManager.getMouseDriver(oper). clickMouse(oper, point.x, point.y, clickCount, oper.getDefaultMouseButton(), 0, oper.getTimeouts().create("ComponentOperator.MouseClickTimeout")); return(null); } }); } } Jemmy2/src/org/netbeans/jemmy/drivers/trees/0000755000175000017500000000000011572745223020073 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/drivers/trees/JTreeAPIDriver.java0000644000175000017500000001075511245712237023461 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.trees; import javax.swing.text.JTextComponent; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.TextDriver; import org.netbeans.jemmy.drivers.TreeDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JTextComponentOperator; import org.netbeans.jemmy.operators.JTreeOperator; /** * TreeDriver for javax.swing.JTree component type. * Uses API calls. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JTreeAPIDriver extends LightSupportiveDriver implements TreeDriver { /** * Constructs a JTreeAPIDriver. */ public JTreeAPIDriver() { super(new String[] {"org.netbeans.jemmy.operators.JTreeOperator"}); } public void selectItem(ComponentOperator oper, int index) { selectItems(oper, new int[] {index}); } public void selectItems(ComponentOperator oper, int[] indices) { checkSupported(oper); ((JTreeOperator)oper).clearSelection(); ((JTreeOperator)oper).addSelectionRows(indices); } public void expandItem(ComponentOperator oper, int index) { checkSupported(oper); ((JTreeOperator)oper).expandRow(index); } public void collapseItem(ComponentOperator oper, int index) { checkSupported(oper); ((JTreeOperator)oper).collapseRow(index); } public void editItem(ComponentOperator oper, int index, Object newValue, Timeout waitEditorTime) { JTextComponentOperator textoper = startEditingAndReturnEditor(oper, index, waitEditorTime); TextDriver text = DriverManager.getTextDriver(JTextComponentOperator.class); text.clearText(textoper); text.typeText(textoper, newValue.toString(), 0); ((JTreeOperator)oper).stopEditing(); } public void startEditing(ComponentOperator oper, int index, Timeout waitEditorTime) { startEditing(oper, index, waitEditorTime); } private JTextComponentOperator startEditingAndReturnEditor(ComponentOperator oper, int index, Timeout waitEditorTime) { checkSupported(oper); JTreeOperator toper = (JTreeOperator)oper; toper.startEditingAtPath(toper.getPathForRow(index)); toper.getTimeouts(). setTimeout("ComponentOperator.WaitComponentTimeout", waitEditorTime.getValue()); return(new JTextComponentOperator((JTextComponent)toper. waitSubComponent(new JTextComponentOperator. JTextComponentFinder()))); } } Jemmy2/src/org/netbeans/jemmy/drivers/trees/package.html0000644000175000017500000000037211064436407022353 0ustar tonytony Tree drivers

Tree drivers

Different drivers to perform a tree operations.
@since 17 Apr 2002
Jemmy2/src/org/netbeans/jemmy/drivers/trees/JTreeMouseDriver.java0000644000175000017500000002060111245712347024131 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.trees; import java.awt.Point; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import javax.swing.text.JTextComponent; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.MouseDriver; import org.netbeans.jemmy.drivers.TextDriver; import org.netbeans.jemmy.drivers.TreeDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JTextComponentOperator; import org.netbeans.jemmy.operators.JTreeOperator; import org.netbeans.jemmy.operators.Operator; /** * TreeDriver for javax.swing.JTree component type. * Uses mouse operations. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JTreeMouseDriver extends LightSupportiveDriver implements TreeDriver { QueueTool queueTool; /** * Constructs a JTreeMouseDriver. */ public JTreeMouseDriver() { super(new String[] {"org.netbeans.jemmy.operators.JTreeOperator"}); queueTool = new QueueTool(); } public void selectItem(ComponentOperator oper, int index) { selectItems(oper, new int[] {index}); } public void selectItems(final ComponentOperator oper, int[] indices) { ((JTreeOperator)oper).clearSelection(); checkSupported(oper); final MouseDriver mdriver = DriverManager.getMouseDriver(oper); final JTreeOperator toper = (JTreeOperator)oper; final Timeout clickTime = oper.getTimeouts().create("ComponentOperator.MouseClickTimeout"); for(int i = 0; i < indices.length; i++) { final int index = i; if(!queueTool.isDispatchThread()) { toper.scrollToRow(indices[i]); } final Point p = toper.getPointToClick(indices[index]); queueTool.invokeSmoothly(new QueueTool.QueueAction("Path selecting") { public Object launch() { mdriver.clickMouse(oper, p.x, p.y, 1, Operator.getDefaultMouseButton(), (index == 0) ? 0 : InputEvent.CTRL_MASK, clickTime); return(null); } }); } //1.5 workaround if(System.getProperty("java.specification.version").compareTo("1.4") > 0) { if(!QueueTool.isDispatchThread()) { queueTool.setOutput(oper.getOutput().createErrorOutput()); queueTool.waitEmpty(10); queueTool.waitEmpty(10); queueTool.waitEmpty(10); } } //end of 1.5 workaround } public void expandItem(ComponentOperator oper, final int index) { checkSupported(oper); final JTreeOperator toper = (JTreeOperator)oper; final MouseDriver mdriver = DriverManager.getMouseDriver(oper); if(!toper.isExpanded(index)) { queueTool.invokeSmoothly(new QueueTool.QueueAction("Path selecting") { public Object launch() { Point p = toper.getPointToClick(index); mdriver.clickMouse(toper, p.x, p.y, 2, Operator.getDefaultMouseButton(), 0, toper.getTimeouts(). create("ComponentOperator.MouseClickTimeout")); return(null); } }); } } public void collapseItem(ComponentOperator oper, final int index) { checkSupported(oper); final JTreeOperator toper = (JTreeOperator)oper; final MouseDriver mdriver = DriverManager.getMouseDriver(oper); if(toper.isExpanded(index)) { queueTool.invokeSmoothly(new QueueTool.QueueAction("Path selecting") { public Object launch() { Point p = toper.getPointToClick(index); mdriver.clickMouse(toper, p.x, p.y, 2, Operator.getDefaultMouseButton(), 0, toper.getTimeouts(). create("ComponentOperator.MouseClickTimeout")); return(null); } }); } } public void editItem(ComponentOperator oper, int index, Object newValue, Timeout waitEditorTime) { JTextComponentOperator textoper = startEditingAndReturnEditor(oper, index, waitEditorTime); final TextDriver text = DriverManager.getTextDriver(JTextComponentOperator.class); text.clearText(textoper); text.typeText(textoper, newValue.toString(), 0); DriverManager.getKeyDriver(oper). pushKey(textoper, KeyEvent.VK_ENTER, 0, oper.getTimeouts(). create("ComponentOperator.PushKeyTimeout")); } public void startEditing(ComponentOperator oper, int index, Timeout waitEditorTime) { startEditingAndReturnEditor(oper, index, waitEditorTime); } private JTextComponentOperator startEditingAndReturnEditor(ComponentOperator oper, final int index, Timeout waitEditorTime) { checkSupported(oper); final JTreeOperator toper = (JTreeOperator)oper; final MouseDriver mdriver = DriverManager.getMouseDriver(oper); queueTool.invokeSmoothly(new QueueTool.QueueAction("Path selecting") { public Object launch() { Point p = toper.getPointToClick(index); mdriver.clickMouse(toper, p.x, p.y, 1, Operator.getDefaultMouseButton(), 0, toper.getTimeouts(). create("ComponentOperator.MouseClickTimeout")); return(null); } }); oper.getTimeouts().sleep("JTreeOperator.BeforeEditTimeout"); queueTool.invokeSmoothly(new QueueTool.QueueAction("Path selecting") { public Object launch() { Point p = toper.getPointToClick(index); mdriver.clickMouse(toper, p.x, p.y, 1, Operator.getDefaultMouseButton(), 0, toper.getTimeouts(). create("ComponentOperator.MouseClickTimeout")); return(null); } }); toper.getTimeouts(). setTimeout("ComponentOperator.WaitComponentTimeout", waitEditorTime.getValue()); return(new JTextComponentOperator((JTextComponent)toper. waitSubComponent(new JTextComponentOperator. JTextComponentFinder()))); } } Jemmy2/src/org/netbeans/jemmy/drivers/LightDriver.java0000644000175000017500000000501011064436407022030 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; /** * Implements "light" model of driver because does not require to * load classes for all supported operator types. * @see Driver * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface LightDriver { /** * Returns array of operator classes which are supported by this driver. * @return an array of supported operator classes' names. */ public String[] getSupported(); } Jemmy2/src/org/netbeans/jemmy/drivers/TreeDriver.java0000644000175000017500000000624611245712237021673 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to work with trees. */ public interface TreeDriver extends MultiSelListDriver { /** * Expandes a node. * @param oper Tree operator. * @param index Node index. */ public void expandItem(ComponentOperator oper, int index); /** * Collapses a node. * @param oper Tree operator. * @param index Node index. */ public void collapseItem(ComponentOperator oper, int index); /** * Edits a node. * @param oper Tree operator. * @param index Node index. * @param newValue New node value * @param waitEditorTime Time to wait node editor. */ public void editItem(ComponentOperator oper, int index, Object newValue, Timeout waitEditorTime); /** * Starts node editing. * @param oper Tree operator. * @param index Node index. * @param waitEditorTime Time to wait node editor. */ public void startEditing(ComponentOperator oper, int index, Timeout waitEditorTime); } Jemmy2/src/org/netbeans/jemmy/drivers/package.html0000644000175000017500000000134311064436407021230 0ustar tonytony Drivers interfaces

Drivers interfaces

Contains interfaces of "drivers".

Driver is a class which actually implements action reproducing. There are different types of drivers (mouse driver, keyboard driver, button drivers, ...), each of them represented by interface (button driver - by ButtonDriver interface, ...)

Package also contains some classes allowing to manage driver set.

Subpackages contain driver implementations.

Drivers is low-level API: they are not supposed to be used directly from test.
@since 04/17/2002
Jemmy2/src/org/netbeans/jemmy/drivers/APIDriverInstaller.java0000644000175000017500000002015311245712237023254 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.ClassReference; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.drivers.buttons.ButtonMouseDriver; import org.netbeans.jemmy.drivers.focus.APIFocusDriver; import org.netbeans.jemmy.drivers.focus.MouseFocusDriver; import org.netbeans.jemmy.drivers.lists.ChoiceDriver; import org.netbeans.jemmy.drivers.lists.JComboMouseDriver; import org.netbeans.jemmy.drivers.lists.JListMouseDriver; import org.netbeans.jemmy.drivers.lists.JTabAPIDriver; import org.netbeans.jemmy.drivers.lists.JTableHeaderDriver; import org.netbeans.jemmy.drivers.lists.ListKeyboardDriver; import org.netbeans.jemmy.drivers.menus.AppleMenuDriver; import org.netbeans.jemmy.drivers.menus.DefaultJMenuDriver; import org.netbeans.jemmy.drivers.menus.QueueJMenuDriver; import org.netbeans.jemmy.drivers.scrolling.JScrollBarAPIDriver; import org.netbeans.jemmy.drivers.scrolling.JSliderAPIDriver; import org.netbeans.jemmy.drivers.scrolling.JSplitPaneDriver; import org.netbeans.jemmy.drivers.scrolling.ScrollPaneDriver; import org.netbeans.jemmy.drivers.scrolling.ScrollbarDriver; import org.netbeans.jemmy.drivers.tables.JTableMouseDriver; import org.netbeans.jemmy.drivers.text.AWTTextKeyboardDriver; import org.netbeans.jemmy.drivers.text.SwingTextKeyboardDriver; import org.netbeans.jemmy.drivers.trees.JTreeAPIDriver; import org.netbeans.jemmy.drivers.windows.DefaultFrameDriver; import org.netbeans.jemmy.drivers.windows.DefaultInternalFrameDriver; import org.netbeans.jemmy.drivers.windows.DefaultWindowDriver; /** * Installs all necessary drivers for Jemmy operators except * low-level drivers which are installed by * InputDriverInstaller. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class APIDriverInstaller extends ArrayDriverInstaller { /** * Constructs a DefaultDriverInstaller object. * @param shortcutEvents Signals whether shortcut mode is used. */ public APIDriverInstaller(boolean shortcutEvents) { super(new String[] { DriverManager.LIST_DRIVER_ID, DriverManager.MULTISELLIST_DRIVER_ID, DriverManager.TREE_DRIVER_ID, DriverManager.TEXT_DRIVER_ID, DriverManager.TEXT_DRIVER_ID, DriverManager.SCROLL_DRIVER_ID, DriverManager.SCROLL_DRIVER_ID, DriverManager.SCROLL_DRIVER_ID, DriverManager.SCROLL_DRIVER_ID, DriverManager.SCROLL_DRIVER_ID, DriverManager.SCROLL_DRIVER_ID, DriverManager.BUTTON_DRIVER_ID, DriverManager.LIST_DRIVER_ID, DriverManager.LIST_DRIVER_ID, DriverManager.MULTISELLIST_DRIVER_ID, DriverManager.LIST_DRIVER_ID, DriverManager.LIST_DRIVER_ID, DriverManager.MULTISELLIST_DRIVER_ID, DriverManager.TABLE_DRIVER_ID, DriverManager.LIST_DRIVER_ID, DriverManager.FRAME_DRIVER_ID, DriverManager.WINDOW_DRIVER_ID, DriverManager.FRAME_DRIVER_ID, DriverManager.INTERNAL_FRAME_DRIVER_ID, DriverManager.WINDOW_DRIVER_ID, DriverManager.FOCUS_DRIVER_ID, DriverManager.FOCUS_DRIVER_ID, DriverManager.MENU_DRIVER_ID, DriverManager.MENU_DRIVER_ID, DriverManager.ORDEREDLIST_DRIVER_ID}, new Object[] { new JTreeAPIDriver(), new JTreeAPIDriver(), new JTreeAPIDriver(), new AWTTextKeyboardDriver(), new SwingTextKeyboardDriver(), new ScrollbarDriver(), new ScrollPaneDriver(), new JScrollBarAPIDriver(), new JSplitPaneDriver(), new JSliderAPIDriver(), createSpinnerDriver(), new ButtonMouseDriver(), new JTabAPIDriver(), new ListKeyboardDriver(), new ListKeyboardDriver(), new JComboMouseDriver(), new JListMouseDriver(), new JListMouseDriver(), new JTableMouseDriver(), new ChoiceDriver(), new DefaultFrameDriver(), new DefaultWindowDriver(), new DefaultInternalFrameDriver(), new DefaultInternalFrameDriver(), new DefaultInternalFrameDriver(), new APIFocusDriver(), new MouseFocusDriver(), (shortcutEvents ? ((Object)new QueueJMenuDriver()) : ((Object)new DefaultJMenuDriver())), ((System.getProperty("apple.laf.useScreenMenuBar") != null && System.getProperty("apple.laf.useScreenMenuBar").equals("true")) ? new AppleMenuDriver() : (shortcutEvents ? ((Object)new QueueJMenuDriver()) : ((Object)new DefaultJMenuDriver()))), new JTableHeaderDriver()}); } /** * Constructs a DefaultDriverInstaller object with shortcut mode flag * taken from JemmyProperties. */ public APIDriverInstaller() { this((JemmyProperties.getCurrentDispatchingModel() & JemmyProperties.SHORTCUT_MODEL_MASK) != 0); } private static LightDriver createSpinnerDriver() { if(System.getProperty("java.specification.version").compareTo("1.3") > 0) { try { return((LightDriver)new ClassReference("org.netbeans.jemmy.drivers.scrolling.JSpinnerDriver"). newInstance(null, null)); } catch(ClassNotFoundException e) { JemmyProperties.getCurrentOutput(). printErrLine("ATTENTION! you are using Jemmy built by Java earlier then 1.4, under " + "Java 1.4. \nImpossible to create JSpinnerDriver"); return(createEmptyDriver()); } catch(Exception e) { throw(new JemmyException("Impossible to create JSpinnerDriver although java version is " + System.getProperty("java.version"), e)); } } else { return(createEmptyDriver()); } } private static LightDriver createEmptyDriver() { return(new LightDriver() { public String[] getSupported() { return(new String[] {Object.class.getName()}); }}); } } Jemmy2/src/org/netbeans/jemmy/drivers/FrameDriver.java0000644000175000017500000000535711064436407022031 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to work with frames. */ public interface FrameDriver { /** * Iconifies a frame. * @param oper Frame operator. */ public void iconify(ComponentOperator oper); /** * Deiconifies a frame. * @param oper Frame operator. */ public void deiconify(ComponentOperator oper); /** * Maximizes a frame. * @param oper Frame operator. */ public void maximize(ComponentOperator oper); /** * Demaximizes a frame. * @param oper Frame operator. */ public void demaximize(ComponentOperator oper); } Jemmy2/src/org/netbeans/jemmy/drivers/ButtonDriver.java0000644000175000017500000000514311064436407022243 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to work with buttons. */ public interface ButtonDriver { /** * Presses a button. * @param oper Button operator. */ public void press(ComponentOperator oper); /** * Releases a button. * @param oper Button operator. */ public void release(ComponentOperator oper); /** * Pushes a button. * @param oper Button operator. */ public void push(ComponentOperator oper); } Jemmy2/src/org/netbeans/jemmy/drivers/DescriptablePathChooser.java0000644000175000017500000000460111064436407024353 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; /** * Specifies an interface for objects defining path searching criteria. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public interface DescriptablePathChooser extends PathChooser { /** * Gives path description. */ public String getDescription(); } Jemmy2/src/org/netbeans/jemmy/drivers/EditorDriver.java0000644000175000017500000000500211245712237022207 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.operators.ComponentOperator; /** * Interface of objects to be used for value changing (editing). * * @author Alexandre Iline(alexandre.iline@sun.com) */ public interface EditorDriver { /** * Changes value. * @param oper Operator to change value for. * @param newValue a new value. */ public void enterNewValue(ComponentOperator oper, Object newValue); } Jemmy2/src/org/netbeans/jemmy/drivers/UnsupportedOperatorException.java0000644000175000017500000000757511064436407025552 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.JemmyException; /** * Is thrown as a result of attempt to use driver for unsupported operator type. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class UnsupportedOperatorException extends JemmyException { /** * Constructor. * @param driver a driver * @param operator an operator */ public UnsupportedOperatorException(Class driver, Class operator) { super(driver.getName() + " operators are not supported by " + operator.getName() + " driver!"); } /** * Checks if operator class is in the list of supported classes. * @param driver Driver class * @param supported Supported classes. * @param operator Operator class. * @throws UnsupportedOperatorException if class is not supported. */ public static void checkSupported(Class driver, Class[] supported, Class operator) { for(int i = 0; i < supported.length; i++) { if(supported[i].isAssignableFrom(operator)) { return; } } throw(new UnsupportedOperatorException(driver, operator)); } /** * Checks if operator class name is in the list of supported classes names. * @param driver Driver class * @param supported Supported classes names. * @param operator Operator class. * @throws UnsupportedOperatorException if class is not supported. */ public static void checkSupported(Class driver, String[] supported, Class operator) { Class opClass = operator; do { for(int i = 0; i < supported.length; i++) { if(opClass.getName().equals(supported[i])) { return; } } } while((opClass = opClass.getSuperclass()) != null); throw(new UnsupportedOperatorException(driver, operator)); } } Jemmy2/src/org/netbeans/jemmy/drivers/InputDriverInstaller.java0000644000175000017500000001500411245712237023741 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.EventDispatcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.input.KeyEventDriver; import org.netbeans.jemmy.drivers.input.KeyRobotDriver; import org.netbeans.jemmy.drivers.input.MouseEventDriver; import org.netbeans.jemmy.drivers.input.MouseRobotDriver; /** * Installs drivers for low-level drivers. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class InputDriverInstaller { Timeout robotAutoDelay; boolean useEventDrivers; boolean smooth = false; /** * Constructs an InputDriverInstaller object. * @param useEventDrivers Tells whether to use event drivers, otherwise robot drivers. * @param robotAutoDelay Time for Robot.setAutoDelay(long) method. */ public InputDriverInstaller(boolean useEventDrivers, Timeout robotAutoDelay) { this.robotAutoDelay = robotAutoDelay; this.useEventDrivers = useEventDrivers; } /** * Constructs an InputDriverInstaller object. Takes autodelay time * from JemmyProperties' timeouts. * @param useEventDrivers Tells whether to use event drivers, otherwise robot drivers. */ public InputDriverInstaller(boolean useEventDrivers) { this(useEventDrivers, JemmyProperties.getCurrentTimeouts(). create("EventDispatcher.RobotAutoDelay")); } /** * Constructs an InputDriverInstaller object. Takes autodelay time * from JemmyProperties' timeouts. * @param useEventDrivers Tells whether to use event drivers, otherwise robot drivers. * @param smooth whether to move mouse smoothly. */ public InputDriverInstaller(boolean useEventDrivers, boolean smooth) { this(useEventDrivers); this.smooth = smooth; } /** * Constructs an InputDriverInstaller object. Uses event drivers. * @param robotAutoDelay Time for Robot.setAutoDelay(long) method. */ public InputDriverInstaller(Timeout robotAutoDelay) { this(true, robotAutoDelay); } /** * Constructs an InputDriverInstaller object. Takes autodelay time * from JemmyProperties' timeouts. Uses event drivers. */ public InputDriverInstaller() { this(true); } static { EventDispatcher.performInit(); } /** * Installs input drivers. */ public void install() { if(useEventDrivers) { LightDriver keyE = new KeyEventDriver(); LightDriver mouseE = new MouseEventDriver(); DriverManager.removeDriver(DriverManager.KEY_DRIVER_ID, keyE.getSupported()); DriverManager.removeDriver(DriverManager.MOUSE_DRIVER_ID, mouseE.getSupported()); DriverManager.setDriver(DriverManager.KEY_DRIVER_ID, keyE); DriverManager.setDriver(DriverManager.MOUSE_DRIVER_ID, mouseE); try { String[] awtOperators = { "org.netbeans.jemmy.operators.ButtonOperator", "org.netbeans.jemmy.operators.CheckboxOperator", "org.netbeans.jemmy.operators.ChoiceOperator", "org.netbeans.jemmy.operators.LabelOperator", "org.netbeans.jemmy.operators.ListOperator", "org.netbeans.jemmy.operators.ScrollPaneOperator", "org.netbeans.jemmy.operators.ScrollbarOperator", "org.netbeans.jemmy.operators.TextAreaOperator", "org.netbeans.jemmy.operators.TextComponentOperator", "org.netbeans.jemmy.operators.TextFieldOperator" }; LightDriver keyR = new KeyRobotDriver(robotAutoDelay, awtOperators); LightDriver mouseR = new MouseRobotDriver(robotAutoDelay, awtOperators); DriverManager.removeDriver(DriverManager.KEY_DRIVER_ID, keyR.getSupported()); DriverManager.removeDriver(DriverManager.MOUSE_DRIVER_ID, mouseR.getSupported()); DriverManager.setDriver(DriverManager.KEY_DRIVER_ID, keyR); DriverManager.setDriver(DriverManager.MOUSE_DRIVER_ID, mouseR); } catch(JemmyException e) { if(!(e.getInnerException() instanceof ClassNotFoundException)) { throw(e); } } } else { LightDriver keyR = new KeyRobotDriver(robotAutoDelay); LightDriver mouseR = new MouseRobotDriver(robotAutoDelay, smooth); DriverManager.removeDriver(DriverManager.KEY_DRIVER_ID, keyR.getSupported()); DriverManager.removeDriver(DriverManager.MOUSE_DRIVER_ID, mouseR.getSupported()); DriverManager.setDriver(DriverManager.KEY_DRIVER_ID, keyR); DriverManager.setDriver(DriverManager.MOUSE_DRIVER_ID, mouseR); } } } Jemmy2/src/org/netbeans/jemmy/drivers/PathChooser.java0000644000175000017500000000527611064436407022042 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; /** * Specifies an interface for objects defining path searching criteria. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public interface PathChooser { /** * Checks if depth'th path components fits the requirements. * @param depth A depth of the component. * @param component A path component to be checked. * @return true if the component fits the requirements. */ public boolean checkPathComponent(int depth, Object component); /** * Return requiered depth of the path. * @return depth. */ public int getDepth(); } Jemmy2/src/org/netbeans/jemmy/drivers/lists/0000755000175000017500000000000011572745223020107 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/drivers/lists/ListKeyboardDriver.java0000644000175000017500000000673011245712237024524 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.lists; import java.awt.event.KeyEvent; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.KeyDriver; import org.netbeans.jemmy.drivers.MultiSelListDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.ListOperator; /** * List driver for java.awt.List component type. * Uses keyboard and mouse. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class ListKeyboardDriver extends ListAPIDriver implements MultiSelListDriver { /** * Constructs a ListKeyboardDriver. */ public ListKeyboardDriver() { super(); } public void selectItem(ComponentOperator oper, int index) { ListOperator loper = (ListOperator)oper; if(loper.isMultipleMode()) { super.selectItem(loper, index); } DriverManager.getFocusDriver(oper).giveFocus(oper); KeyDriver kDriver = DriverManager.getKeyDriver(oper); int current = loper.getSelectedIndex(); int diff = 0; int key = 0; if(index > current) { diff = index - current; key = KeyEvent.VK_DOWN; } else { diff = current - index; key = KeyEvent.VK_UP; } Timeout pushTime = oper.getTimeouts().create("ComponentOperator.PushKeyTimeout"); for(int i = 0; i < diff; i++) { kDriver.pushKey(oper, key, 0, pushTime); } kDriver.pushKey(oper, KeyEvent.VK_ENTER, 0, pushTime); } } Jemmy2/src/org/netbeans/jemmy/drivers/lists/JComboMouseDriver.java0000644000175000017500000001005611245712237024306 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.lists; import javax.swing.UIManager; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.ListDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JComboBoxOperator; import org.netbeans.jemmy.operators.JListOperator; import org.netbeans.jemmy.util.EmptyVisualizer; /** * List driver for javax.swing.JCompoBox component type. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JComboMouseDriver extends LightSupportiveDriver implements ListDriver { /** * Constructs a JComboMouseDriver. */ QueueTool queueTool; public JComboMouseDriver() { super(new String[] {"org.netbeans.jemmy.operators.JComboBoxOperator"}); queueTool = new QueueTool(); } public void selectItem(ComponentOperator oper, int index) { JComboBoxOperator coper = (JComboBoxOperator)oper; //1.5 workaround if(System.getProperty("java.specification.version").compareTo("1.4") > 0) { queueTool.setOutput(oper.getOutput().createErrorOutput()); queueTool.waitEmpty(10); queueTool.waitEmpty(10); queueTool.waitEmpty(10); } //end of 1.5 workaround if(!coper.isPopupVisible()) { if(UIManager.getLookAndFeel().getClass().getName().equals("com.sun.java.swing.plaf.motif.MotifLookAndFeel")) { oper.clickMouse(oper.getWidth() - 2, oper.getHeight()/2, 1); } else { DriverManager.getButtonDriver(coper.getButton()). push(coper.getButton()); } } JListOperator list = new JListOperator(coper.waitList()); list.copyEnvironment(coper); list.setVisualizer(new EmptyVisualizer()); coper.getTimeouts().sleep("JComboBoxOperator.BeforeSelectingTimeout"); DriverManager.getListDriver(list). selectItem(list, index); } } Jemmy2/src/org/netbeans/jemmy/drivers/lists/JTableHeaderDriver.java0000644000175000017500000001142011245712237024372 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.lists; import java.awt.Point; import java.awt.event.InputEvent; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.OrderedListDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JTableHeaderOperator; /** * List driver for javax.swing.table.JTableHeader component type. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JTableHeaderDriver extends LightSupportiveDriver implements OrderedListDriver { private QueueTool queueTool; /** * Constructs a JTableHeaderDriver. */ public JTableHeaderDriver() { super(new String[] {"org.netbeans.jemmy.operators.JTableHeaderOperator"}); queueTool = new QueueTool(); } public void selectItem(ComponentOperator oper, int index) { clickOnHeader((JTableHeaderOperator)oper, index); } public void selectItems(ComponentOperator oper, int[] indices) { clickOnHeader((JTableHeaderOperator)oper, indices[0]); for(int i = 1; i < indices.length; i++) { clickOnHeader((JTableHeaderOperator)oper, indices[i], InputEvent.CTRL_MASK); } } public void moveItem(ComponentOperator oper, int moveColumn, int moveTo) { Point start = ((JTableHeaderOperator)oper).getPointToClick(moveColumn); Point end = ((JTableHeaderOperator)oper).getPointToClick(moveTo); oper.dragNDrop(start.x, start.y, end.x, end.y); } /** * Clicks on a column header. * @param oper an operator to click on. * @param index column index. */ protected void clickOnHeader(JTableHeaderOperator oper, int index) { clickOnHeader(oper, index, 0); } /** * Clicks on a column header. * @param oper an operator to click on. * @param index column index. * @param modifiers a combination of InputEvent.*_MASK fields. */ protected void clickOnHeader(final JTableHeaderOperator oper, final int index, final int modifiers) { queueTool.invokeSmoothly(new QueueTool.QueueAction("Column selecting") { public Object launch() { Point toClick = ((JTableHeaderOperator)oper).getPointToClick(index); DriverManager.getMouseDriver(oper). clickMouse(oper, toClick.x, toClick.y, 1, oper.getDefaultMouseButton(), modifiers, oper.getTimeouts().create("ComponentOperator.MouseClickTimeout")); return(null); } }); } } Jemmy2/src/org/netbeans/jemmy/drivers/lists/package.html0000644000175000017500000000037011064436407022365 0ustar tonytony List drivers

List drivers

Different drivers to perform a list operations.
@since 4/17/2002
Jemmy2/src/org/netbeans/jemmy/drivers/lists/JListMouseDriver.java0000644000175000017500000001074511245712237024167 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.lists; import java.awt.Rectangle; import java.awt.event.InputEvent; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.MultiSelListDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JListOperator; /** * List driver for javax.swing.JList component type. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JListMouseDriver extends LightSupportiveDriver implements MultiSelListDriver { QueueTool queueTool; /** * Constructs a JListMouseDriver. */ public JListMouseDriver() { super(new String[] {"org.netbeans.jemmy.operators.JListOperator"}); queueTool = new QueueTool(); } public void selectItem(ComponentOperator oper, int index) { clickOnItem((JListOperator)oper, index); } public void selectItems(ComponentOperator oper, int[] indices) { clickOnItem((JListOperator)oper, indices[0]); for(int i = 1; i < indices.length; i++) { clickOnItem((JListOperator)oper, indices[i], InputEvent.CTRL_MASK); } } /** * Clicks on a list item. * @param oper an operator to click on. * @param index item index. */ protected void clickOnItem(JListOperator oper, int index) { clickOnItem(oper, index, 0); } /** * Clicks on a list item. * @param oper an operator to click on. * @param index item index. * @param modifiers a combination of InputEvent.*_MASK fields. */ protected void clickOnItem(final JListOperator oper, final int index, final int modifiers) { if(!queueTool.isDispatchThread()) { oper.scrollToItem(index); } queueTool.invokeSmoothly(new QueueTool.QueueAction("Path selecting") { public Object launch() { Rectangle rect = oper.getCellBounds(index, index); DriverManager.getMouseDriver(oper). clickMouse(oper, rect.x + rect.width / 2, rect.y + rect.height / 2, 1, oper.getDefaultMouseButton(), modifiers, oper.getTimeouts().create("ComponentOperator.MouseClickTimeout")); return(null); } }); } } Jemmy2/src/org/netbeans/jemmy/drivers/lists/ListAPIDriver.java0000644000175000017500000000627711245712237023403 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.lists; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.MultiSelListDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.ListOperator; /** * List driver for java.awt.List component type. * Uses API calls. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class ListAPIDriver extends LightSupportiveDriver implements MultiSelListDriver { /** * Constructs a ListAPIDriver. */ public ListAPIDriver() { super(new String[] {"org.netbeans.jemmy.operators.ListOperator"}); } public void selectItem(ComponentOperator oper, int index) { ListOperator loper = (ListOperator)oper; clearSelection(loper); loper.select(index); } public void selectItems(ComponentOperator oper, int[] indices) { ListOperator loper = (ListOperator)oper; clearSelection(loper); for(int i = 0; i < indices.length; i++) { loper.select(indices[i]); } } private void clearSelection(ListOperator loper) { for(int i = 0; i < loper.getItemCount(); i++) { loper.deselect(i); } } } Jemmy2/src/org/netbeans/jemmy/drivers/lists/JTabMouseDriver.java0000644000175000017500000000756111245712237023764 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.lists; import java.awt.Rectangle; import javax.swing.JTabbedPane; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.ListDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JTabbedPaneOperator; /** * List driver for javax.swing.JTabbedPane component type. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JTabMouseDriver extends LightSupportiveDriver implements ListDriver { private QueueTool queueTool; /** * Constructs a JTabMouseDriver. */ public JTabMouseDriver() { super(new String[] {"org.netbeans.jemmy.operators.JTabbedPaneOperator"}); queueTool = new QueueTool(); } public void selectItem(final ComponentOperator oper, final int index) { if(index != -1) { queueTool.invokeSmoothly(new QueueTool.QueueAction("Choise expanding") { public Object launch() { Rectangle rect = ((JTabbedPaneOperator)oper). getUI(). getTabBounds((JTabbedPane)oper.getSource(), index); DriverManager.getMouseDriver(oper). clickMouse(oper, (int)(rect.getX() + rect.getWidth() / 2), (int)(rect.getY() + rect.getHeight() / 2), 1, oper.getDefaultMouseButton(), 0, oper.getTimeouts().create("ComponentOperator.MouseClickTimeout")); return(null); } }); } } } Jemmy2/src/org/netbeans/jemmy/drivers/lists/ChoiceDriver.java0000644000175000017500000001055211245712237023317 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.lists; import java.awt.Point; import java.awt.event.KeyEvent; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.KeyDriver; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.ListDriver; import org.netbeans.jemmy.operators.ChoiceOperator; import org.netbeans.jemmy.operators.ComponentOperator; /** * List driver for java.awt.Choice component type. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class ChoiceDriver extends LightSupportiveDriver implements ListDriver { private final static int RIGHT_INDENT = 10; /** * Constructs a ChoiceDriver. */ public ChoiceDriver() { super(new String[] {"org.netbeans.jemmy.operators.ChoiceOperator"}); } public void selectItem(ComponentOperator oper, int index) { ChoiceOperator coper = (ChoiceOperator)oper; Point pointToClick = getClickPoint(oper); DriverManager.getMouseDriver(oper). clickMouse(oper, pointToClick.x, pointToClick.y, 1, oper.getDefaultMouseButton(), 0, oper.getTimeouts().create("ComponentOperator.MouseClickTimeout")); KeyDriver kdriver = DriverManager.getKeyDriver(oper); Timeout pushTimeout = oper.getTimeouts().create("ComponentOperator.PushKeyTimeout"); if(System.getProperty("java.specification.version").compareTo("1.3") > 0) { while(coper.getSelectedIndex() != index) { kdriver.pushKey(oper, (index > coper.getSelectedIndex()) ? KeyEvent.VK_DOWN : KeyEvent.VK_UP, 0, pushTimeout); } } else { int current = ((ChoiceOperator)oper).getSelectedIndex(); int diff = 0; int key = 0; if(index > current) { diff = index - current; key = KeyEvent.VK_DOWN; } else { diff = current - index; key = KeyEvent.VK_UP; } for(int i = 0; i < diff; i++) { kdriver.pushKey(oper, key, 0, pushTimeout); } } kdriver.pushKey(oper, KeyEvent.VK_ENTER, 0, pushTimeout); } private Point getClickPoint(ComponentOperator oper) { return(new Point(oper.getWidth() - RIGHT_INDENT, oper.getHeight()/2)); } } Jemmy2/src/org/netbeans/jemmy/drivers/lists/JTabAPIDriver.java0000644000175000017500000000624511245712237023303 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.lists; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.ListDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JTabbedPaneOperator; /** * List driver for javax.swing.JTabbedPane component type. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JTabAPIDriver extends LightSupportiveDriver implements ListDriver { private QueueTool queueTool; /** * Constructs a JTabMouseDriver. */ public JTabAPIDriver() { super(new String[] {"org.netbeans.jemmy.operators.JTabbedPaneOperator"}); queueTool = new QueueTool(); } public void selectItem(final ComponentOperator oper, final int index) { if(index != -1) { queueTool.invokeSmoothly(new QueueTool.QueueAction("Choise expanding") { public Object launch() { ((JTabbedPaneOperator)oper).setSelectedIndex(index); return(null); } }); } } } Jemmy2/src/org/netbeans/jemmy/drivers/menus/0000755000175000017500000000000011572745223020100 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/drivers/menus/APIJMenuDriver.java0000644000175000017500000001307411245712237023470 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.menus; import java.awt.Component; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.drivers.MenuDriver; import org.netbeans.jemmy.drivers.PathChooser; import org.netbeans.jemmy.operators.AbstractButtonOperator; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JMenuItemOperator; import org.netbeans.jemmy.operators.JMenuOperator; public class APIJMenuDriver extends DefaultJMenuDriver implements MenuDriver { public APIJMenuDriver() { super(); } protected Object push(ComponentOperator oper, JMenuBar menuBar, PathChooser chooser, int depth, boolean pressMouse) { try { oper.waitComponentVisible(true); oper.waitComponentEnabled(); } catch(InterruptedException e) { throw(new JemmyException("Interrupted!", e)); } if(depth > chooser.getDepth() - 1) { if(oper instanceof JMenuOperator) { if(((JMenuOperator)oper).isPopupMenuVisible()) { ((JMenuOperator)oper).setPopupMenuVisible(false); } ((JMenuOperator)oper).setPopupMenuVisible(true); waitPopupMenu(oper); } ((AbstractButtonOperator)oper).doClick(); return(oper.getSource()); } else { if(((JMenuOperator)oper).isPopupMenuVisible()) { ((JMenuOperator)oper).setPopupMenuVisible(false); } ((JMenuOperator)oper).setPopupMenuVisible(true); waitPopupMenu(oper); } oper.getTimeouts().sleep("JMenuOperator.WaitBeforePopupTimeout"); JMenuItem item = waitItem(oper, waitPopupMenu(oper), chooser, depth); if(item instanceof JMenu) { JMenuOperator mo = new JMenuOperator((JMenu)item); mo.copyEnvironment(oper); Object result = push(mo, null, chooser, depth + 1, false); if(result instanceof JMenu) { org.netbeans.jemmy.JemmyProperties.getCurrentOutput().printLine("IN HERE" + ((JMenu)result).getText()); org.netbeans.jemmy.JemmyProperties.getCurrentOutput().printLine("IN HERE" + Boolean.toString(((JMenu)result).isPopupMenuVisible())); if(!((JMenu)result).isPopupMenuVisible()) { ((JMenuOperator)oper).setPopupMenuVisible(false); } } else { ((JMenuOperator)oper).setPopupMenuVisible(false); waitNoPopupMenu(oper); } return(result); } else { JMenuItemOperator mio = new JMenuItemOperator(item); mio.copyEnvironment(oper); try { mio.waitComponentEnabled(); } catch(InterruptedException e) { throw(new JemmyException("Interrupted!", e)); } ((AbstractButtonOperator)mio).doClick(); ((JMenuOperator)oper).setPopupMenuVisible(false); waitNoPopupMenu(oper); return(item); } } protected void waitNoPopupMenu(final ComponentOperator oper) { oper.waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(!((JMenuOperator)oper).isPopupMenuVisible()); } public String getDescription() { return(((JMenuOperator)oper).getText() + "'s popup"); } }); } } Jemmy2/src/org/netbeans/jemmy/drivers/menus/package.html0000644000175000017500000000034411064436407022357 0ustar tonytony Menu drivers.

Menu drivers.

Different drivers to perform a menu operations.

Jemmy2/src/org/netbeans/jemmy/drivers/menus/AppleMenuDriver.java0000644000175000017500000001463611245712237024013 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.menus; import java.awt.event.KeyEvent; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.MenuElement; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.drivers.DescriptablePathChooser; import org.netbeans.jemmy.drivers.MenuDriver; import org.netbeans.jemmy.drivers.PathChooser; import org.netbeans.jemmy.drivers.input.RobotDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.Operator; /** * * @author shura */ public class AppleMenuDriver extends RobotDriver implements MenuDriver { /** * Creates a new instance of AppleMenuDriver */ public AppleMenuDriver() { super(new Timeout("apple.system.menu.delay", 100), new String[] {"org.netbeans.jemmy.operators.JMenuBarOperator"}); } public Object pushMenu(ComponentOperator oper, PathChooser chooser) { Timeout maxTime = oper.getTimeouts().create("ComponentOperator.WaitComponentTimeout"); JMenuBar bar = (JMenuBar)(oper.getSource()); activateMenu(bar); MenuElement menuObject; maxTime.start(); while(!chooser.checkPathComponent(0, (menuObject = getSelectedElement(bar)))) { pressKey(KeyEvent.VK_RIGHT, 0); releaseKey(KeyEvent.VK_RIGHT, 0); if(maxTime.expired()) { throw(new TimeoutExpiredException("AppleMenuDriver: can not find an appropriate menu!")); } } for(int depth = 1; depth < chooser.getDepth(); depth++) { // TODO - wait for menu item int elementIndex = getDesiredElementIndex(menuObject, chooser, depth); if(elementIndex == -1) { throw(new JemmyException("Unable to find menu (menuitem): " + ((DescriptablePathChooser)chooser).getDescription())); } for(int i = ((depth == 1) ? 0 : 1); i<=elementIndex; i++) { pressKey(KeyEvent.VK_DOWN, 0); releaseKey(KeyEvent.VK_DOWN, 0); } if(depth == chooser.getDepth() - 1) { pressKey(KeyEvent.VK_ENTER, 0); releaseKey(KeyEvent.VK_ENTER, 0); return(null); } else { pressKey(KeyEvent.VK_RIGHT, 0); releaseKey(KeyEvent.VK_RIGHT, 0); menuObject = menuObject.getSubElements()[0].getSubElements()[elementIndex]; } } return menuObject; } private void activateMenu(JMenuBar bar) { if(getSelectedElement(bar) == null) { tryToActivate(); if(getSelectedElement(bar) == null) { tryToActivate(); } } } private void tryToActivate() { moveMouse(0, 0); pressMouse(Operator.getDefaultMouseButton(), 0); releaseMouse(Operator.getDefaultMouseButton(), 0); pressKey(KeyEvent.VK_RIGHT, 0); releaseKey(KeyEvent.VK_RIGHT, 0); pressKey(KeyEvent.VK_RIGHT, 0); releaseKey(KeyEvent.VK_RIGHT, 0); } private static MenuElement getSelectedElement(MenuElement bar) { MenuElement[] subElements = bar.getSubElements(); for(int i = 0; i < subElements.length; i++) { if(subElements[i] instanceof JMenu && ((JMenu)subElements[i]).isSelected()) { return(subElements[i]); } else if(subElements[i] instanceof JMenuItem && ((JMenuItem)subElements[i]).isSelected()) { return(subElements[i]); } } return(null); } private static int getDesiredElementIndex(MenuElement bar, PathChooser chooser, int depth) { MenuElement[] subElements = bar.getSubElements()[0].getSubElements(); int realIndex = 0; for(int i = 0; i < subElements.length; i++) { // do not count invisible and disabled menu items if(subElements[i] instanceof JMenuItem && ((JMenuItem)subElements[i]).isVisible() && ((JMenuItem)subElements[i]).isEnabled()) { if(chooser.checkPathComponent(depth, subElements[i])) { return realIndex; } realIndex++; } } return(-1); } } Jemmy2/src/org/netbeans/jemmy/drivers/menus/DefaultJMenuDriver.java0000644000175000017500000002453011245712237024442 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.menus; import java.awt.Component; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.MenuElement; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.Waitable; import org.netbeans.jemmy.Waiter; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.MenuDriver; import org.netbeans.jemmy.drivers.MouseDriver; import org.netbeans.jemmy.drivers.PathChooser; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JMenuBarOperator; import org.netbeans.jemmy.operators.JMenuItemOperator; import org.netbeans.jemmy.operators.JMenuOperator; import org.netbeans.jemmy.operators.JPopupMenuOperator; public class DefaultJMenuDriver extends LightSupportiveDriver implements MenuDriver { public DefaultJMenuDriver() { super(new String[] {"org.netbeans.jemmy.operators.JMenuOperator", "org.netbeans.jemmy.operators.JMenuBarOperator", "org.netbeans.jemmy.operators.JPopupMenuOperator"}); } public Object pushMenu(ComponentOperator oper, PathChooser chooser) { checkSupported(oper); if(oper instanceof JMenuBarOperator || oper instanceof JPopupMenuOperator) { JMenuItem item; if(oper instanceof JMenuBarOperator) { item = waitItem(oper, (JMenuBar)oper.getSource(), chooser, 0); } else { item = waitItem(oper, (JPopupMenu)oper.getSource(), chooser, 0); } JMenuItemOperator itemOper; if(item instanceof JMenu) { itemOper = new JMenuOperator((JMenu)item); } else if(item instanceof JMenuItem) { itemOper = new JMenuItemOperator(item); } else { return(null); } itemOper.copyEnvironment(oper); return(push(itemOper, null, (oper instanceof JMenuBarOperator) ? ((JMenuBar)oper.getSource()) : null, chooser, 1, true)); } else { return(push(oper, null, null, chooser, 0, true)); } } protected Object push(ComponentOperator oper, ComponentOperator lastItem, JMenuBar menuBar, PathChooser chooser, int depth, boolean pressMouse) { try { oper.waitComponentVisible(true); oper.waitComponentEnabled(); } catch(InterruptedException e) { throw(new JemmyException("Interrupted!", e)); } MouseDriver mDriver = DriverManager.getMouseDriver(oper); //mDriver.enterMouse(oper); //use enhanced algorithm instead smartMove(lastItem, oper); if(depth > chooser.getDepth() - 1) { if(oper instanceof JMenuOperator && menuBar != null && getSelectedElement(menuBar) != null) { //mDriver.enterMouse(oper); } else { DriverManager.getButtonDriver(oper).push(oper); } return(oper.getSource()); } if(pressMouse && !((JMenuOperator)oper).isPopupMenuVisible() && !(menuBar != null && getSelectedElement(menuBar) != null)) { DriverManager.getButtonDriver(oper).push(oper); } oper.getTimeouts().sleep("JMenuOperator.WaitBeforePopupTimeout"); JMenuItem item = waitItem(oper, waitPopupMenu(oper), chooser, depth); mDriver.exitMouse(oper); if(item instanceof JMenu) { JMenuOperator mo = new JMenuOperator((JMenu)item); mo.copyEnvironment(oper); return(push(mo, oper, null, chooser, depth + 1, false)); } else { JMenuItemOperator mio = new JMenuItemOperator(item); mio.copyEnvironment(oper); try { mio.waitComponentEnabled(); } catch(InterruptedException e) { throw(new JemmyException("Interrupted!", e)); } //move here first smartMove(oper, mio); DriverManager.getButtonDriver(oper).push(mio); return(item); } } private void smartMove(ComponentOperator last, ComponentOperator oper) { if(last == null) { oper.enterMouse(); return; } //get all the coordinates first //previous item long lastXl, lastXr, lastYl, lastYr; lastXl = (long)last.getSource().getLocationOnScreen().getX(); lastXr = lastXl + last.getSource().getWidth(); lastYl = (long)last.getSource().getLocationOnScreen().getY(); lastYr = lastYl + last.getSource().getHeight(); //this item long operXl, operXr, operYl, operYr; operXl = (long)oper.getSource().getLocationOnScreen().getX(); operXr = operXl + oper.getSource().getWidth(); operYl = (long)oper.getSource().getLocationOnScreen().getY(); operYr = operYl + oper.getSource().getHeight(); //get the overlap borders long overXl, overXr, overYl, overYr; overXl = (lastXl > operXl) ? lastXl : operXl; overXr = (lastXr < operXr) ? lastXr : operXr; overYl = (lastYl > operYl) ? lastYl : operYl; overYr = (lastYr < operYr) ? lastYr : operYr; //now, let's see ... //what if it overlaps by x? if(overXl < overXr) { //good - move mose to the center of the overlap last.moveMouse((int)((overXr - overXl) / 2 - lastXl), last.getCenterY()); //move mouse inside oper.moveMouse((int)((overXr - overXl) / 2 - operXl), oper.getCenterY()); //done - now move to the center oper.enterMouse(); return; } //ok, what if it overlaps by y? if(overYl < overYr) { //good - move mose to the center of the overlap last.moveMouse(last.getCenterX(), (int)((overYr - overYl) / 2 - lastYl)); //move mouse inside oper.moveMouse(last.getCenterX(), (int)((overYr - overYl) / 2 - operYl)); //done - now move to the center oper.enterMouse(); return; } //well - can't help it oper.enterMouse(); } protected JPopupMenu waitPopupMenu(final ComponentOperator oper) { return((JPopupMenu)JPopupMenuOperator.waitJPopupMenu(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp == ((JMenuOperator)oper).getPopupMenu() && comp.isShowing()); } public String getDescription() { return(((JMenuOperator)oper).getText() + "'s popup"); } }).getSource()); } protected JMenuItem waitItem(ComponentOperator oper, MenuElement element, PathChooser chooser, int depth) { Waiter waiter = new Waiter(new JMenuItemWaiter(element, chooser, depth)); waiter.setOutput(oper.getOutput().createErrorOutput()); waiter.setTimeouts(oper.getTimeouts()); try { return((JMenuItem)waiter.waitAction(null)); } catch(InterruptedException e) { throw(new JemmyException("Waiting has been interrupted", e)); } } public static Object getSelectedElement(JMenuBar bar) { MenuElement[] subElements = bar.getSubElements(); for(int i = 0; i < subElements.length; i++) { if(subElements[i] instanceof JMenu && ((JMenu)subElements[i]).isPopupMenuVisible()) { return(subElements[i]); } } return(null); } private class JMenuItemWaiter implements Waitable { MenuElement cont; PathChooser chooser; int depth; public JMenuItemWaiter(MenuElement cont, PathChooser chooser, int depth) { this.cont = cont; this.chooser = chooser; this.depth = depth; } public Object actionProduced(Object obj) { if(!((Component)cont).isShowing()) { return(null); } MenuElement[] subElements = cont.getSubElements(); for(int i = 0; i < subElements.length; i++) { if(((Component)subElements[i]).isShowing() && ((Component)subElements[i]).isEnabled() && chooser.checkPathComponent(depth, subElements[i])) { return subElements[i]; } } return(null); } public String getDescription() { return(""); } } } Jemmy2/src/org/netbeans/jemmy/drivers/menus/QueueJMenuDriver.java0000644000175000017500000003233711245712237024146 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.menus; import java.awt.Component; import java.awt.Window; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.MenuElement; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.Waitable; import org.netbeans.jemmy.Waiter; import org.netbeans.jemmy.drivers.DescriptablePathChooser; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.MenuDriver; import org.netbeans.jemmy.drivers.PathChooser; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JMenuBarOperator; import org.netbeans.jemmy.operators.JMenuItemOperator; import org.netbeans.jemmy.operators.JMenuOperator; import org.netbeans.jemmy.operators.JPopupMenuOperator; /** * * 100% stable menu driver. * Tries to do next steps during one action executed through EventQueue:
* find showing window containing popup
* find showing popup
* find showing menuitem
* enter mouse into it
* * Repeats this action as many times as "JMenuOperator.WaitPopupTimeout" timeout allows. * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class QueueJMenuDriver extends LightSupportiveDriver implements MenuDriver { QueueTool queueTool; public QueueJMenuDriver() { super(new String[] {"org.netbeans.jemmy.operators.JMenuOperator", "org.netbeans.jemmy.operators.JMenuBarOperator", "org.netbeans.jemmy.operators.JPopupMenuOperator"}); queueTool = new QueueTool(); } public Object pushMenu(final ComponentOperator oper, PathChooser chooser) { queueTool.setOutput(oper.getOutput().createErrorOutput()); checkSupported(oper); JMenuItem result; OneReleaseAction action; if(oper instanceof JMenuBarOperator) { action = new OneReleaseAction(chooser, 0, oper, false) { protected void pushAlone(JMenuItemOperator subMenuOper) { if(subMenuOper.getSource() instanceof JMenu && isMenuBarSelected((JMenuBar)oper.getSource())) { DriverManager.getMouseDriver(subMenuOper).enterMouse(subMenuOper); } else { DriverManager.getButtonDriver(subMenuOper).push(subMenuOper); } } protected boolean inTheMiddle(JMenuOperator subMenuOper, boolean mousePressed) { if(isMenuBarSelected((JMenuBar)oper.getSource())) { DriverManager.getMouseDriver(subMenuOper).enterMouse(subMenuOper); return(false); } else { return(super.inTheMiddle(subMenuOper, mousePressed)); } } protected void process(MenuElement element) { super.process(element); } public MenuElement getMenuElement() { return((MenuElement)oper.getSource()); } }; } else if(oper instanceof JPopupMenuOperator) { action = new OneReleaseAction(chooser, 0, oper, false) { public MenuElement getMenuElement() { return((MenuElement)oper.getSource()); } }; } else { DriverManager.getButtonDriver(oper).press(oper); action = new OneReleaseAction(chooser, 0, oper, false) { public Object launch() { process((MenuElement)oper.getSource()); return((MenuElement)oper.getSource()); } public MenuElement getMenuElement() { return(null); } }; } //1.5 workaround if(System.getProperty("java.specification.version").compareTo("1.4") > 0) { queueTool.setOutput(oper.getOutput().createErrorOutput()); queueTool.waitEmpty(10); queueTool.waitEmpty(10); queueTool.waitEmpty(10); } //end of 1.5 workaround result = runAction(action, oper, oper.getTimeouts().getTimeout("ComponentOperator.WaitComponentTimeout"), (chooser instanceof DescriptablePathChooser) ? ((DescriptablePathChooser)chooser).getDescription() : "Menu pushing"); if(result instanceof JMenu) { for(int i = 1; i < chooser.getDepth(); i++) { final JMenu menu = (JMenu)result; final ComponentChooser popupChooser = new PopupMenuChooser(menu); action = new OneReleaseAction(chooser, i, oper, action.mousePressed) { public MenuElement getMenuElement() { Window win = JPopupMenuOperator.findJPopupWindow(popupChooser); if(win != null && win.isShowing()) { return(JPopupMenuOperator.findJPopupMenu(win, popupChooser)); } else { return(null); } } }; result = (JMenuItem)runAction(action, oper, oper.getTimeouts().getTimeout("JMenuOperator.WaitPopupTimeout"), (chooser instanceof DescriptablePathChooser) ? ((DescriptablePathChooser)chooser).getDescription() : "Menu pushing"); } } return(result); } private JMenuItem runAction(final OneReleaseAction action, ComponentOperator env, long waitingTime, final String description) { Waiter waiter = new Waiter(new Waitable() { public Object actionProduced(Object param) { return(queueTool.invokeSmoothly(action)); } public String getDescription() { return(description); } }); waiter.setOutput(env.getOutput().createErrorOutput()); waiter.setTimeouts(env.getTimeouts().cloneThis()); waiter.getTimeouts().setTimeout("Waiter.WaitingTime", waitingTime); waiter.getTimeouts().setTimeout("Waiter.TimeDelta", 100); //1.5 workaround if(System.getProperty("java.specification.version").compareTo("1.4") > 0) { queueTool.setOutput(env.getOutput().createErrorOutput()); queueTool.waitEmpty(10); queueTool.waitEmpty(10); queueTool.waitEmpty(10); } //end of 1.5 workaround try { return((JMenuItem)waiter.waitAction(null)); } catch(InterruptedException e) { action.stop(); throw(new JemmyException("Waiting has been interrupted", e)); } } private boolean isMenuBarSelected(JMenuBar bar) { MenuElement[] subElements = bar.getSubElements(); for(int i = 0; i < subElements.length; i++) { if(subElements[i] instanceof JMenu && ((JMenu)subElements[i]).isPopupMenuVisible()) { return(true); } } return(false); } private abstract class OneReleaseAction extends QueueTool.QueueAction { PathChooser chooser; int depth; ComponentOperator env; boolean mousePressed = false; private boolean stopped = false; public OneReleaseAction(PathChooser chooser, int depth, ComponentOperator env, boolean mousePressed) { super("Menu pushing"); this.chooser = chooser; this.depth = depth; this.env = env; this.mousePressed = mousePressed; } protected void pushAlone(JMenuItemOperator subMenuOper) { DriverManager.getButtonDriver(subMenuOper).push(subMenuOper); } protected void pushLast(JMenuItemOperator subMenuOper, boolean mousePressed) { DriverManager.getMouseDriver(subMenuOper).enterMouse(subMenuOper); DriverManager.getButtonDriver(subMenuOper).release(subMenuOper); } protected boolean inTheMiddle(JMenuOperator subMenuOper, boolean mousePressed) { if(!subMenuOper.isPopupMenuVisible()) { if(!mousePressed) { DriverManager.getMouseDriver(subMenuOper).enterMouse(subMenuOper); DriverManager.getButtonDriver(subMenuOper).press(subMenuOper); } else { DriverManager.getMouseDriver(subMenuOper).enterMouse(subMenuOper); } return(true); } return(mousePressed); } protected void process(MenuElement element) { if(depth == chooser.getDepth() - 1) { JMenuItemOperator subMenuOper = new JMenuItemOperator((JMenuItem)element); subMenuOper.copyEnvironment(env); if(depth == 0) { pushAlone(subMenuOper); } else { pushLast(subMenuOper, mousePressed); } } else { if(element instanceof JMenu) { JMenuOperator subMenuOper = new JMenuOperator((JMenu)element); subMenuOper.copyEnvironment(env); mousePressed = inTheMiddle(subMenuOper, mousePressed); } else { throw(new JemmyException("Menu path too long")); } } } public Object launch() { MenuElement element = getMenuElement(); if(element != null) { MenuElement[] subElements = element.getSubElements(); for(int i = 0; i < subElements.length; i++) { if(((Component)subElements[i]).isShowing() && ((Component)subElements[i]).isEnabled() && chooser.checkPathComponent(depth, subElements[i])) { process(subElements[i]); return(subElements[i]); } if(stopped) { return(null); } } } return(null); } public abstract MenuElement getMenuElement(); private void stop() { stopped = true; } } private class PopupMenuChooser implements ComponentChooser { JMenu menu; public PopupMenuChooser(JMenu menu) { this.menu = menu; } public boolean checkComponent(Component comp) { return(comp == menu.getPopupMenu() && comp.isShowing() && comp.isEnabled()); } public String getDescription() { return(menu.getText() + "'s popup"); } } } Jemmy2/src/org/netbeans/jemmy/drivers/ListDriver.java0000644000175000017500000000462211064436407021704 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to work with lists. */ public interface ListDriver { /** * Selects an item. * @param oper List operator. * @param index Item index. */ public void selectItem(ComponentOperator oper, int index); } Jemmy2/src/org/netbeans/jemmy/drivers/MultiSelListDriver.java0000644000175000017500000000472411064436407023366 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to work with lists allowing multiple selection. */ public interface MultiSelListDriver extends ListDriver { /** * Selects some items. * @param oper List operator. * @param indices Item indices. */ public void selectItems(ComponentOperator oper, int[] indices); } Jemmy2/src/org/netbeans/jemmy/drivers/InternalFrameDriver.java0000644000175000017500000000474111064436407023522 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import java.awt.Component; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines the way to get a title pane. */ public interface InternalFrameDriver { /** * Returns the title pane component. * @param oper operator for an internal frame. * @return a component - title pane. */ public Component getTitlePane(ComponentOperator oper); } Jemmy2/src/org/netbeans/jemmy/drivers/DefaultDriverInstaller.java0000644000175000017500000001735611245712237024242 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.ClassReference; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.drivers.buttons.ButtonMouseDriver; import org.netbeans.jemmy.drivers.focus.APIFocusDriver; import org.netbeans.jemmy.drivers.focus.MouseFocusDriver; import org.netbeans.jemmy.drivers.lists.ChoiceDriver; import org.netbeans.jemmy.drivers.lists.JComboMouseDriver; import org.netbeans.jemmy.drivers.lists.JListMouseDriver; import org.netbeans.jemmy.drivers.lists.JTabMouseDriver; import org.netbeans.jemmy.drivers.lists.JTableHeaderDriver; import org.netbeans.jemmy.drivers.lists.ListKeyboardDriver; import org.netbeans.jemmy.drivers.menus.DefaultJMenuDriver; import org.netbeans.jemmy.drivers.menus.QueueJMenuDriver; import org.netbeans.jemmy.drivers.scrolling.JScrollBarDriver; import org.netbeans.jemmy.drivers.scrolling.JSliderDriver; import org.netbeans.jemmy.drivers.scrolling.JSplitPaneDriver; import org.netbeans.jemmy.drivers.scrolling.ScrollPaneDriver; import org.netbeans.jemmy.drivers.scrolling.ScrollbarDriver; import org.netbeans.jemmy.drivers.tables.JTableMouseDriver; import org.netbeans.jemmy.drivers.text.AWTTextKeyboardDriver; import org.netbeans.jemmy.drivers.text.SwingTextKeyboardDriver; import org.netbeans.jemmy.drivers.trees.JTreeMouseDriver; import org.netbeans.jemmy.drivers.windows.DefaultFrameDriver; import org.netbeans.jemmy.drivers.windows.DefaultInternalFrameDriver; import org.netbeans.jemmy.drivers.windows.DefaultWindowDriver; /** * Installs all necessary drivers for Jemmy operators except * low-level drivers which are installed by * InputDriverInstaller. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class DefaultDriverInstaller extends ArrayDriverInstaller { /** * Constructs a DefaultDriverInstaller object. * @param shortcutEvents Signals whether shortcut mode is used. */ public DefaultDriverInstaller(boolean shortcutEvents) { super(new String[] { DriverManager.LIST_DRIVER_ID, DriverManager.MULTISELLIST_DRIVER_ID, DriverManager.TREE_DRIVER_ID, DriverManager.TEXT_DRIVER_ID, DriverManager.TEXT_DRIVER_ID, DriverManager.SCROLL_DRIVER_ID, DriverManager.SCROLL_DRIVER_ID, DriverManager.SCROLL_DRIVER_ID, DriverManager.SCROLL_DRIVER_ID, DriverManager.SCROLL_DRIVER_ID, DriverManager.SCROLL_DRIVER_ID, DriverManager.BUTTON_DRIVER_ID, DriverManager.LIST_DRIVER_ID, DriverManager.LIST_DRIVER_ID, DriverManager.MULTISELLIST_DRIVER_ID, DriverManager.LIST_DRIVER_ID, DriverManager.LIST_DRIVER_ID, DriverManager.MULTISELLIST_DRIVER_ID, DriverManager.TABLE_DRIVER_ID, DriverManager.LIST_DRIVER_ID, DriverManager.FRAME_DRIVER_ID, DriverManager.WINDOW_DRIVER_ID, DriverManager.FRAME_DRIVER_ID, DriverManager.INTERNAL_FRAME_DRIVER_ID, DriverManager.WINDOW_DRIVER_ID, DriverManager.FOCUS_DRIVER_ID, DriverManager.FOCUS_DRIVER_ID, DriverManager.MENU_DRIVER_ID, DriverManager.ORDEREDLIST_DRIVER_ID}, new Object[] { new JTreeMouseDriver(), new JTreeMouseDriver(), new JTreeMouseDriver(), new AWTTextKeyboardDriver(), new SwingTextKeyboardDriver(), new ScrollbarDriver(), new ScrollPaneDriver(), new JScrollBarDriver(), new JSplitPaneDriver(), new JSliderDriver(), createSpinnerDriver(), new ButtonMouseDriver(), new JTabMouseDriver(), new ListKeyboardDriver(), new ListKeyboardDriver(), new JComboMouseDriver(), new JListMouseDriver(), new JListMouseDriver(), new JTableMouseDriver(), new ChoiceDriver(), new DefaultFrameDriver(), new DefaultWindowDriver(), new DefaultInternalFrameDriver(), new DefaultInternalFrameDriver(), new DefaultInternalFrameDriver(), new APIFocusDriver(), new MouseFocusDriver(), (shortcutEvents ? ((Object)new QueueJMenuDriver()) : ((Object)new DefaultJMenuDriver())), new JTableHeaderDriver()}); } /** * Constructs a DefaultDriverInstaller object with shortcut mode flag * taken from JemmyProperties. */ public DefaultDriverInstaller() { this((JemmyProperties.getCurrentDispatchingModel() & JemmyProperties.SHORTCUT_MODEL_MASK) != 0); } private static LightDriver createSpinnerDriver() { if(System.getProperty("java.specification.version").compareTo("1.3") > 0) { try { return((LightDriver)new ClassReference("org.netbeans.jemmy.drivers.scrolling.JSpinnerDriver"). newInstance(null, null)); } catch(ClassNotFoundException e) { JemmyProperties.getCurrentOutput(). printErrLine("ATTENTION! you are using Jemmy built by Java earlier then 1.4, under " + "Java 1.4. \nImpossible to create JSpinnerDriver"); return(createEmptyDriver()); } catch(Exception e) { throw(new JemmyException("Impossible to create JSpinnerDriver although java version is " + System.getProperty("java.version"), e)); } } else { return(createEmptyDriver()); } } private static LightDriver createEmptyDriver() { return(new LightDriver() { public String[] getSupported() { return(new String[] {Object.class.getName()}); }}); } } Jemmy2/src/org/netbeans/jemmy/drivers/focus/0000755000175000017500000000000011572745223020070 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/drivers/focus/MouseFocusDriver.java0000644000175000017500000000744311245712237024203 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.focus; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.FocusDriver; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.operators.ComponentOperator; public class MouseFocusDriver extends LightSupportiveDriver implements FocusDriver { private QueueTool queueTool; public MouseFocusDriver() { super(new String[] { "org.netbeans.jemmy.operators.JListOperator", "org.netbeans.jemmy.operators.JScrollBarOperator", "org.netbeans.jemmy.operators.JSliderOperator", "org.netbeans.jemmy.operators.JTableOperator", "org.netbeans.jemmy.operators.JTextComponentOperator", "org.netbeans.jemmy.operators.JTreeOperator", "org.netbeans.jemmy.operators.ListOperator", "org.netbeans.jemmy.operators.ScrollbarOperator", "org.netbeans.jemmy.operators.TextAreaOperator", "org.netbeans.jemmy.operators.TextComponentOperator", "org.netbeans.jemmy.operators.TextFieldOperator"}); queueTool = new QueueTool(); } public void giveFocus(final ComponentOperator oper) { if(!oper.hasFocus()) { queueTool.invokeSmoothly(new QueueTool.QueueAction("Mouse click to get focus") { public Object launch() { DriverManager.getMouseDriver(oper). clickMouse(oper, oper.getCenterXForClick(), oper.getCenterYForClick(), 1, oper.getDefaultMouseButton(), 0, oper.getTimeouts().create("ComponentOperator.MouseClickTimeout")); return(null); } }); oper.waitHasFocus(); } } } Jemmy2/src/org/netbeans/jemmy/drivers/focus/package.html0000644000175000017500000000035411064436407022350 0ustar tonytony Focus drivers.

Focus drivers.

Different drivers to give input focus to a component.

Jemmy2/src/org/netbeans/jemmy/drivers/focus/APIFocusDriver.java0000644000175000017500000000546311245712237023524 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.focus; import java.awt.event.FocusEvent; import org.netbeans.jemmy.drivers.FocusDriver; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.input.EventDriver; import org.netbeans.jemmy.operators.ComponentOperator; public class APIFocusDriver extends LightSupportiveDriver implements FocusDriver { EventDriver eDriver; public APIFocusDriver() { super(new String[] {"org.netbeans.jemmy.operators.ComponentOperator"}); eDriver = new EventDriver(); } public void giveFocus(ComponentOperator operator) { operator.requestFocus(); eDriver.dispatchEvent(operator.getSource(), new FocusEvent(operator.getSource(), FocusEvent.FOCUS_GAINED)); } } Jemmy2/src/org/netbeans/jemmy/drivers/WindowDriver.java0000644000175000017500000000652611247147442022246 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to work with windows. */ public interface WindowDriver { /** * Activates a window. * @param oper Window operator. */ public void activate(ComponentOperator oper); /** * Requests a window to close. * @param oper Window operator. */ public void requestClose(ComponentOperator oper); /** * Closes a window by requesting it to close and then hiding it. * @param oper Window operator. */ public void requestCloseAndThenHide(ComponentOperator oper); /** * Closes a window by requesting it to close and then hiding it. * @param oper Window operator. * @deprecated Use requestClose(ComponentOperator) instead. */ public void close(ComponentOperator oper); /** * Change window location. * @param oper Window operator. * @param x New x coordinate * @param y New y coordinate */ public void move(ComponentOperator oper, int x, int y); /** * Change window size. * @param oper Window operator. * @param width New window width. * @param height New window height. */ public void resize(ComponentOperator oper, int width, int height); } Jemmy2/src/org/netbeans/jemmy/drivers/KeyDriver.java0000644000175000017500000000724311245712237021522 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to simulate keyboard operations. */ public interface KeyDriver { /** * Presses a key. * @param oper Component operator. * @param keyCode Key code (KeyEvent.VK_* value) * @param modifiers a combination of InputEvent.*_MASK fields. */ public void pressKey(ComponentOperator oper, int keyCode, int modifiers); /** * Releases a key. * @param oper Component operator. * @param keyCode Key code (KeyEvent.VK_* value) * @param modifiers a combination of InputEvent.*_MASK fields. */ public void releaseKey(ComponentOperator oper, int keyCode, int modifiers); /** * Pushes a key. * @param oper Component operator. * @param keyCode Key code (KeyEvent.VK_* value) * @param modifiers a combination of InputEvent.*_MASK fields. * @param pushTime Time between pressing and releasing. */ public void pushKey(ComponentOperator oper, int keyCode, int modifiers, Timeout pushTime); /** * Types a symbol. * @param oper Component operator. * @param keyCode Key code (KeyEvent.VK_* value) * @param keyChar Symbol to be typed. * @param modifiers a combination of InputEvent.*_MASK fields. * @param pushTime Time between pressing and releasing. */ public void typeKey(ComponentOperator oper, int keyCode, char keyChar, int modifiers, Timeout pushTime); } Jemmy2/src/org/netbeans/jemmy/drivers/windows/0000755000175000017500000000000011572745223020443 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/drivers/windows/package.html0000644000175000017500000000035211064436407022721 0ustar tonytony Window drivers.

Window drivers.

Different drivers to perform a window operations.

Jemmy2/src/org/netbeans/jemmy/drivers/windows/DefaultFrameDriver.java0000644000175000017500000000711411245712237025020 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.windows; import java.awt.Dimension; import java.awt.Frame; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.WindowEvent; import org.netbeans.jemmy.drivers.FrameDriver; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.input.EventDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.FrameOperator; public class DefaultFrameDriver extends LightSupportiveDriver implements FrameDriver { EventDriver eDriver; public DefaultFrameDriver() { super(new String[] {"org.netbeans.jemmy.operators.FrameOperator"}); eDriver = new EventDriver(); } public void iconify(ComponentOperator oper) { checkSupported(oper); eDriver.dispatchEvent(oper.getSource(), new WindowEvent((Window)oper.getSource(), WindowEvent.WINDOW_ICONIFIED)); ((FrameOperator)oper).setState(Frame.ICONIFIED); } public void deiconify(ComponentOperator oper) { checkSupported(oper); eDriver.dispatchEvent(oper.getSource(), new WindowEvent((Window)oper.getSource(), WindowEvent.WINDOW_DEICONIFIED)); ((FrameOperator)oper).setState(Frame.NORMAL); } public void maximize(ComponentOperator oper) { checkSupported(oper); ((FrameOperator)oper).setLocation(0, 0); Dimension ssize = Toolkit.getDefaultToolkit().getScreenSize(); ((FrameOperator)oper).setSize(ssize.width, ssize.height); } public void demaximize(ComponentOperator oper) { checkSupported(oper); } } Jemmy2/src/org/netbeans/jemmy/drivers/windows/DefaultInternalFrameDriver.java0000644000175000017500000001325111247147442026516 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.windows; import java.awt.Component; import java.awt.Container; import javax.swing.plaf.basic.BasicInternalFrameTitlePane; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.drivers.FrameDriver; import org.netbeans.jemmy.drivers.InternalFrameDriver; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.WindowDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JButtonOperator; import org.netbeans.jemmy.operators.JInternalFrameOperator; public class DefaultInternalFrameDriver extends LightSupportiveDriver implements WindowDriver, FrameDriver, InternalFrameDriver { public DefaultInternalFrameDriver() { super(new String[] {"org.netbeans.jemmy.operators.JInternalFrameOperator"}); } public void activate(ComponentOperator oper) { checkSupported(oper); ((JInternalFrameOperator)oper).moveToFront(); ((JInternalFrameOperator)oper).getTitleOperator().clickMouse(); } public void requestClose(ComponentOperator oper) { checkSupported(oper); ((JInternalFrameOperator)oper).moveToFront(); ((JButtonOperator)((JInternalFrameOperator)oper).getCloseButton()).push(); } public void requestCloseAndThenHide(ComponentOperator oper) { throw new UnsupportedOperationException(); } public void close(ComponentOperator oper) { requestClose(oper); } public void move(ComponentOperator oper, int x, int y) { checkSupported(oper); ComponentOperator titleOperator = ((JInternalFrameOperator)oper).getTitleOperator(); titleOperator.dragNDrop(titleOperator.getCenterY(), titleOperator.getCenterY(), x - ((JInternalFrameOperator)oper).getX() + titleOperator.getCenterY(), y - ((JInternalFrameOperator)oper).getY() + titleOperator.getCenterY()); } public void resize(ComponentOperator oper, int width, int height) { checkSupported(oper); ((JInternalFrameOperator)oper). dragNDrop(((JInternalFrameOperator)oper).getWidth() - 1, ((JInternalFrameOperator)oper).getHeight() - 1, width - 1, height - 1); } public void iconify(ComponentOperator oper) { checkSupported(oper); ((JButtonOperator)((JInternalFrameOperator)oper).getMinimizeButton()).clickMouse(); } public void deiconify(ComponentOperator oper) { checkSupported(oper); ((JInternalFrameOperator)oper).getIconOperator().pushButton(); } public void maximize(ComponentOperator oper) { checkSupported(oper); if(!((JInternalFrameOperator)oper).isMaximum()) { if(!((JInternalFrameOperator)oper).isSelected()) { activate(oper); } ((JInternalFrameOperator)oper).getMaximizeButton().push(); } } public void demaximize(ComponentOperator oper) { checkSupported(oper); if(((JInternalFrameOperator)oper).isMaximum()) { if(!((JInternalFrameOperator)oper).isSelected()) { activate(oper); } ((JInternalFrameOperator)oper).getMaximizeButton().push(); } } public Component getTitlePane(ComponentOperator operator) { ComponentSearcher cs = new ComponentSearcher((Container)operator.getSource()); cs.setOutput(operator.getOutput().createErrorOutput()); return(cs.findComponent(new ComponentChooser() { public boolean checkComponent(Component comp) { if(System.getProperty("java.version").startsWith("1.2")) { return(comp.getClass().getName().endsWith("InternalFrameTitlePane")); } else { return(comp instanceof BasicInternalFrameTitlePane); } } public String getDescription() { return("Title pane"); } })); } } Jemmy2/src/org/netbeans/jemmy/drivers/windows/DefaultWindowDriver.java0000644000175000017500000001014511247147442025235 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.windows; import java.awt.Window; import java.awt.event.ComponentEvent; import java.awt.event.FocusEvent; import java.awt.event.WindowEvent; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.WindowDriver; import org.netbeans.jemmy.drivers.input.EventDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.WindowOperator; public class DefaultWindowDriver extends LightSupportiveDriver implements WindowDriver { EventDriver eDriver; public DefaultWindowDriver() { super(new String[] {"org.netbeans.jemmy.operators.WindowOperator"}); eDriver = new EventDriver(); } public void activate(ComponentOperator oper) { checkSupported(oper); if(((WindowOperator)oper).getFocusOwner() == null) { ((WindowOperator)oper).toFront(); } eDriver.dispatchEvent(oper.getSource(), new WindowEvent((Window)oper.getSource(), WindowEvent.WINDOW_ACTIVATED)); eDriver.dispatchEvent(oper.getSource(), new FocusEvent((Window)oper.getSource(), FocusEvent.FOCUS_GAINED)); } public void requestClose(ComponentOperator oper) { checkSupported(oper); eDriver.dispatchEvent(oper.getSource(), new WindowEvent((Window)oper.getSource(), WindowEvent.WINDOW_CLOSING)); } public void requestCloseAndThenHide(ComponentOperator oper) { requestClose(oper); ((WindowOperator)oper).setVisible(false); } public void close(ComponentOperator oper) { requestCloseAndThenHide(oper); } public void move(ComponentOperator oper, int x, int y) { checkSupported(oper); ((WindowOperator)oper).setLocation(x, y); } public void resize(ComponentOperator oper, int width, int height) { checkSupported(oper); ((WindowOperator)oper).setSize(width, height); eDriver.dispatchEvent(oper.getSource(), new ComponentEvent((Window)oper.getSource(), ComponentEvent.COMPONENT_RESIZED)); } } Jemmy2/src/org/netbeans/jemmy/drivers/ArrayDriverInstaller.java0000644000175000017500000000576511064436407023736 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; /** * Auxiliary class making driver registration easier. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class ArrayDriverInstaller implements DriverInstaller { String[] ids; Object[] drivers; /** * Constructs an ArrayDriverInstaller object. * Both parameter arrays mush have same length, * drivers must keep instances of * Driver or * LightDriver implementations. * @param ids an array of driver IDs * @param drivers an array of drivers. */ public ArrayDriverInstaller(String[] ids, Object[] drivers) { this.ids = ids; this.drivers = drivers; } /** * Installs drivers from the array passed into constructor. */ public void install() { for(int i = 0; i < ids.length; i++) { DriverManager.setDriver(ids[i], drivers[i]); } } } Jemmy2/src/org/netbeans/jemmy/drivers/input/0000755000175000017500000000000011572745223020110 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/drivers/input/MouseEventDriver.java0000644000175000017500000001547511245712237024231 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.input; import java.awt.Component; import java.awt.event.MouseEvent; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.MouseDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.Operator; /** * MouseDriver using event dispatching. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class MouseEventDriver extends EventDriver implements MouseDriver { /** * Constructs a MouseEventDriver object. * @param supported an array of supported class names */ public MouseEventDriver(String[] supported) { super(supported); } /** * Constructs a MouseEventDriver object. */ public MouseEventDriver() { super(); } public void pressMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers) { dispatchEvent(oper.getSource(), MouseEvent.MOUSE_PRESSED, modifiers, x, y, 1, mouseButton); } public void releaseMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers) { dispatchEvent(oper.getSource(), MouseEvent.MOUSE_RELEASED, modifiers, x, y, 1, mouseButton); } public void moveMouse(ComponentOperator oper, int x, int y) { dispatchEvent(oper.getSource(), MouseEvent.MOUSE_MOVED, 0, x, y, 0, Operator.getDefaultMouseButton()); } public void clickMouse(ComponentOperator oper, int x, int y, int clickCount, int mouseButton, int modifiers, Timeout mouseClick) { moveMouse(oper, x, y); dispatchEvent(oper.getSource(), MouseEvent.MOUSE_ENTERED, 0, x, y, 0, Operator.getDefaultMouseButton()); dispatchEvent(oper.getSource(), MouseEvent.MOUSE_PRESSED, modifiers, x, y, 1, mouseButton); for(int i = 1; i < clickCount; i++) { dispatchEvent(oper.getSource(), MouseEvent.MOUSE_RELEASED, modifiers, x, y, i, mouseButton); dispatchEvent(oper.getSource(), MouseEvent.MOUSE_CLICKED, modifiers, x, y, i, mouseButton); dispatchEvent(oper.getSource(), MouseEvent.MOUSE_PRESSED, modifiers, x, y, i + 1, mouseButton); } mouseClick.sleep(); dispatchEvent(oper.getSource(), MouseEvent.MOUSE_RELEASED, modifiers, x, y, clickCount, mouseButton); dispatchEvent(oper.getSource(), MouseEvent.MOUSE_CLICKED, modifiers, x, y, clickCount, mouseButton); exitMouse(oper); } public void dragMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers) { dispatchEvent(oper.getSource(), MouseEvent.MOUSE_DRAGGED, modifiers, x, y, 1, mouseButton); } public void dragNDrop(ComponentOperator oper, int start_x, int start_y, int end_x, int end_y, int mouseButton, int modifiers, Timeout before, Timeout after) { dispatchEvent(oper.getSource(), MouseEvent.MOUSE_ENTERED, 0, start_x, start_y, 0, Operator.getDefaultMouseButton()); dispatchEvent(oper.getSource(), MouseEvent.MOUSE_PRESSED, modifiers, start_x, start_y, 1, mouseButton); before.sleep(); dragMouse(oper, end_x, end_y, mouseButton, modifiers); after.sleep(); dispatchEvent(oper.getSource(), MouseEvent.MOUSE_RELEASED, modifiers, end_x, end_y, 1, mouseButton); exitMouse(oper); } public void enterMouse(ComponentOperator oper) { dispatchEvent(oper.getSource(), MouseEvent.MOUSE_ENTERED, 0, oper.getCenterX(), oper.getCenterY(), 0, Operator.getDefaultMouseButton()); } public void exitMouse(ComponentOperator oper) { dispatchEvent(oper.getSource(), MouseEvent.MOUSE_EXITED, 0, oper.getCenterX(), oper.getCenterY(), 0, Operator.getDefaultMouseButton()); } /** * Dispatches a mouse event to the component. * @param comp Component to dispatch events to. * @param id an event id. * @param modifiers a combination of InputEvent.*_MASK fields. * @param x relative x coordinate of event point * @param y relative y coordinate of event point * @param clickCount click count * @param mouseButton mouse button. */ protected void dispatchEvent(Component comp, int id, int modifiers, int x, int y, int clickCount, int mouseButton) { dispatchEvent(comp, new MouseEvent(comp, id, System.currentTimeMillis(), modifiers | mouseButton, x, y, clickCount, mouseButton == Operator.getPopupMouseButton() && id == MouseEvent.MOUSE_PRESSED)); } } Jemmy2/src/org/netbeans/jemmy/drivers/input/package.html0000644000175000017500000000043011064436407022363 0ustar tonytony Mouse and keyboard drivers

Mouse and keyboard drivers

Contains low-level drivers to perform user input.
@since 17 Apr 2002
Jemmy2/src/org/netbeans/jemmy/drivers/input/MouseRobotDriver.java0000644000175000017500000001361511245712304024222 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.input; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.MouseDriver; import org.netbeans.jemmy.operators.ComponentOperator; /** * MouseDriver using robot operations. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class MouseRobotDriver extends RobotDriver implements MouseDriver { /** * Constructs a MouseRobotDriver object. * @param autoDelay Time for Robot.setAutoDelay(long) method. */ public MouseRobotDriver(Timeout autoDelay) { super(autoDelay); } /** * Constructs a MouseRobotDriver object. * @param autoDelay Time for Robot.setAutoDelay(long) method. * @param smooth - whether to move mouse smooth from one ppoint to another. */ public MouseRobotDriver(Timeout autoDelay, boolean smooth) { super(autoDelay, smooth); } /** * Constructs a MouseRobotDriver object. * @param autoDelay Time for Robot.setAutoDelay(long) method. * @param supported an array of supported class names */ public MouseRobotDriver(Timeout autoDelay, String[] supported) { super(autoDelay, supported); } /** * Constructs a MouseRobotDriver object. * @param autoDelay Time for Robot.setAutoDelay(long) method. * @param supported an array of supported class names * @param smooth - whether to move mouse smooth from one ppoint to another. */ public MouseRobotDriver(Timeout autoDelay, String[] supported, boolean smooth) { super(autoDelay, supported, smooth); } public void pressMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers) { pressMouse(mouseButton, modifiers); } public void releaseMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers) { releaseMouse(mouseButton, modifiers); } public void moveMouse(ComponentOperator oper, int x, int y) { moveMouse(getAbsoluteX(oper, x), getAbsoluteY(oper, y)); } public void clickMouse(ComponentOperator oper, int x, int y, int clickCount, int mouseButton, int modifiers, Timeout mouseClick) { clickMouse(getAbsoluteX(oper, x), getAbsoluteY(oper, y), clickCount, mouseButton, modifiers, mouseClick); } public void dragMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers) { moveMouse(getAbsoluteX(oper, x), getAbsoluteY(oper, y)); } public void dragNDrop(ComponentOperator oper, int start_x, int start_y, int end_x, int end_y, int mouseButton, int modifiers, Timeout before, Timeout after) { dragNDrop(getAbsoluteX(oper, start_x), getAbsoluteY(oper, start_y), getAbsoluteX(oper, end_x), getAbsoluteY(oper, end_y), mouseButton, modifiers, before, after); } public void enterMouse(ComponentOperator oper) { moveMouse(oper, oper.getCenterXForClick(), oper.getCenterYForClick()); } public void exitMouse(ComponentOperator oper) { //better not go anywhere //exit will be executed during the next //mouse move anyway. // moveMouse(oper, -1, -1); } /** * Returns absolute x coordinate for relative x coordinate. * @param oper an operator * @param x a relative x coordinate. * @return an absolute x coordinate. */ protected int getAbsoluteX(ComponentOperator oper, int x) { return(oper.getSource().getLocationOnScreen().x + x); } /** * Returns absolute y coordinate for relative y coordinate. * @param oper an operator * @param y a relative y coordinate. * @return an absolute y coordinate. */ protected int getAbsoluteY(ComponentOperator oper, int y) { return(oper.getSource().getLocationOnScreen().y + y); } } Jemmy2/src/org/netbeans/jemmy/drivers/input/KeyEventDriver.java0000644000175000017500000001125411245712237023660 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.input; import java.awt.Component; import java.awt.event.KeyEvent; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.KeyDriver; import org.netbeans.jemmy.operators.ComponentOperator; /** * KeyDriver using event dispatching. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class KeyEventDriver extends EventDriver implements KeyDriver { /** * Constructs a KeyEventDriver object. * @param supported an array of supported class names */ public KeyEventDriver(String[] supported) { super(supported); } /** * Constructs an KeyEventDriver object suporting ComponentOperator. */ public KeyEventDriver() { super(); } public void pressKey(ComponentOperator oper, int keyCode, int modifiers) { pressKey(findNativeParent(oper.getSource()), keyCode, modifiers); } public void releaseKey(ComponentOperator oper, int keyCode, int modifiers) { releaseKey(findNativeParent(oper.getSource()), keyCode, modifiers); } public void pushKey(ComponentOperator oper, int keyCode, int modifiers, Timeout pushTime) { Component nativeContainer = findNativeParent(oper.getSource()); pressKey(nativeContainer, keyCode, modifiers); pushTime.sleep(); releaseKey(nativeContainer, keyCode, modifiers); } public void typeKey(ComponentOperator oper, int keyCode, char keyChar, int modifiers, Timeout pushTime) { Component nativeContainer = findNativeParent(oper.getSource()); pressKey(nativeContainer, keyCode, modifiers); pushTime.sleep(); dispatchEvent(nativeContainer, new KeyEvent(nativeContainer, KeyEvent.KEY_TYPED, System.currentTimeMillis(), modifiers, KeyEvent.VK_UNDEFINED, keyChar)); releaseKey(nativeContainer, keyCode, modifiers); } private void pressKey(Component nativeContainer, int keyCode, int modifiers) { dispatchEvent(nativeContainer, new KeyEvent(nativeContainer, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), modifiers, keyCode)); } private void releaseKey(Component nativeContainer, int keyCode, int modifiers) { dispatchEvent(nativeContainer, new KeyEvent(nativeContainer, KeyEvent.KEY_RELEASED, System.currentTimeMillis(), modifiers, keyCode)); } private Component findNativeParent(Component source) { Component nativeOne = source; while(nativeOne != null) { if(!nativeOne.isLightweight()) { return(nativeOne); } nativeOne = nativeOne.getParent(); } return(source); } } Jemmy2/src/org/netbeans/jemmy/drivers/input/EventDriver.java0000644000175000017500000001012611245712237023204 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.input; import java.awt.AWTEvent; import java.awt.Component; import org.netbeans.jemmy.ComponentIsNotVisibleException; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.drivers.LightSupportiveDriver; /** * Superclass for all drivers using event dispatching. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class EventDriver extends LightSupportiveDriver { QueueTool queueTool; /** * Constructs an EventDriver object. * @param supported an array of supported class names */ public EventDriver(String[] supported) { super(supported); queueTool = new QueueTool(); } /** * Constructs an EventDriver object suporting ComponentOperator. */ public EventDriver() { this(new String[] {"org.netbeans.jemmy.operators.ComponentOperator"}); } /** * Dispatches an event to the component. * @param comp Component to dispatch events to. * @param event an event to dispatch. */ public void dispatchEvent(Component comp, AWTEvent event) { // checkVisibility(comp); QueueTool.processEvent(event); } /** * Checks component visibility. * @param component a component. */ protected void checkVisibility(Component component) { if(!component.isVisible()) { throw(new ComponentIsNotVisibleException(component)); } } /** * Class used fot execution of an event through the dispatching thread. */ protected class Dispatcher extends QueueTool.QueueAction { AWTEvent event; Component component; /** * Constructs an EventDriver$Dispatcher object. * @param component a component to dispatch event to. * @param e an event to dispatch. */ public Dispatcher(Component component, AWTEvent e) { super(e.getClass().getName() + " event dispatching"); this.component = component; event = e; } public Object launch() { checkVisibility(component); component.dispatchEvent(event); return(null); } } } Jemmy2/src/org/netbeans/jemmy/drivers/input/RobotDriver.java0000644000175000017500000003553311245712304023214 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.input; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.lang.reflect.InvocationTargetException; import org.netbeans.jemmy.ClassReference; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.LightSupportiveDriver; /** * Superclass for all drivers using robot. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class RobotDriver extends LightSupportiveDriver { private boolean haveOldPos; private boolean smooth = false; private double oldX; private double oldY; private static final double CONSTANT1 = 0.75; private static final double CONSTANT2 = 12.0; /** * A reference to the robot instance. */ protected ClassReference robotReference = null; /** * A QueueTool instance. */ protected QueueTool qtool; protected Timeout autoDelay; /** * Constructs a RobotDriver object. * @param autoDelay Time for Robot.setAutoDelay(long) method. * @param supported an array of supported class names */ public RobotDriver(Timeout autoDelay, String[] supported) { super(supported); qtool = new QueueTool(); qtool.setOutput(TestOut.getNullOutput()); this.autoDelay = autoDelay; } public RobotDriver(Timeout autoDelay, String[] supported, boolean smooth) { this(autoDelay, supported); this.smooth = smooth; } /** * Constructs a RobotDriver object. * @param autoDelay Time for Robot.setAutoDelay(long) method. */ public RobotDriver(Timeout autoDelay) { this(autoDelay, new String[] {"org.netbeans.jemmy.operators.ComponentOperator"}); } public RobotDriver(Timeout autoDelay, boolean smooth) { this(autoDelay); this.smooth = smooth; } public void pressMouse(int mouseButton, int modifiers) { pressModifiers(modifiers); makeAnOperation("mousePress", new Object[] {new Integer(mouseButton)}, new Class[] {Integer.TYPE}); } public void releaseMouse(int mouseButton, int modifiers) { makeAnOperation("mouseRelease", new Object[] {new Integer(mouseButton)}, new Class[] {Integer.TYPE}); releaseModifiers(modifiers); } public void moveMouse(int x, int y) { if(!smooth) { makeAnOperation("mouseMove", new Object[] {new Integer(x), new Integer(y)}, new Class[] {Integer.TYPE, Integer.TYPE}); } else { double targetX = x; double targetY = y; if (haveOldPos) { double currX = oldX; double currY = oldY; double vx = 0.0; double vy = 0.0; while (Math.round(currX)!=Math.round(targetX) || Math.round(currY)!=Math.round(targetY)) { vx = vx*CONSTANT1+(targetX-currX)/CONSTANT2*(1.0-CONSTANT1); vy = vy*CONSTANT1+(targetY-currY)/CONSTANT2*(1.0-CONSTANT1); currX += vx; currY += vy; makeAnOperation("mouseMove", new Object[]{ new Integer((int)Math.round(currX)), new Integer((int) Math.round(currY))}, new Class[]{Integer.TYPE, Integer.TYPE}); } } else { makeAnOperation("mouseMove", new Object[]{ new Integer((int) Math.round(targetX)), new Integer((int) Math.round(targetY))}, new Class[]{Integer.TYPE, Integer.TYPE}); } haveOldPos = true; oldX = targetX; oldY = targetY; } } public void clickMouse(int x, int y, int clickCount, int mouseButton, int modifiers, Timeout mouseClick) { pressModifiers(modifiers); moveMouse(x, y); makeAnOperation("mousePress", new Object[] {new Integer(mouseButton)}, new Class[] {Integer.TYPE}); for(int i = 1; i < clickCount; i++) { makeAnOperation("mouseRelease", new Object[] {new Integer(mouseButton)}, new Class[] {Integer.TYPE}); makeAnOperation("mousePress", new Object[] {new Integer(mouseButton)}, new Class[] {Integer.TYPE}); } mouseClick.sleep(); makeAnOperation("mouseRelease", new Object[] {new Integer(mouseButton)}, new Class[] {Integer.TYPE}); releaseModifiers(modifiers); } public void dragMouse(int x, int y, int mouseButton, int modifiers) { moveMouse(x, y); } public void dragNDrop(int start_x, int start_y, int end_x, int end_y, int mouseButton, int modifiers, Timeout before, Timeout after) { moveMouse(start_x, start_y); pressMouse(mouseButton, modifiers); before.sleep(); moveMouse(end_x, end_y); after.sleep(); releaseMouse(mouseButton, modifiers); } /** * Presses a key. * @param keyCode Key code (KeyEventVK_* field. * @param modifiers a combination of InputEvent.*_MASK fields. */ public void pressKey(int keyCode, int modifiers) { pressModifiers(modifiers); makeAnOperation("keyPress", new Object[] {new Integer(keyCode)}, new Class[] {Integer.TYPE}); } /** * Releases a key. * @param keyCode Key code (KeyEventVK_* field. * @param modifiers a combination of InputEvent.*_MASK fields. */ public void releaseKey(int keyCode, int modifiers) { releaseModifiers(modifiers); makeAnOperation("keyRelease", new Object[] {new Integer(keyCode)}, new Class[] {Integer.TYPE}); } /** * Performs a single operation. * @param method a name of java.awt.Robot method. * @param params method parameters * @param paramClasses method parameters classes */ protected void makeAnOperation(final String method, final Object[] params, final Class[] paramClasses) { if(robotReference == null) { initRobot(); } try { robotReference.invokeMethod(method, params, paramClasses); synchronizeRobot(); } catch(InvocationTargetException e) { throw(new JemmyException("Exception during java.awt.Robot accessing", e)); } catch(IllegalStateException e) { throw(new JemmyException("Exception during java.awt.Robot accessing", e)); } catch(NoSuchMethodException e) { throw(new JemmyException("Exception during java.awt.Robot accessing", e)); } catch(IllegalAccessException e) { throw(new JemmyException("Exception during java.awt.Robot accessing", e)); } } /** * Calls java.awt.Robot.waitForIdle() method. */ protected void synchronizeRobot() { if(!qtool.isDispatchThread()) { if ((JemmyProperties.getCurrentDispatchingModel() & JemmyProperties.QUEUE_MODEL_MASK) != 0) { if(robotReference == null) { initRobot(); } try { robotReference.invokeMethod("waitForIdle", null, null); } catch(Exception e) { e.printStackTrace(); } } } } /** * Presses modifiers keys by robot. * @param modifiers a combination of InputEvent.*_MASK fields. */ protected void pressModifiers(int modifiers) { if ((modifiers & InputEvent.SHIFT_MASK) != 0) { pressKey(KeyEvent.VK_SHIFT, modifiers & ~InputEvent.SHIFT_MASK); } else if((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) { pressKey(KeyEvent.VK_ALT_GRAPH, modifiers & ~InputEvent.ALT_GRAPH_MASK); } else if((modifiers & InputEvent.ALT_MASK) != 0) { pressKey(KeyEvent.VK_ALT, modifiers & ~InputEvent.ALT_MASK); } else if((modifiers & InputEvent.META_MASK) != 0) { pressKey(KeyEvent.VK_META, modifiers & ~InputEvent.META_MASK); } else if((modifiers & InputEvent.CTRL_MASK) != 0) { pressKey(KeyEvent.VK_CONTROL, modifiers & ~InputEvent.CTRL_MASK); } } /* protected void pressModifiers(ComponentOperator oper, int modifiers) { if ((modifiers & InputEvent.SHIFT_MASK) != 0) { pressKey(oper, KeyEvent.VK_SHIFT, modifiers & ~InputEvent.SHIFT_MASK); } else if((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) { pressKey(oper, KeyEvent.VK_ALT_GRAPH, modifiers & ~InputEvent.ALT_GRAPH_MASK); } else if((modifiers & InputEvent.ALT_MASK) != 0) { pressKey(oper, KeyEvent.VK_ALT, modifiers & ~InputEvent.ALT_MASK); } else if((modifiers & InputEvent.META_MASK) != 0) { pressKey(oper, KeyEvent.VK_META, modifiers & ~InputEvent.META_MASK); } else if((modifiers & InputEvent.CTRL_MASK) != 0) { pressKey(oper, KeyEvent.VK_CONTROL, modifiers & ~InputEvent.CTRL_MASK); } } */ /** * Releases modifiers keys by robot. * @param modifiers a combination of InputEvent.*_MASK fields. */ protected void releaseModifiers(int modifiers) { if ((modifiers & InputEvent.SHIFT_MASK) != 0) { releaseKey(KeyEvent.VK_SHIFT, modifiers & ~InputEvent.SHIFT_MASK); } else if((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) { releaseKey(KeyEvent.VK_ALT_GRAPH, modifiers & ~InputEvent.ALT_GRAPH_MASK); } else if((modifiers & InputEvent.ALT_MASK) != 0) { releaseKey(KeyEvent.VK_ALT, modifiers & ~InputEvent.ALT_MASK); } else if((modifiers & InputEvent.META_MASK) != 0) { releaseKey(KeyEvent.VK_META, modifiers & ~InputEvent.META_MASK); } else if((modifiers & InputEvent.CTRL_MASK) != 0) { releaseKey(KeyEvent.VK_CONTROL, modifiers & ~InputEvent.CTRL_MASK); } } /* protected void releaseModifiers(ComponentOperator oper, int modifiers) { if ((modifiers & InputEvent.SHIFT_MASK) != 0) { releaseKey(oper, KeyEvent.VK_SHIFT, modifiers & ~InputEvent.SHIFT_MASK); } else if((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) { releaseKey(oper, KeyEvent.VK_ALT_GRAPH, modifiers & ~InputEvent.ALT_GRAPH_MASK); } else if((modifiers & InputEvent.ALT_MASK) != 0) { releaseKey(oper, KeyEvent.VK_ALT, modifiers & ~InputEvent.ALT_MASK); } else if((modifiers & InputEvent.META_MASK) != 0) { releaseKey(oper, KeyEvent.VK_META, modifiers & ~InputEvent.META_MASK); } else if((modifiers & InputEvent.CTRL_MASK) != 0) { releaseKey(oper, KeyEvent.VK_CONTROL, modifiers & ~InputEvent.CTRL_MASK); } } */ private void initRobot() { // need to init Robot in dispatch thread because it hangs on Linux // (see http://www.netbeans.org/issues/show_bug.cgi?id=37476) if(qtool.isDispatchThread()) { doInitRobot(); } else { qtool.invokeAndWait(new Runnable() { public void run() { doInitRobot(); } }); } } private void doInitRobot() { try { ClassReference robotClassReverence = new ClassReference("java.awt.Robot"); robotReference = new ClassReference(robotClassReverence.newInstance(null, null)); robotReference.invokeMethod("setAutoDelay", new Object[] {new Integer((int)((autoDelay != null) ? autoDelay.getValue() : 0))}, new Class[] {Integer.TYPE}); } catch(InvocationTargetException e) { throw(new JemmyException("Exception during java.awt.Robot accessing", e)); } catch(IllegalStateException e) { throw(new JemmyException("Exception during java.awt.Robot accessing", e)); } catch(NoSuchMethodException e) { throw(new JemmyException("Exception during java.awt.Robot accessing", e)); } catch(IllegalAccessException e) { throw(new JemmyException("Exception during java.awt.Robot accessing", e)); } catch(ClassNotFoundException e) { throw(new JemmyException("Exception during java.awt.Robot accessing", e)); } catch(InstantiationException e) { throw(new JemmyException("Exception during java.awt.Robot accessing", e)); } } } Jemmy2/src/org/netbeans/jemmy/drivers/input/KeyRobotDriver.java0000644000175000017500000000772211245712237023671 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.input; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.KeyDriver; import org.netbeans.jemmy.operators.ComponentOperator; /** * KeyDriver using robot operations. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class KeyRobotDriver extends RobotDriver implements KeyDriver { /** * Constructs a KeyRobotDriver object. * @param autoDelay Time for Robot.setAutoDelay(long) method. */ public KeyRobotDriver(Timeout autoDelay) { super(autoDelay); } /** * Constructs a KeyRobotDriver object. * @param autoDelay Time for Robot.setAutoDelay(long) method. * @param supported an array of supported class names */ public KeyRobotDriver(Timeout autoDelay, String[] supported) { super(autoDelay, supported); } public void pushKey(ComponentOperator oper, int keyCode, int modifiers, Timeout pushTime) { pressKey(oper, keyCode, modifiers); pushTime.sleep(); releaseKey(oper, keyCode, modifiers); } public void typeKey(ComponentOperator oper, int keyCode, char keyChar, int modifiers, Timeout pushTime) { pushKey(oper, keyCode, modifiers, pushTime); } /** * Presses a key. * @param oper Operator to press a key on. * @param keyCode Key code (KeyEventVK_* field. * @param modifiers a combination of InputEvent.*_MASK fields. */ public void pressKey(ComponentOperator oper, int keyCode, int modifiers) { pressKey(keyCode, modifiers); } /** * Releases a key. * @param oper Operator to release a key on. * @param keyCode Key code (KeyEventVK_* field. * @param modifiers a combination of InputEvent.*_MASK fields. */ public void releaseKey(ComponentOperator oper, int keyCode, int modifiers) { releaseKey(keyCode, modifiers); } } Jemmy2/src/org/netbeans/jemmy/drivers/TextDriver.java0000644000175000017500000000705311064436407021716 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to work with text components. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface TextDriver { /** * Moves caret. * @param oper Text component operator. * @param position Position to move caret to. */ public void changeCaretPosition(ComponentOperator oper, int position); /** * Selects text. * @param oper Text component operator. * @param startPosition a posistion of selction start * @param finalPosition a posistion of selction end */ public void selectText(ComponentOperator oper, int startPosition, int finalPosition); /** * Clears component text. * @param oper Text component operator. */ public void clearText(ComponentOperator oper); /** * Types new text. * @param oper Text component operator. * @param text New text to type. * @param caretPosition Type text at that position. */ public void typeText(ComponentOperator oper, String text, int caretPosition); /** * Replace component text. * @param oper Text component operator. * @param text New text to type. */ public void changeText(ComponentOperator oper, String text); /** * Type text and push enter. * @param oper Text component operator. * @param text New text to type. */ public void enterText(ComponentOperator oper, String text); } Jemmy2/src/org/netbeans/jemmy/drivers/buttons/0000755000175000017500000000000011572745223020447 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/drivers/buttons/package.html0000644000175000017500000000036011064436407022724 0ustar tonytony Button drivers

Button drivers

Different drivers to push a button.
@since 4/17/2002
Jemmy2/src/org/netbeans/jemmy/drivers/buttons/ButtonMouseDriver.java0000644000175000017500000000706011245712237024751 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.buttons; import org.netbeans.jemmy.drivers.ButtonDriver; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.MouseDriver; import org.netbeans.jemmy.operators.ComponentOperator; /** * Driver to push a button by mouse click. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class ButtonMouseDriver extends LightSupportiveDriver implements ButtonDriver { public ButtonMouseDriver() { super(new String[] {"org.netbeans.jemmy.operators.ComponentOperator"}); } public void press(ComponentOperator oper) { MouseDriver mdriver = DriverManager.getMouseDriver(oper); mdriver.moveMouse(oper, oper.getCenterXForClick(), oper.getCenterYForClick()); mdriver.pressMouse(oper, oper.getCenterXForClick(), oper.getCenterYForClick(), oper.getDefaultMouseButton(), 0); } public void release(ComponentOperator oper) { DriverManager. getMouseDriver(oper). releaseMouse(oper, oper.getCenterXForClick(), oper.getCenterYForClick(), oper.getDefaultMouseButton(), 0); } public void push(ComponentOperator oper) { DriverManager. getMouseDriver(oper). clickMouse(oper, oper.getCenterXForClick(), oper.getCenterYForClick(), 1, oper.getDefaultMouseButton(), 0, oper.getTimeouts(). create("ComponentOperator.MouseClickTimeout")); } } Jemmy2/src/org/netbeans/jemmy/drivers/ScrollDriver.java0000644000175000017500000000633111245712237022225 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.drivers.scrolling.ScrollAdjuster; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to work with scrollable components such as * javax.swing.JScrollBar, javax.swing.JScrollPane, javax.swing.JSlider, ... * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface ScrollDriver { /** * Changes value to a minimum. * @param oper Scroller operator. * @param orientation java.awt.Adjustable.HORIZONTAL or java.awt.Adjustable.VERTICAL */ public void scrollToMinimum(ComponentOperator oper, int orientation); /** * Changes value to a maximum. * @param oper Scroller operator. * @param orientation java.awt.Adjustable.HORIZONTAL or java.awt.Adjustable.VERTICAL */ public void scrollToMaximum(ComponentOperator oper, int orientation); /** * Changes value. * @param oper Scroller operator. * @param adj Object defines scroll position. */ public void scroll(ComponentOperator oper, ScrollAdjuster adj); } Jemmy2/src/org/netbeans/jemmy/drivers/Driver.java0000644000175000017500000000477511064436407021061 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; /** * Implements "heavy" model of driver because requires to * load classes for all supported operator types. * @see LightDriver * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface Driver { /** * Returns an array of operator classes which are supported by this driver. * @return an array of supported operators' classes. */ public Class[] getSupported(); } Jemmy2/src/org/netbeans/jemmy/drivers/DriverManager.java0000644000175000017500000005775211245712237022356 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.operators.ComponentOperator; /** * Manages driver set. */ public class DriverManager { /** * Symbolic constant - prefix for drivers names. */ public static final String DRIVER_ID = "drivers."; /** * Symbolic constant for tree drivers. */ public static final String TREE_DRIVER_ID = DRIVER_ID + "tree"; /** * Symbolic constant for text drivers. */ public static final String TEXT_DRIVER_ID = DRIVER_ID + "text"; /** * Symbolic constant for key drivers. */ public static final String KEY_DRIVER_ID = DRIVER_ID + "key"; /** * Symbolic constant for mouse drivers. */ public static final String MOUSE_DRIVER_ID = DRIVER_ID + "mouse"; /** * Symbolic constant for scroll drivers. */ public static final String SCROLL_DRIVER_ID = DRIVER_ID + "scroll"; /** * Symbolic constant for button drivers. */ public static final String BUTTON_DRIVER_ID = DRIVER_ID + "button"; /** * Symbolic constant for list drivers. */ public static final String LIST_DRIVER_ID = DRIVER_ID + "list"; /** * Symbolic constant for multiselection list drivers. */ public static final String MULTISELLIST_DRIVER_ID = DRIVER_ID + "multisellist"; /** * Symbolic constant for reorderable list drivers. */ public static final String ORDEREDLIST_DRIVER_ID = DRIVER_ID + "orderedlist"; /** * Symbolic constant for table drivers. */ public static final String TABLE_DRIVER_ID = DRIVER_ID + "table"; /** * Symbolic constant for window drivers. */ public static final String WINDOW_DRIVER_ID = DRIVER_ID + "window"; /** * Symbolic constant for window drivers. */ public static final String FRAME_DRIVER_ID = DRIVER_ID + "frame"; /** * Symbolic constant for window drivers. */ public static final String INTERNAL_FRAME_DRIVER_ID = DRIVER_ID + "internal_frame"; /** * Symbolic constant for frame drivers. */ public static final String FOCUS_DRIVER_ID = DRIVER_ID + "focus"; /** * Symbolic constant for menu drivers. */ public static final String MENU_DRIVER_ID = DRIVER_ID + "menu"; //cannot be instantiated! private DriverManager() { } /** * Searches a driver. * @param id Driver type id. * @param operatorClass Class to get an driver for. * @param props Instance to get driver from. * @return a driver. * @see #setDriver */ public static Object getDriver(String id, Class operatorClass, JemmyProperties props) { Object result = getADriver(id, operatorClass, props); if(result == null) { return(getDriver(id, operatorClass)); } else { return(result); } } /** * Searches a driver. Uses operator.getProperties() to * receive JemmyProperties instance. * @param id Driver type id. * @param operator Operator to get an driver for. * @return a driver. * @see #setDriver */ public static Object getDriver(String id, ComponentOperator operator) { return(getDriver(id, operator.getClass(), operator.getProperties())); } /** * Searches a driver. * Uses current JemmyProperties. * @param id Driver type id. * @param operatorClass Class to get an driver for. * @return a driver. * @see #setDriver */ public static Object getDriver(String id, Class operatorClass) { Object result = getADriver(id, operatorClass, JemmyProperties.getProperties()); if(result == null) { throw(new JemmyException("No \"" + id + "\" driver registered for " + operatorClass.getName() + " class!")); } else { return(result); } } /** * Sets driver for an operator class. * @param id Driver type id. * @param driver A driver to be installed. * @param operatorClass Class to set driver for. * @see #getDriver */ public static void setDriver(String id, Object driver, Class operatorClass) { JemmyProperties. setCurrentProperty(makeID(id, operatorClass), driver); if(Boolean.getBoolean(DRIVER_ID + "trace_output")) { JemmyProperties.getCurrentOutput().printLine("Installing " + driver.getClass().getName() + " drifer for " + operatorClass.getName() + " operators."); } } /** * Sets driver for an operator class name. * @param id Driver type id. * @param driver A driver to be installed. * @param operatorClassName A name of operator class. * @see #getDriver */ public static void setDriver(String id, Object driver, String operatorClassName) { JemmyProperties. setCurrentProperty(makeID(id, operatorClassName), driver); if(Boolean.getBoolean(DRIVER_ID + "trace_output")) { JemmyProperties.getCurrentOutput().printLine("Installing " + driver.getClass().getName() + " drifer for " + operatorClassName + " operators."); } } /** * Sets driver for all classes supported by driver. * @param id Driver type id. * @param driver A driver to be installed. * @see #getDriver */ public static void setDriver(String id, Driver driver) { Class[] supported = driver.getSupported(); for(int i = 0; i < supported.length; i++) { setDriver(id, driver, supported[i]); } } /** * Sets driver for all classes supported by driver. * @param id Driver type id. * @param driver A driver to be installed. * @see #getDriver */ public static void setDriver(String id, LightDriver driver) { String[] supported = driver.getSupported(); for(int i = 0; i < supported.length; i++) { setDriver(id, driver, supported[i]); } } /** * Removes driver for operator class. * @param id Driver type to remove. * @param operatorClass Class to remove driver for. */ public static void removeDriver(String id, Class operatorClass) { JemmyProperties. removeCurrentProperty(makeID(id, operatorClass)); if(Boolean.getBoolean(DRIVER_ID + "trace_output")) { JemmyProperties.getCurrentOutput().printLine("Uninstalling a drifer for " + operatorClass.getName() + " operators."); } } /** * Removes driver for operator class. * @param id Driver type to remove. * @param operatorClassName A name of operator class. */ public static void removeDriver(String id, String operatorClassName) { JemmyProperties. removeCurrentProperty(makeID(id, operatorClassName)); if(Boolean.getBoolean(DRIVER_ID + "trace_output")) { JemmyProperties.getCurrentOutput().printLine("Uninstalling a drifer for " + operatorClassName + " operators."); } } /** * Removes driver for operator classes. * @param id Driver type to remove. * @param operatorClasses Classes to remove driver for. */ public static void removeDriver(String id, Class[] operatorClasses) { for(int i = 0; i < operatorClasses.length; i++) { removeDriver(id, operatorClasses[i]); } } /** * Removes driver for operator classes. * @param id Driver type to remove. * @param operatorClassNames Names of operator classes. */ public static void removeDriver(String id, String[] operatorClassNames) { for(int i = 0; i < operatorClassNames.length; i++) { removeDriver(id, operatorClassNames[i]); } } /** * Removes driver for all supported classes. * @param id Driver type to remove. */ public static void removeDrivers(String id) { String[] keys = JemmyProperties.getCurrentKeys(); for(int i = 0; i < keys.length; i++) { if(keys[i].startsWith(id)) { JemmyProperties. removeCurrentProperty(keys[i]); } } } /** * Returns TREE_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setTreeDriver */ public static TreeDriver getTreeDriver(Class operatorClass) { return((TreeDriver)getDriver(TREE_DRIVER_ID, operatorClass)); } /** * Returns TREE_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setTreeDriver */ public static TreeDriver getTreeDriver(ComponentOperator operator) { return((TreeDriver)getDriver(TREE_DRIVER_ID, operator.getClass())); } /** * Defines TREE_DRIVER_ID driver. * @param driver a driver * @see #getTreeDriver */ public static void setTreeDriver(TreeDriver driver) { setDriver(TREE_DRIVER_ID, driver); } /** * Returns TEXT_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setTextDriver */ public static TextDriver getTextDriver(Class operatorClass) { return((TextDriver)getDriver(TEXT_DRIVER_ID, operatorClass)); } /** * Returns TEXT_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setTextDriver */ public static TextDriver getTextDriver(ComponentOperator operator) { return((TextDriver)getDriver(TEXT_DRIVER_ID, operator.getClass())); } /** * Defines TEXT_DRIVER_ID driver. * @param driver a driver * @see #getTextDriver */ public static void setTextDriver(TextDriver driver) { setDriver(TEXT_DRIVER_ID, driver); } /** * Returns KEY_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setKeyDriver */ public static KeyDriver getKeyDriver(Class operatorClass) { return((KeyDriver)getDriver(KEY_DRIVER_ID, operatorClass)); } /** * Returns KEY_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setKeyDriver */ public static KeyDriver getKeyDriver(ComponentOperator operator) { return((KeyDriver)getDriver(KEY_DRIVER_ID, operator.getClass())); } /** * Defines KEY_DRIVER_ID driver. * @param driver a driver * @see #getKeyDriver */ public static void setKeyDriver(KeyDriver driver) { setDriver(KEY_DRIVER_ID, driver); } /** * Returns MOUSE_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setMouseDriver */ public static MouseDriver getMouseDriver(Class operatorClass) { return((MouseDriver)getDriver(MOUSE_DRIVER_ID, operatorClass)); } /** * Returns MOUSE_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setMouseDriver */ public static MouseDriver getMouseDriver(ComponentOperator operator) { return((MouseDriver)getDriver(MOUSE_DRIVER_ID, operator.getClass())); } /** * Defines MOUSE_DRIVER_ID driver. * @param driver a driver * @see #getMouseDriver */ public static void setMouseDriver(MouseDriver driver) { setDriver(MOUSE_DRIVER_ID, driver); } /** * Returns SCROLL_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setScrollDriver */ public static ScrollDriver getScrollDriver(Class operatorClass) { return((ScrollDriver)getDriver(SCROLL_DRIVER_ID, operatorClass)); } /** * Returns SCROLL_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setScrollDriver */ public static ScrollDriver getScrollDriver(ComponentOperator operator) { return((ScrollDriver)getDriver(SCROLL_DRIVER_ID, operator.getClass())); } /** * Defines SCROLL_DRIVER_ID driver. * @param driver a driver * @see #getScrollDriver */ public static void setScrollDriver(ScrollDriver driver) { setDriver(SCROLL_DRIVER_ID, driver); } /** * Returns BUTTON_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setButtonDriver */ public static ButtonDriver getButtonDriver(Class operatorClass) { return((ButtonDriver)getDriver(BUTTON_DRIVER_ID, operatorClass)); } /** * Returns BUTTON_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setButtonDriver */ public static ButtonDriver getButtonDriver(ComponentOperator operator) { return((ButtonDriver)getDriver(BUTTON_DRIVER_ID, operator.getClass())); } /** * Defines BUTTON_DRIVER_ID driver. * @param driver a driver * @see #getButtonDriver */ public static void setButtonDriver(ButtonDriver driver) { setDriver(BUTTON_DRIVER_ID, driver); } /** * Returns LIST_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setListDriver */ public static ListDriver getListDriver(Class operatorClass) { return((ListDriver)getDriver(LIST_DRIVER_ID, operatorClass)); } /** * Returns LIST_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setListDriver */ public static ListDriver getListDriver(ComponentOperator operator) { return((ListDriver)getDriver(LIST_DRIVER_ID, operator.getClass())); } /** * Defines LIST_DRIVER_ID driver. * @param driver a driver * @see #getListDriver */ public static void setListDriver(ListDriver driver) { setDriver(LIST_DRIVER_ID, driver); } /** * Returns MULTISELLIST_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setMultiSelListDriver */ public static MultiSelListDriver getMultiSelListDriver(Class operatorClass) { return((MultiSelListDriver)getDriver(MULTISELLIST_DRIVER_ID, operatorClass)); } /** * Returns MULTISELLIST_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setMultiSelListDriver */ public static MultiSelListDriver getMultiSelListDriver(ComponentOperator operator) { return((MultiSelListDriver)getDriver(MULTISELLIST_DRIVER_ID, operator.getClass())); } /** * Defines MULTISELLIST_DRIVER_ID driver. * @param driver a driver * @see #getMultiSelListDriver */ public static void setMultiSelListDriver(MultiSelListDriver driver) { setDriver(MULTISELLIST_DRIVER_ID, driver); } /** * Returns ORDEREDLIST_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setOrderedListDriver */ public static OrderedListDriver getOrderedListDriver(Class operatorClass) { return((OrderedListDriver)getDriver(ORDEREDLIST_DRIVER_ID, operatorClass)); } /** * Returns ORDEREDLIST_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setOrderedListDriver */ public static OrderedListDriver getOrderedListDriver(ComponentOperator operator) { return((OrderedListDriver)getDriver(ORDEREDLIST_DRIVER_ID, operator.getClass())); } /** * Defines ORDEREDLIST_DRIVER_ID driver. * @param driver a driver * @see #getOrderedListDriver */ public static void setOrderedListDriver(OrderedListDriver driver) { setDriver(ORDEREDLIST_DRIVER_ID, driver); } /** * Returns TABLE_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setTableDriver */ public static TableDriver getTableDriver(Class operatorClass) { return((TableDriver)getDriver(TABLE_DRIVER_ID, operatorClass)); } /** * Returns TABLE_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setTableDriver */ public static TableDriver getTableDriver(ComponentOperator operator) { return((TableDriver)getDriver(TABLE_DRIVER_ID, operator.getClass())); } /** * Defines TABLE_DRIVER_ID driver. * @param driver a driver * @see #getTableDriver */ public static void setTableDriver(TableDriver driver) { setDriver(TABLE_DRIVER_ID, driver); } /** * Returns WINDOW_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setWindowDriver */ public static WindowDriver getWindowDriver(Class operatorClass) { return((WindowDriver)getDriver(WINDOW_DRIVER_ID, operatorClass)); } /** * Returns WINDOW_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setWindowDriver */ public static WindowDriver getWindowDriver(ComponentOperator operator) { return((WindowDriver)getDriver(WINDOW_DRIVER_ID, operator.getClass())); } /** * Defines WINDOW_DRIVER_ID driver. * @param driver a driver * @see #getWindowDriver */ public static void setWindowDriver(WindowDriver driver) { setDriver(WINDOW_DRIVER_ID, driver); } /** * Returns FRAME_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setFrameDriver */ public static FrameDriver getFrameDriver(Class operatorClass) { return((FrameDriver)getDriver(FRAME_DRIVER_ID, operatorClass)); } /** * Returns FRAME_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setFrameDriver */ public static FrameDriver getFrameDriver(ComponentOperator operator) { return((FrameDriver)getDriver(FRAME_DRIVER_ID, operator.getClass())); } /** * Defines FRAME_DRIVER_ID driver. * @param driver a driver * @see #getFrameDriver */ public static void setFrameDriver(FrameDriver driver) { setDriver(FRAME_DRIVER_ID, driver); } /** * Returns INTERNAL_FRAME_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setInternalFrameDriver */ public static InternalFrameDriver getInternalFrameDriver(Class operatorClass) { return((InternalFrameDriver)getDriver(INTERNAL_FRAME_DRIVER_ID, operatorClass)); } /** * Returns INTERNAL_FRAME_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setInternalFrameDriver */ public static InternalFrameDriver getInternalFrameDriver(ComponentOperator operator) { return((InternalFrameDriver)getDriver(INTERNAL_FRAME_DRIVER_ID, operator.getClass())); } /** * Defines INTERNAL_FRAME_DRIVER_ID driver. * @param driver a driver * @see #getInternalFrameDriver */ public static void setInternalFrameDriver(InternalFrameDriver driver) { setDriver(INTERNAL_FRAME_DRIVER_ID, driver); } /** * Returns FOCUS_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setFocusDriver */ public static FocusDriver getFocusDriver(Class operatorClass) { return((FocusDriver)getDriver(FOCUS_DRIVER_ID, operatorClass)); } /** * Returns FOCUS_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setFocusDriver */ public static FocusDriver getFocusDriver(ComponentOperator operator) { return((FocusDriver)getDriver(FOCUS_DRIVER_ID, operator.getClass())); } /** * Defines FOCUS_DRIVER_ID driver. * @param driver a driver * @see #getFocusDriver */ public static void setFocusDriver(FocusDriver driver) { setDriver(FOCUS_DRIVER_ID, driver); } /** * Returns MENU_DRIVER_ID driver. * @param operatorClass Class to find driver for. * @return a driver * @see #setMenuDriver */ public static MenuDriver getMenuDriver(Class operatorClass) { return((MenuDriver)getDriver(MENU_DRIVER_ID, operatorClass)); } /** * Returns MENU_DRIVER_ID driver. * @param operator Operator to find driver for. * @return a driver * @see #setMenuDriver */ public static MenuDriver getMenuDriver(ComponentOperator operator) { return((MenuDriver)getDriver(MENU_DRIVER_ID, operator.getClass())); } /** * Defines MENU_DRIVER_ID driver. * @param driver a driver * @see #getMenuDriver */ public static void setMenuDriver(MenuDriver driver) { setDriver(MENU_DRIVER_ID, driver); } static void setDriver(String id, Object driver) { if(driver instanceof Driver) { setDriver(id, (Driver)driver); } else if(driver instanceof LightDriver) { setDriver(id, (LightDriver)driver); } else { throw(new JemmyException("Driver is neither Driver nor LightDriver " + driver.toString())); } } //creates driver id private static String makeID(String id, Class operatorClass) { return(makeID(id, operatorClass.getName())); } private static String makeID(String id, String operatorClassName) { return(id + "." + operatorClassName); } //returns a driver private static Object getADriver(String id, Class operatorClass, JemmyProperties props) { Class superClass = operatorClass; Object drvr; do { drvr = props. getProperty(makeID(id, superClass)); if(drvr != null) { return(drvr); } } while(ComponentOperator.class. isAssignableFrom(superClass = superClass.getSuperclass())); return(null); } static { new InputDriverInstaller().install(); new DefaultDriverInstaller().install(); } } Jemmy2/src/org/netbeans/jemmy/drivers/OrderedListDriver.java0000644000175000017500000000502311064436407023205 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to work with lists allowing items reordering. */ public interface OrderedListDriver extends MultiSelListDriver { /** * Changes item index. * @param oper List operator. * @param itemIndex Current item index. * @param newIndex Ne witem index. */ public void moveItem(ComponentOperator oper, int itemIndex, int newIndex); } Jemmy2/src/org/netbeans/jemmy/drivers/FocusDriver.java0000644000175000017500000000457711064436407022061 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to manage focus. */ public interface FocusDriver { /** * Makes a compoennt having focus. * @param operator Component operator. */ public void giveFocus(ComponentOperator operator); } Jemmy2/src/org/netbeans/jemmy/drivers/MouseDriver.java0000644000175000017500000001251411245712237022057 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to simulate mouse operations. */ public interface MouseDriver { /** * Presses mouse. * @param oper Component operator. * @param x Relative x coordinate. * @param y Relative y coordinate. * @param mouseButton mouse button (InputEvent.BUTTON*_MASK field) * @param modifiers a combination of InputEvent.*_MASK fields. */ public void pressMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers); /** * Releases mouse. * @param oper Component operator. * @param x Relative x coordinate. * @param y Relative y coordinate. * @param mouseButton mouse button (InputEvent.BUTTON*_MASK field) * @param modifiers a combination of InputEvent.*_MASK fields. */ public void releaseMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers); /** * Clicks mouse. * @param oper Component operator. * @param x Relative x coordinate. * @param y Relative y coordinate. * @param clickCount How many times to click. * @param mouseButton mouse button (InputEvent.BUTTON*_MASK field) * @param modifiers a combination of InputEvent.*_MASK fields. * @param mouseClick Time between pressing and releasing mouse. */ public void clickMouse(ComponentOperator oper, int x, int y, int clickCount, int mouseButton, int modifiers, Timeout mouseClick); /** * Moves mouse. * @param oper Component operator. * @param x Relative x coordinate. * @param y Relative y coordinate. */ public void moveMouse(ComponentOperator oper, int x, int y); /** * Drags mouse. * @param oper Component operator. * @param x Relative x coordinate. * @param y Relative y coordinate. * @param mouseButton mouse button (InputEvent.BUTTON*_MASK field) * @param modifiers a combination of InputEvent.*_MASK fields. */ public void dragMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers); /** * Performs drag'n'drop. * @param oper Component operator. * @param start_x Relative x coordinate of start point. * @param start_y Relative y coordinate of start point. * @param end_x Relative x coordinate of end point. * @param end_y Relative y coordinate of end point. * @param mouseButton mouse button (InputEvent.BUTTON*_MASK field) * @param modifiers a combination of InputEvent.*_MASK fields. * @param before Time to sleep after taking (before dragging) * @param after Time to sleep before dropping (after dragging) */ public void dragNDrop(ComponentOperator oper, int start_x, int start_y, int end_x, int end_y, int mouseButton, int modifiers, Timeout before, Timeout after); /** * Moves mouse inside a component. * @param oper Component operator. */ public void enterMouse(ComponentOperator oper); /** * Moves mouse outside a component. * @param oper Component operator. */ public void exitMouse(ComponentOperator oper); } Jemmy2/src/org/netbeans/jemmy/drivers/DriverInstaller.java0000644000175000017500000000434511064436407022730 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; /** * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface DriverInstaller { public void install(); } Jemmy2/src/org/netbeans/jemmy/drivers/TableDriver.java0000644000175000017500000000531711064436407022022 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to work with tables. */ public interface TableDriver { /** * Selects a cell. * @param oper Table operator. * @param row Cell row index. * @param column Cell column index. */ public void selectCell(ComponentOperator oper, int row, int column); /** * Edits a cell. * @param oper Table operator. * @param row Cell row index. * @param column Cell column index. * @param value New value. */ public void editCell(ComponentOperator oper, int row, int column, Object value); } Jemmy2/src/org/netbeans/jemmy/drivers/MenuDriver.java0000644000175000017500000000510211064436407021667 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.operators.ComponentOperator; /** * Defines how to work with menus. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface MenuDriver { /** * Pushes menu. * @param oper Menu operator. * @param chooser Object defining menupath. * @return a result of menu pushing. It could be last pushed menuitem or * anything else. */ public Object pushMenu(ComponentOperator oper, PathChooser chooser); } Jemmy2/src/org/netbeans/jemmy/drivers/SupportiveDriver.java0000644000175000017500000000606411064436407023153 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.operators.ComponentOperator; /** * Allows to declare supported operator classes. */ abstract public class SupportiveDriver implements Driver { private Class[] supported; /** * Creates an instance. * @param supported Array of operator classes which are supported by this driver. */ public SupportiveDriver(Class[] supported) { this.supported = supported; } /** * Throws UnsupportedOperatorException exception if * parameter's class is not in list of supported classes. * @param oper Operator whose class should be checked. * @throws UnsupportedOperatorException */ public void checkSupported(ComponentOperator oper) { UnsupportedOperatorException.checkSupported(getClass(), supported, oper.getClass()); } /** * Returns array of operator classes which are supported by this driver. */ public Class[] getSupported() { return(supported); } } Jemmy2/src/org/netbeans/jemmy/drivers/LightSupportiveDriver.java0000644000175000017500000000610611064436407024140 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers; import org.netbeans.jemmy.operators.ComponentOperator; /** * Allows to declare supported operator classes. */ abstract public class LightSupportiveDriver implements LightDriver { private String[] supported; /** * Creates an instance. * @param supported Array of operator classes which are supported by this driver. */ public LightSupportiveDriver(String[] supported) { this.supported = supported; } /** * Throws UnsupportedOperatorException exception if * parameter's class is not in list of supported classes. * @param oper Operator whose class should be checked. * @throws UnsupportedOperatorException */ public void checkSupported(ComponentOperator oper) { UnsupportedOperatorException.checkSupported(getClass(), supported, oper.getClass()); } /** * Returns array of operator classes which are supported by this driver. */ public String[] getSupported() { return(supported); } } Jemmy2/src/org/netbeans/jemmy/drivers/text/0000755000175000017500000000000011572745223017735 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/drivers/text/HomeKey.java0000644000175000017500000000450211064436407022137 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.text; class HomeKey extends OffsetKey { public HomeKey(int keyCode, int mods) { super(keyCode, mods); } public int getDirection() { return(-1); } public int getExpectedPosition() { return(0); } } Jemmy2/src/org/netbeans/jemmy/drivers/text/AWTTextAPIDriver.java0000644000175000017500000000603011245712237023601 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.text; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.TextComponentOperator; /** * TextDriver for AWT component types. * Uses API calls. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class AWTTextAPIDriver extends TextAPIDriver { /** * Constructs a AWTTextAPIDriver. */ public AWTTextAPIDriver() { super(new String[] {"org.netbeans.jemmy.operators.TextComponentOperator"}); } public String getText(ComponentOperator oper) { return(((TextComponentOperator)oper).getText()); } public int getCaretPosition(ComponentOperator oper) { return(((TextComponentOperator)oper).getCaretPosition()); } public int getSelectionStart(ComponentOperator oper) { return(((TextComponentOperator)oper).getSelectionStart()); } public int getSelectionEnd(ComponentOperator oper) { return(((TextComponentOperator)oper).getSelectionEnd()); } } Jemmy2/src/org/netbeans/jemmy/drivers/text/AWTTextKeyboardDriver.java0000644000175000017500000000772011245712237024737 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.text; import java.awt.event.KeyEvent; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.TextAreaOperator; import org.netbeans.jemmy.operators.TextComponentOperator; /** * TextDriver for AWT text component types. * Uses keyboard operations. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class AWTTextKeyboardDriver extends TextKeyboardDriver { /** * Constructs a AWTTextKeyboardDriver. */ public AWTTextKeyboardDriver() { super(new String[] {"org.netbeans.jemmy.operators.TextComponentOperator"}); } public String getText(ComponentOperator oper) { return(((TextComponentOperator)oper).getText()); } public int getCaretPosition(ComponentOperator oper) { return(((TextComponentOperator)oper).getCaretPosition()); } public int getSelectionStart(ComponentOperator oper) { return(((TextComponentOperator)oper).getSelectionStart()); } public int getSelectionEnd(ComponentOperator oper) { return(((TextComponentOperator)oper).getSelectionEnd()); } public NavigationKey[] getKeys(ComponentOperator oper) { boolean multiString = oper instanceof TextAreaOperator; NavigationKey[] result = new NavigationKey[multiString ? 4 : 2]; result[0] = new UpKey (KeyEvent.VK_LEFT , 0); result[1] = new DownKey(KeyEvent.VK_RIGHT, 0); (( UpKey)result[0]).setDownKey((DownKey)result[1]); ((DownKey)result[1]).setUpKey ((UpKey )result[0]); if(multiString) { result[2] = new UpKey (KeyEvent.VK_UP , 0); result[3] = new DownKey(KeyEvent.VK_DOWN, 0); (( UpKey)result[2]).setDownKey((DownKey)result[3]); ((DownKey)result[3]).setUpKey ((UpKey )result[2]); } return(result); } public Timeout getBetweenTimeout(ComponentOperator oper) { return(oper.getTimeouts().create("TextComponentOperator.BetweenKeysTimeout")); } } Jemmy2/src/org/netbeans/jemmy/drivers/text/NavigationKey.java0000644000175000017500000000466011064436407023353 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.text; abstract class NavigationKey { private int keyCode; private int mods; public NavigationKey(int keyCode, int mods) { this.keyCode = keyCode; this.mods = mods; } public int getKeyCode() { return(keyCode); } public int getModifiers() { return(mods); } public abstract int getDirection(); } Jemmy2/src/org/netbeans/jemmy/drivers/text/package.html0000644000175000017500000000037211064436407022215 0ustar tonytony Text drivers

Text drivers

Different drivers to perform a text operations.
@since 17 Apr 2002
Jemmy2/src/org/netbeans/jemmy/drivers/text/TextKeyboardDriver.java0000644000175000017500000002045211245712237024360 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.text; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import org.netbeans.jemmy.CharBindingMap; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.KeyDriver; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.TextDriver; import org.netbeans.jemmy.operators.ComponentOperator; /** * Superclass for all TextDrivers using keyboard. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public abstract class TextKeyboardDriver extends LightSupportiveDriver implements TextDriver { /** * Constructs a TextKeyboardDriver. * @param supported an array of supported class names */ public TextKeyboardDriver(String[] supported) { super(supported); } public void changeCaretPosition(ComponentOperator oper, int position) { DriverManager.getFocusDriver(oper).giveFocus(oper); checkSupported(oper); changeCaretPosition(oper, position, 0); } public void selectText(ComponentOperator oper, int startPosition, int finalPosition) { changeCaretPosition(oper, startPosition); DriverManager.getKeyDriver(oper).pressKey(oper, KeyEvent.VK_SHIFT, 0); changeCaretPosition(oper, finalPosition, InputEvent.SHIFT_MASK); DriverManager.getKeyDriver(oper).releaseKey(oper, KeyEvent.VK_SHIFT, 0); } public void clearText(ComponentOperator oper) { DriverManager.getFocusDriver(oper).giveFocus(oper); checkSupported(oper); KeyDriver kdriver = DriverManager.getKeyDriver(oper); Timeout pushTime = oper.getTimeouts().create("ComponentOperator.PushKeyTimeout"); Timeout betweenTime = getBetweenTimeout(oper); while(getCaretPosition(oper) > 0) { kdriver.typeKey(oper, KeyEvent.VK_BACK_SPACE, (char)KeyEvent.VK_BACK_SPACE, 0, pushTime); betweenTime.sleep(); } while(getText(oper).length() > 0) { kdriver.pushKey(oper, KeyEvent.VK_DELETE, 0, pushTime); betweenTime.sleep(); } } public void typeText(ComponentOperator oper, String text, int caretPosition) { changeCaretPosition(oper, caretPosition); KeyDriver kDriver = DriverManager.getKeyDriver(oper); CharBindingMap map = oper.getCharBindingMap(); Timeout pushTime = oper.getTimeouts().create("ComponentOperator.PushKeyTimeout"); Timeout betweenTime = getBetweenTimeout(oper); char[] crs = text.toCharArray(); for(int i = 0; i < crs.length; i++) { kDriver.typeKey(oper, map.getCharKey(crs[i]), crs[i], map.getCharModifiers(crs[i]), pushTime); betweenTime.sleep(); } } public void changeText(ComponentOperator oper, String text) { clearText(oper); typeText(oper, text, 0); } public void enterText(ComponentOperator oper, String text) { changeText(oper, text); DriverManager.getKeyDriver(oper).pushKey(oper, KeyEvent.VK_ENTER, 0, new Timeout("", 0)); } /** * Returns operator's text. * @param oper an operator. * @return string representing component text. */ public abstract String getText(ComponentOperator oper); /** * Returns current caret position. * @param oper an operator. * @return int represnting current operator's caret position. */ public abstract int getCaretPosition(ComponentOperator oper); /** * Returns a caret position of selection start. * @param oper an operator. * @return int represnting index of operator's selection start. */ public abstract int getSelectionStart(ComponentOperator oper); /** * Returns a caret position of selection end. * @param oper an operator. * @return int represnting index of operator's selection end. */ public abstract int getSelectionEnd(ComponentOperator oper); /** * Returns an array of navigation keys. * @param oper an operator. * @return an array on NavigationKey instances. */ public abstract NavigationKey[] getKeys(ComponentOperator oper); /** * Returns a timeout to sleep between text typing and caret operations. * @param oper an operator. * @return a Timeout instance. */ public abstract Timeout getBetweenTimeout(ComponentOperator oper); /** * Changes current caret position to specifyed. * @param oper an operator. * @param position new caret position * @param preModifiers a modifiers (combination of InputEvent.*_MASK fields) * pushed before caret moving (like shift during text selection). */ protected void changeCaretPosition(ComponentOperator oper, final int position, final int preModifiers){ NavigationKey[] keys = getKeys(oper); for(int i = keys.length - 1; i >=0; i--) { if(keys[i] instanceof OffsetKey) { moveCaret(oper, (OffsetKey)keys[i], position, preModifiers); } else { moveCaret(oper, (GoAndBackKey)keys[i], position, preModifiers); } } } private int difference(int one, int two) { if(one >= two) { return(one - two); } else { return(two - one); } } private void push(ComponentOperator oper, NavigationKey key, int preModifiers) { DriverManager.getKeyDriver(oper). pushKey(oper, key.getKeyCode(), key.getModifiers() | preModifiers, oper.getTimeouts().create("ComponentOperator.PushKeyTimeout")); getBetweenTimeout(oper).sleep(); } private final void moveCaret(ComponentOperator oper, GoAndBackKey key, int position, int preModifiers) { int newDiff = difference(position, getCaretPosition(oper)); int oldDiff = newDiff; QueueTool qTool = new QueueTool(); qTool.setOutput(oper.getOutput().createErrorOutput()); while(key.getDirection() * (position - getCaretPosition(oper)) > 0) { oldDiff = newDiff; push(oper, key, preModifiers); qTool.waitEmpty(); newDiff = difference(position, getCaretPosition(oper)); if(newDiff == oldDiff) { return; } }; if(newDiff > oldDiff) { push(oper, key.getBackKey(), preModifiers); } } private final void moveCaret(ComponentOperator oper, OffsetKey key, int position, int preModifiers) { if(gotToGo(oper, position, key.getExpectedPosition())) { push(oper, key, preModifiers); } } private boolean gotToGo(ComponentOperator oper, int point, int offset) { return(difference(point, offset) < difference(point, getCaretPosition(oper))); } } Jemmy2/src/org/netbeans/jemmy/drivers/text/DownKey.java0000644000175000017500000000464111245712347022163 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.text; class DownKey extends GoAndBackKey { private UpKey backKey; public DownKey(int keyCode, int mods) { super(keyCode, mods); } public void setUpKey(UpKey key) { backKey = key; } public int getDirection() { return(1); } public GoAndBackKey getBackKey() { return(backKey); } } Jemmy2/src/org/netbeans/jemmy/drivers/text/SwingTextAPIDriver.java0000644000175000017500000000605211245712237024241 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.text; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JTextComponentOperator; /** * TextDriver for swing component types. * Uses API calls. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class SwingTextAPIDriver extends TextAPIDriver { /** * Constructs a SwingTextAPIDriver. */ public SwingTextAPIDriver() { super(new String[] {"org.netbeans.jemmy.operators.JTextComponentOperator"}); } public String getText(ComponentOperator oper) { return(((JTextComponentOperator)oper).getDisplayedText()); } public int getCaretPosition(ComponentOperator oper) { return(((JTextComponentOperator)oper).getCaretPosition()); } public int getSelectionStart(ComponentOperator oper) { return(((JTextComponentOperator)oper).getSelectionStart()); } public int getSelectionEnd(ComponentOperator oper) { return(((JTextComponentOperator)oper).getSelectionEnd()); } } Jemmy2/src/org/netbeans/jemmy/drivers/text/EndKey.java0000644000175000017500000000504111064436407021754 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.text; import org.netbeans.jemmy.operators.ComponentOperator; class EndKey extends OffsetKey { TextKeyboardDriver cont; ComponentOperator oper; public EndKey(int keyCode, int mods, TextKeyboardDriver cont, ComponentOperator oper) { super(keyCode, mods); this.cont = cont; this.oper = oper; } public int getDirection() { return(1); } public int getExpectedPosition() { return(cont.getText(oper).length()); } } Jemmy2/src/org/netbeans/jemmy/drivers/text/TextAPIDriver.java0000644000175000017500000001352711245712237023236 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.text; import java.awt.event.KeyEvent; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.TextDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JTextComponentOperator; import org.netbeans.jemmy.operators.TextComponentOperator; /** * Superclass for all TextDrivers using API calls. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public abstract class TextAPIDriver extends LightSupportiveDriver implements TextDriver { /** * Constructs a ChoiceDriver. * @param supported an array of supported class names */ public TextAPIDriver(String[] supported) { super(supported); } public void changeCaretPosition(ComponentOperator oper, int position) { checkSupported(oper); if(oper instanceof TextComponentOperator) { ((TextComponentOperator)oper).setCaretPosition(position); } else { ((JTextComponentOperator)oper).setCaretPosition(position); } } public void selectText(ComponentOperator oper, int startPosition, int finalPosition) { checkSupported(oper); int start = (startPosition < finalPosition) ? startPosition : finalPosition; int end = (startPosition > finalPosition) ? startPosition : finalPosition; if(oper instanceof TextComponentOperator) { TextComponentOperator toper = ((TextComponentOperator)oper); toper.setSelectionStart(start); toper.setSelectionEnd(end); } else { JTextComponentOperator toper = ((JTextComponentOperator)oper); toper.setSelectionStart(start); toper.setSelectionEnd(end); } } public void clearText(ComponentOperator oper) { if(oper instanceof TextComponentOperator) { ((TextComponentOperator)oper).setText(""); } else { ((JTextComponentOperator)oper).setText(""); } } public void typeText(ComponentOperator oper, String text, int caretPosition) { checkSupported(oper); String curtext = getText(oper); int realPos = caretPosition; if(getSelectionStart(oper) == realPos || getSelectionEnd(oper) == realPos) { if(getSelectionEnd(oper) == realPos) { realPos = realPos - (getSelectionEnd(oper) - getSelectionStart(oper)); } curtext = curtext.substring(0, getSelectionStart(oper)) + curtext.substring(getSelectionEnd(oper)); } changeText(oper, curtext.substring(0, realPos) + text + curtext.substring(realPos)); } public void changeText(ComponentOperator oper, String text) { checkSupported(oper); if(oper instanceof TextComponentOperator) { ((TextComponentOperator)oper).setText(text); } else { ((JTextComponentOperator)oper).setText(text); } } public void enterText(ComponentOperator oper, String text) { changeText(oper, text); DriverManager.getKeyDriver(oper). pushKey(oper, KeyEvent.VK_ENTER, 0, new Timeout("", 0)); } /** * Returns operator's text. * @param oper an operator. * @return string representing component text. */ public abstract String getText(ComponentOperator oper); /** * Returns current caret position. * @param oper an operator. * @return int represnting current operator's caret position. */ public abstract int getCaretPosition(ComponentOperator oper); /** * Returns a caret position of selection start. * @param oper an operator. * @return int represnting index of operator's selection start. */ public abstract int getSelectionStart(ComponentOperator oper); /** * Returns a caret position of selection end. * @param oper an operator. * @return int represnting index of operator's selection end. */ public abstract int getSelectionEnd(ComponentOperator oper); } Jemmy2/src/org/netbeans/jemmy/drivers/text/UpKey.java0000644000175000017500000000464411245712347021643 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.text; class UpKey extends GoAndBackKey { private DownKey backKey; public UpKey(int keyCode, int mods) { super(keyCode, mods); } public void setDownKey(DownKey key) { backKey = key; } public int getDirection() { return(-1); } public GoAndBackKey getBackKey() { return(backKey); } } Jemmy2/src/org/netbeans/jemmy/drivers/text/OffsetKey.java0000644000175000017500000000442511064436407022501 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.text; abstract class OffsetKey extends NavigationKey{ public OffsetKey(int keyCode, int mods) { super(keyCode, mods); } public abstract int getExpectedPosition(); } Jemmy2/src/org/netbeans/jemmy/drivers/text/GoAndBackKey.java0000644000175000017500000000443311064436407023023 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.text; abstract class GoAndBackKey extends NavigationKey{ public GoAndBackKey(int keyCode, int mods) { super(keyCode, mods); } public abstract GoAndBackKey getBackKey(); } Jemmy2/src/org/netbeans/jemmy/drivers/text/SwingTextKeyboardDriver.java0000644000175000017500000001224311245712237025367 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.text; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.KeyDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JEditorPaneOperator; import org.netbeans.jemmy.operators.JTextAreaOperator; import org.netbeans.jemmy.operators.JTextComponentOperator; /** * TextDriver for swing text component types. * Uses keyboard operations. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class SwingTextKeyboardDriver extends TextKeyboardDriver { /** * Constructs a SwingTextKeyboardDriver. */ public SwingTextKeyboardDriver() { super(new String[] {"org.netbeans.jemmy.operators.JTextComponentOperator"}); } public void clearText(ComponentOperator oper) { if(oper instanceof JTextAreaOperator || oper instanceof JEditorPaneOperator) { DriverManager.getFocusDriver(oper).giveFocus(oper); KeyDriver kdriver = DriverManager.getKeyDriver(oper); selectText(oper, 0, getText(oper).length()); kdriver.pushKey(oper, KeyEvent.VK_DELETE, 0, oper.getTimeouts().create("ComponentOperator.PushKeyTimeout")); } else { super.clearText(oper); } } public String getText(ComponentOperator oper) { return(((JTextComponentOperator)oper).getDisplayedText()); } public int getCaretPosition(ComponentOperator oper) { return(((JTextComponentOperator)oper).getCaretPosition()); } public int getSelectionStart(ComponentOperator oper) { return(((JTextComponentOperator)oper).getSelectionStart()); } public int getSelectionEnd(ComponentOperator oper) { return(((JTextComponentOperator)oper).getSelectionEnd()); } public NavigationKey[] getKeys(ComponentOperator oper) { boolean multiString = oper instanceof JTextAreaOperator || oper instanceof JEditorPaneOperator; NavigationKey[] result = new NavigationKey[multiString ? 8 : 4]; result[0] = new UpKey (KeyEvent.VK_LEFT , 0); result[1] = new DownKey(KeyEvent.VK_RIGHT, 0); (( UpKey)result[0]).setDownKey((DownKey)result[1]); ((DownKey)result[1]).setUpKey (( UpKey)result[0]); if(multiString) { result[2] = new UpKey (KeyEvent.VK_UP , 0); result[3] = new DownKey(KeyEvent.VK_DOWN, 0); (( UpKey)result[2]).setDownKey((DownKey)result[3]); ((DownKey)result[3]).setUpKey (( UpKey)result[2]); result[4] = new UpKey (KeyEvent.VK_PAGE_UP , 0); result[5] = new DownKey(KeyEvent.VK_PAGE_DOWN, 0); (( UpKey)result[4]).setDownKey((DownKey)result[5]); ((DownKey)result[5]).setUpKey (( UpKey)result[4]); result[6] = new HomeKey(KeyEvent.VK_HOME, InputEvent.CTRL_MASK); result[7] = new EndKey(KeyEvent.VK_END , InputEvent.CTRL_MASK, this, oper); } else { result[2] = new HomeKey(KeyEvent.VK_HOME, 0); result[3] = new EndKey(KeyEvent.VK_END , 0, this, oper); } return(result); } public Timeout getBetweenTimeout(ComponentOperator oper) { return(oper.getTimeouts().create("TextComponentOperator.BetweenKeysTimeout")); } } Jemmy2/src/org/netbeans/jemmy/drivers/scrolling/0000755000175000017500000000000011572745223020745 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/drivers/scrolling/JScrollBarAPIDriver.java0000644000175000017500000001347211446273577025332 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.scrolling; import java.awt.Point; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JScrollBarOperator; /** * ScrollDriver for javax.swing.JScrollBar component type. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JScrollBarAPIDriver extends AbstractScrollDriver { private final static int SMALL_INCREMENT = 1; /** * Constructs a JScrollBarDriver. */ public JScrollBarAPIDriver() { super(new String[] {"org.netbeans.jemmy.operators.JScrollBarOperator"}); } @Override protected int position(ComponentOperator oper, int orientation) { return ((JScrollBarOperator)oper).getValue(); } public void scrollToMinimum(ComponentOperator oper, int orientation) { JScrollBarOperator scroll = (JScrollBarOperator)oper; setValue(oper, scroll.getMinimum()); } public void scrollToMaximum(ComponentOperator oper, int orientation) { JScrollBarOperator scroll = (JScrollBarOperator)oper; setValue(oper, scroll.getMaximum() - scroll.getVisibleAmount()); } protected void step(ComponentOperator oper, ScrollAdjuster adj) { JScrollBarOperator scroll = (JScrollBarOperator)oper; int newValue = -1; if(adj.getScrollDirection() == adj.DECREASE_SCROLL_DIRECTION) { newValue = (scroll.getValue() > scroll.getMinimum() + scroll.getUnitIncrement()) ? scroll.getValue() - scroll.getUnitIncrement() : scroll.getMinimum(); } else if(adj.getScrollDirection() == adj.INCREASE_SCROLL_DIRECTION) { newValue = (scroll.getValue() < scroll.getMaximum() - scroll.getVisibleAmount() - scroll.getUnitIncrement()) ? scroll.getValue() + scroll.getUnitIncrement() : scroll.getMaximum(); } setValue(oper, newValue); } private void setValue(ComponentOperator oper, int value) { if(value != -1) { ((JScrollBarOperator)oper).setValue(value); } } protected Timeout getScrollDeltaTimeout(ComponentOperator oper) { return(oper.getTimeouts(). create("JScrollBarOperator.DragAndDropScrollingDelta")); } protected void jump(final ComponentOperator oper, final ScrollAdjuster adj) { JScrollBarOperator scroll = (JScrollBarOperator)oper; int newValue = -1; if(adj.getScrollDirection() == adj.DECREASE_SCROLL_DIRECTION) { newValue = (scroll.getValue() > scroll.getMinimum() + scroll.getBlockIncrement()) ? scroll.getValue() - scroll.getBlockIncrement() : scroll.getMinimum(); } else if(adj.getScrollDirection() == adj.INCREASE_SCROLL_DIRECTION) { newValue = (scroll.getValue() < scroll.getMaximum() - scroll.getVisibleAmount() - scroll.getBlockIncrement()) ? scroll.getValue() + scroll.getBlockIncrement() : scroll.getMaximum(); } setValue(oper, newValue); } protected void startPushAndWait(ComponentOperator oper, int direction, int orientation) { } protected void stopPushAndWait(ComponentOperator oper, int direction, int orientation) { } protected Point startDragging(ComponentOperator oper) { return(null); } protected void drop(ComponentOperator oper, Point pnt) { } protected void drag(ComponentOperator oper, Point pnt) { } protected boolean canDragAndDrop(ComponentOperator oper) { return(false); } protected boolean canJump(ComponentOperator oper) { return(isSmallIncrement((JScrollBarOperator)oper)); } protected boolean canPushAndWait(ComponentOperator oper) { return(false); } protected int getDragAndDropStepLength(ComponentOperator oper) { return(1); } private boolean isSmallIncrement(JScrollBarOperator oper) { return(oper.getUnitIncrement(-1) <= SMALL_INCREMENT && oper.getUnitIncrement( 1) <= SMALL_INCREMENT); } } Jemmy2/src/org/netbeans/jemmy/drivers/scrolling/KeyboardJSliderScrollDriver.java0000644000175000017500000000632711446273577027200 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.scrolling; import java.awt.Adjustable; import java.awt.event.KeyEvent; import java.util.logging.Level; import java.util.logging.Logger; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.operators.ComponentOperator; /** * * @author shura */ public class KeyboardJSliderScrollDriver extends JSliderDriver { private static int getButton(int direction, int orientation) { if (direction == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { return (orientation == Adjustable.HORIZONTAL) ? KeyEvent.VK_LEFT : KeyEvent.VK_DOWN; } else { return (orientation == Adjustable.HORIZONTAL) ? KeyEvent.VK_RIGHT : KeyEvent.VK_UP; } } @Override protected boolean doPushAndWait(ComponentOperator oper, ScrollAdjuster adj, long freezeTimeout) { super.doPushAndWait(oper, adj, freezeTimeout); return true; } @Override protected void step(ComponentOperator oper, ScrollAdjuster adj) { oper.pushKey(getButton(adj.getScrollDirection(), adj.getScrollOrientation())); oper.getTimeouts().create("Waiter.TimeDelta").sleep(); } } Jemmy2/src/org/netbeans/jemmy/drivers/scrolling/ScrollAdjuster.java0000644000175000017500000000617411064436407024555 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.scrolling; /** * Specifies scrolling criteria. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public interface ScrollAdjuster { /** * Increase scroll direction. */ public static final int INCREASE_SCROLL_DIRECTION = 1; /** * Decrease scroll direction. */ public static final int DECREASE_SCROLL_DIRECTION = -1; /** * Specifies that necessary value has been reached.. */ public static final int DO_NOT_TOUCH_SCROLL_DIRECTION = 0; /** * Returns scroll direction to reach necessary scroller value. * @return one of the values: INCREASE_SCROLL_DIRECTION, DECREASE_SCROLL_DIRECTION or DO_NOT_TOUCH_SCROLL_DIRECTION. */ public int getScrollDirection(); /** * Returns scrolling orientation. * @return one of the values: Adjustable.HORIZONTAL or Adjustable.VERTICAL. */ public int getScrollOrientation(); /** * Returns a printable scrolling description. * @return a description. */ public String getDescription(); } Jemmy2/src/org/netbeans/jemmy/drivers/scrolling/package.html0000644000175000017500000000041111064436407023217 0ustar tonytony Scrolling drivers

Scrolling drivers

Different drivers to perform a scrolling operations.
@since 17 Apr 2002
Jemmy2/src/org/netbeans/jemmy/drivers/scrolling/AWTScrollDriver.java0000644000175000017500000001516711446273577024620 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.scrolling; import java.awt.Point; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.MouseDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.Operator; /** * ScrollDriver for awt components. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public abstract class AWTScrollDriver extends AbstractScrollDriver { private QueueTool queueTool; /** * Constructs a ChoiceDriver. * @param supported an array of supported class names */ public AWTScrollDriver(String[] supported) { super(supported); queueTool = new QueueTool(); } protected void step(final ComponentOperator oper, final ScrollAdjuster adj) { if(adj.getScrollDirection() != ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION) { queueTool.invokeSmoothly(new QueueTool.QueueAction("Choise expanding") { public Object launch() { Point clickPoint = getClickPoint(oper, adj.getScrollDirection(), adj.getScrollOrientation()); if(clickPoint != null) { DriverManager.getMouseDriver(oper). clickMouse(oper, clickPoint.x, clickPoint.y, 1, Operator.getDefaultMouseButton(), 0, oper.getTimeouts(). create("ComponentOperator.MouseClickTimeout")); } return(null); } }); } } protected void jump(ComponentOperator oper, ScrollAdjuster adj) {} protected void startPushAndWait(final ComponentOperator oper, final int direction, final int orientation) { queueTool.invokeSmoothly(new QueueTool.QueueAction("Choise expanding") { public Object launch() { Point clickPoint = getClickPoint(oper, direction, orientation); if(clickPoint != null) { MouseDriver mdriver = DriverManager.getMouseDriver(oper); mdriver.moveMouse(oper, clickPoint.x, clickPoint.y); mdriver.pressMouse(oper, clickPoint.x, clickPoint.y, Operator.getDefaultMouseButton(), 0); } return(null); } }); } protected void stopPushAndWait(final ComponentOperator oper, final int direction, final int orientation) { queueTool.invokeSmoothly(new QueueTool.QueueAction("Choise expanding") { public Object launch() { Point clickPoint = getClickPoint(oper, direction, orientation); if(clickPoint != null) { MouseDriver mdriver = DriverManager.getMouseDriver(oper); mdriver.releaseMouse(oper, clickPoint.x, clickPoint.y, Operator.getDefaultMouseButton(), 0); } return(null); } }); } protected Point startDragging(ComponentOperator oper) { return(null); } protected void drop(ComponentOperator oper, Point pnt) {} protected void drag(ComponentOperator oper, Point pnt) {} protected Timeout getScrollDeltaTimeout(ComponentOperator oper) { return(oper.getTimeouts(). create("ScrollbarOperator.DragAndDropScrollingDelta")); } protected boolean canDragAndDrop(ComponentOperator oper) { return(false); } protected boolean canJump(ComponentOperator oper) { return(false); } protected boolean canPushAndWait(ComponentOperator oper) { return(true); } protected int getDragAndDropStepLength(ComponentOperator oper) { return(1); } /** * Defines a click point which needs to be used in * order to increase/decrease scroller value. * @param oper an operator. * @param direction - one of the ScrollAdjister.INCREASE_SCROLL_DIRECTION, * ScrollAdjister.DECREASE_SCROLL_DIRECTION, ScrollAdjister.DO_NOT_TOUCH_SCROLL_DIRECTION values. * @param orientation one of the Adjustable.HORIZONTAL or Adjustable.VERTICAL values. * @return a point to click. */ protected abstract Point getClickPoint(ComponentOperator oper, int direction, int orientation); } Jemmy2/src/org/netbeans/jemmy/drivers/scrolling/AbstractScrollDriver.java0000644000175000017500000002421311446273577025720 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.scrolling; import java.awt.Adjustable; import java.awt.Point; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.ScrollDriver; import org.netbeans.jemmy.operators.ComponentOperator; /** * Superclass for all scroll drivers. * Contains all the logic of scrolling. * Tries allowed operations in this order: * "jump", "drag'n'drop", "push'n'wait", "step". * Repeats "step" scrolling while scroller value is not equal * to the necessary value, but no more than ADJUST_CLICK_COUNT. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public abstract class AbstractScrollDriver extends LightSupportiveDriver implements ScrollDriver { /** * Maximal number of attempts to reach required position * by minimal scrolling operation. */ public static final int ADJUST_CLICK_COUNT = 10; public static final String SCROLL_FREEZE_TIMEOUT = AbstractScrollDriver.class.getName() + ".freeze.timeout"; static { JemmyProperties.getProperties().initTimeout(SCROLL_FREEZE_TIMEOUT, 1000); } /** * Constructs an AbstractScrollDriver. * @param supported an array of supported class names */ public AbstractScrollDriver(String[] supported) { super(supported); } public void scroll(ComponentOperator oper, ScrollAdjuster adj) { if(canJump(oper)) { doJumps(oper, adj); } if(canDragAndDrop(oper)) { doDragAndDrop(oper, adj); } if(canPushAndWait(oper)) { if(!doPushAndWait(oper, adj, oper.getTimeouts().getTimeout(SCROLL_FREEZE_TIMEOUT))) { throw new JemmyException("Scrolling stuck for more than " + oper.getTimeouts().getTimeout(SCROLL_FREEZE_TIMEOUT) + " on " + oper); } } for(int i = 0; i < ADJUST_CLICK_COUNT; i++) { doSteps(oper, adj); } } /** * Performs minimal scrolling step. * @param oper an operator. * @param adj a scroll adjuster */ protected abstract void step(ComponentOperator oper, ScrollAdjuster adj); /** * Performs maximal scroll step. * @param oper an operator. * @param adj a scroll adjuster */ protected abstract void jump(ComponentOperator oper, ScrollAdjuster adj); /** * Presses something like a scroll button. * @param oper an operator. * @param direction - one of the ScrollAdjister.INCREASE_SCROLL_DIRECTION, * ScrollAdjister.DECREASE_SCROLL_DIRECTION, ScrollAdjister.DO_NOT_TOUCH_SCROLL_DIRECTION values. * @param orientation one of the Adjustable.HORIZONTAL or Adjustable.VERTICAL values. */ protected abstract void startPushAndWait(ComponentOperator oper, int direction, int orientation); /** * Releases something like a scroll button. * @param oper an operator. * @param direction - one of the ScrollAdjister.INCREASE_SCROLL_DIRECTION, * ScrollAdjister.DECREASE_SCROLL_DIRECTION, ScrollAdjister.DO_NOT_TOUCH_SCROLL_DIRECTION values. * @param orientation one of the Adjustable.HORIZONTAL or Adjustable.VERTICAL values. */ protected abstract void stopPushAndWait(ComponentOperator oper, int direction, int orientation); /** * Starts drag'n'drop scrolling. * @param oper an operator. * @return start drugging point. */ protected abstract Point startDragging(ComponentOperator oper); /** * Drop at a specified point. * @param oper an operator. * @param pnt the point to drop. */ protected abstract void drop(ComponentOperator oper, Point pnt); /** * Drag to a specified point. * @param oper an operator. * @param pnt the point to drag to. */ protected abstract void drag(ComponentOperator oper, Point pnt); /** * Returns a timeout for sleeping between verifications during * "push and wait" scrolling. * @param oper an operator. * @return a timeout */ protected abstract Timeout getScrollDeltaTimeout(ComponentOperator oper); /** * Tells if this driver allows to perform drag'n'drop scrolling. * @param oper an operator. * @return true if this driver allows to drag'n'drop. */ protected abstract boolean canDragAndDrop(ComponentOperator oper); /** * Tells if this driver allows to perform jumps. * @param oper an operator. * @return true if this driver allows to jump. */ protected abstract boolean canJump(ComponentOperator oper); /** * Tells if this driver allows to perform "push and wait" scrolling. * @param oper an operator. * @return true if this driver allows to "push and wait". */ protected abstract boolean canPushAndWait(ComponentOperator oper); /** * Returns a number of pixels in one drag and drop scrolling. * @param oper an operator. * @return drag'n'drop step length. */ protected abstract int getDragAndDropStepLength(ComponentOperator oper); /** * Performs drag'n'drop scrolling till scroller's value * does not cross required value. * @param oper an operator. * @param adj a scroll adjuster */ protected void doDragAndDrop(ComponentOperator oper, ScrollAdjuster adj) { int direction = adj.getScrollDirection(); if(direction != adj.DO_NOT_TOUCH_SCROLL_DIRECTION) { Point pnt = startDragging(oper); while(adj.getScrollDirection() == direction) { drag(oper, pnt = increasePoint(oper, pnt, adj, direction)); } drop(oper, pnt); } } /** * Performs jump scrolling till scroller's value * does not cross required value. * @param oper an operator. * @param adj a scroll adjuster */ protected void doJumps(ComponentOperator oper, ScrollAdjuster adj) { int direction = adj.getScrollDirection(); if(direction != adj.DO_NOT_TOUCH_SCROLL_DIRECTION) { while(adj.getScrollDirection() == direction) { jump(oper, adj); } } } protected abstract int position(ComponentOperator oper, int orientation); /** * Performs "push and wait" scrolling till scroller's value * does not cross required value. * @param oper an operator. * @param adj a scroll adjuster */ protected boolean doPushAndWait(ComponentOperator oper, ScrollAdjuster adj, long freezeTimeout) { int direction = adj.getScrollDirection(); int orientation = adj.getScrollOrientation(); int position = position(oper, orientation); long lastChanded = System.currentTimeMillis(); if(direction != adj.DO_NOT_TOUCH_SCROLL_DIRECTION) { Timeout delta = getScrollDeltaTimeout(oper); startPushAndWait(oper, direction, orientation); while(adj.getScrollDirection() == direction) { delta.sleep(); int curPosition = position(oper, orientation); if(curPosition != position) { position = curPosition; lastChanded = System.currentTimeMillis(); } else { if((System.currentTimeMillis() - lastChanded) > freezeTimeout) { return false; } } } stopPushAndWait(oper, direction, orientation); } return true; } /** * Performs minimal scrollings till scroller's value * does not cross required value. * @param oper an operator. * @param adj a scroll adjuster */ protected void doSteps(ComponentOperator oper, ScrollAdjuster adj) { int direction = adj.getScrollDirection(); if(direction != adj.DO_NOT_TOUCH_SCROLL_DIRECTION) { while(adj.getScrollDirection() == direction) { step(oper, adj); } } } private Point increasePoint(ComponentOperator oper, Point pnt, ScrollAdjuster adj, int direction) { return((adj.getScrollOrientation() == Adjustable.HORIZONTAL) ? new Point(pnt.x + ((direction == 1) ? 1 : -1) * getDragAndDropStepLength(oper), pnt.y) : new Point(pnt.x, pnt.y + ((direction == 1) ? 1 : -1) * getDragAndDropStepLength(oper))); } } Jemmy2/src/org/netbeans/jemmy/drivers/scrolling/ScrollbarDriver.java0000644000175000017500000001130011446273577024712 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.scrolling; import java.awt.Point; import java.awt.Scrollbar; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.ScrollbarOperator; /** * ScrollDriver for java.awt.Scrollbar component type. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class ScrollbarDriver extends AWTScrollDriver { private static final int CLICK_OFFSET = 5; /** * Constructs a ScrollbarDriver. */ public ScrollbarDriver() { super(new String[] {"org.netbeans.jemmy.operators.ScrollbarOperator"}); } @Override protected int position(ComponentOperator oper, int orientation) { return ((ScrollbarOperator)oper).getValue(); } public void scrollToMinimum(final ComponentOperator oper, final int orientation) { scroll(oper, new ScrollAdjuster() { public int getScrollDirection() { return((((ScrollbarOperator)oper).getMinimum() < ((ScrollbarOperator)oper).getValue()) ? DECREASE_SCROLL_DIRECTION : DO_NOT_TOUCH_SCROLL_DIRECTION); } public int getScrollOrientation() { return(((ScrollbarOperator)oper).getOrientation()); } public String getDescription() { return("Scroll to minimum"); } }); } public void scrollToMaximum(final ComponentOperator oper, final int orientation) { scroll(oper, new ScrollAdjuster() { public int getScrollDirection() { return(((((ScrollbarOperator)oper).getMaximum() - ((ScrollbarOperator)oper).getVisibleAmount()) > ((ScrollbarOperator)oper).getValue()) ? INCREASE_SCROLL_DIRECTION : DO_NOT_TOUCH_SCROLL_DIRECTION); } public int getScrollOrientation() { return(((ScrollbarOperator)oper).getOrientation()); } public String getDescription() { return("Scroll to maximum"); } }); } protected Point getClickPoint(ComponentOperator oper, int direction, int orientation) { int x, y; if (orientation == Scrollbar.HORIZONTAL) { if (direction == ScrollAdjuster.INCREASE_SCROLL_DIRECTION) { x = oper.getWidth() - 1 - CLICK_OFFSET; } else if(direction == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { x = CLICK_OFFSET; } else { return(null); } y = oper.getHeight() / 2; } else if(orientation == Scrollbar.VERTICAL) { if (direction == ScrollAdjuster.INCREASE_SCROLL_DIRECTION) { y = oper.getHeight() - 1 - CLICK_OFFSET; } else if(direction == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { y = CLICK_OFFSET; } else { return(null); } x = oper.getWidth() / 2; } else { return(null); } return(new Point(x, y)); } } Jemmy2/src/org/netbeans/jemmy/drivers/scrolling/JSliderDriver.java0000644000175000017500000002147211446273577024336 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.scrolling; import java.awt.Point; import javax.swing.JSlider; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.MouseDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JSliderOperator; import org.netbeans.jemmy.operators.Operator; /** * A scroll driver serving JSlider component. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JSliderDriver extends AbstractScrollDriver { private QueueTool queueTool; /** * Constructs a JSliderDriver object. */ public JSliderDriver() { super(new String[] {"org.netbeans.jemmy.operators.JSliderOperator"}); queueTool = new QueueTool(); } @Override protected int position(ComponentOperator oper, int orientation) { return ((JSliderOperator)oper).getValue(); } public void scrollToMinimum(final ComponentOperator oper, int orientation) { checkSupported(oper); scroll(oper, new ScrollAdjuster() { public int getScrollDirection() { return((((JSliderOperator)oper).getMinimum() < ((JSliderOperator)oper).getValue()) ? DECREASE_SCROLL_DIRECTION : DO_NOT_TOUCH_SCROLL_DIRECTION); } public int getScrollOrientation() { return(((JSliderOperator)oper).getOrientation()); } public String getDescription() { return("Scroll to minimum"); } }); } public void scrollToMaximum(final ComponentOperator oper, int orientation) { checkSupported(oper); scroll(oper, new ScrollAdjuster() { public int getScrollDirection() { return((((JSliderOperator)oper).getMaximum() > ((JSliderOperator)oper).getValue()) ? INCREASE_SCROLL_DIRECTION : DO_NOT_TOUCH_SCROLL_DIRECTION); } public int getScrollOrientation() { return(((JSliderOperator)oper).getOrientation()); } public String getDescription() { return("Scroll to maximum"); } }); } protected void step(final ComponentOperator oper, final ScrollAdjuster adj) { if(adj.getScrollDirection() != ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION) { queueTool.invokeSmoothly(new QueueTool.QueueAction("Choise expanding") { public Object launch() { Point clickPoint = getClickPoint(oper, adj.getScrollDirection(), adj.getScrollOrientation()); if(clickPoint != null) { DriverManager.getMouseDriver(oper). clickMouse(oper, clickPoint.x, clickPoint.y, 1, Operator.getDefaultMouseButton(), 0, oper.getTimeouts(). create("ComponentOperator.MouseClickTimeout")); } return(null); } }); } } protected void jump(ComponentOperator oper, ScrollAdjuster adj) { //cannot } protected void startPushAndWait(final ComponentOperator oper, final int direction, final int orientation) { queueTool.invokeSmoothly(new QueueTool.QueueAction("Start scrolling") { public Object launch() { Point clickPoint = getClickPoint(oper, direction, orientation); if(clickPoint != null) { MouseDriver mdriver = DriverManager.getMouseDriver(oper); mdriver.moveMouse(oper, clickPoint.x, clickPoint.y); mdriver.pressMouse(oper, clickPoint.x, clickPoint.y, Operator.getDefaultMouseButton(), 0); } return(null); } }); } protected void stopPushAndWait(final ComponentOperator oper, final int direction, final int orientation) { queueTool.invokeSmoothly(new QueueTool.QueueAction("Stop scrolling") { public Object launch() { Point clickPoint = getClickPoint(oper, direction, orientation); if(clickPoint != null) { MouseDriver mdriver = DriverManager.getMouseDriver(oper); mdriver.releaseMouse(oper, clickPoint.x, clickPoint.y, Operator.getDefaultMouseButton(), 0); } return(null); } }); } protected Point startDragging(ComponentOperator oper) { //cannot return(null); } protected void drop(ComponentOperator oper, Point pnt) { //cannot } protected void drag(ComponentOperator oper, Point pnt) { //cannot } protected Timeout getScrollDeltaTimeout(ComponentOperator oper) { return(oper.getTimeouts().create("JSliderOperator.ScrollingDelta")); } protected boolean canDragAndDrop(ComponentOperator oper) { return(false); } protected boolean canJump(ComponentOperator oper) { return(false); } protected boolean canPushAndWait(ComponentOperator oper) { return(true); } protected int getDragAndDropStepLength(ComponentOperator oper) { return(0); } private Point getClickPoint(ComponentOperator oper, int direction, int orientation) { int x, y; boolean inverted = ((JSliderOperator)oper).getInverted(); int realDirection = ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION; if(inverted) { if (direction == ScrollAdjuster.INCREASE_SCROLL_DIRECTION) { realDirection = ScrollAdjuster.DECREASE_SCROLL_DIRECTION; } else if(direction == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { realDirection = ScrollAdjuster.INCREASE_SCROLL_DIRECTION; } else { return(null); } } else { realDirection = direction; } if (orientation == JSlider.HORIZONTAL) { if (realDirection == ScrollAdjuster.INCREASE_SCROLL_DIRECTION) { x = oper.getWidth() - 1; } else if(realDirection == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { x = 0; } else { return(null); } y = oper.getHeight() / 2; } else if(orientation == JSlider.VERTICAL) { if (realDirection == ScrollAdjuster.INCREASE_SCROLL_DIRECTION) { y = 0; } else if(realDirection == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { y = oper.getHeight() - 1; } else { return(null); } x = oper.getWidth() / 2; } else { return(null); } return(new Point(x, y)); } } Jemmy2/src/org/netbeans/jemmy/drivers/scrolling/JSplitPaneDriver.java0000644000175000017500000001600511446273577025007 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.scrolling; import javax.swing.JButton; import javax.swing.JSplitPane; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.drivers.ButtonDriver; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.ScrollDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.ContainerOperator; import org.netbeans.jemmy.operators.JButtonOperator; import org.netbeans.jemmy.operators.JSplitPaneOperator; /** * ScrollDriver for javax.swing.JSplitPane component type. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JSplitPaneDriver extends LightSupportiveDriver implements ScrollDriver { /** * Constructs a JSplitPaneDriver. */ public JSplitPaneDriver() { super(new String[] {"org.netbeans.jemmy.operators.JSplitPaneOperator"}); } public void scroll(ComponentOperator oper, ScrollAdjuster adj) { moveDividerTo((JSplitPaneOperator)oper, adj); } public void scrollToMinimum(ComponentOperator oper, int orientation) { expandTo((JSplitPaneOperator)oper, 0); } public void scrollToMaximum(ComponentOperator oper, int orientation) { expandTo((JSplitPaneOperator)oper, 1); } private void moveDividerTo(JSplitPaneOperator oper, ScrollAdjuster adj) { ContainerOperator divOper = oper.getDivider(); /* workaround */ if(oper.getDividerLocation() == -1) { moveTo(oper, divOper, divOper.getCenterX() - 1, divOper.getCenterY() - 1); if(oper. getDividerLocation() == -1) { moveTo(oper, divOper, divOper.getCenterX() + 1, divOper.getCenterY() + 1); } } if(oper.getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { moveOnce(oper, divOper, adj, 0, oper.getWidth()); } else { moveOnce(oper, divOper, adj, 0, oper.getHeight()); } } private void moveOnce(JSplitPaneOperator oper, ContainerOperator divOper, ScrollAdjuster adj, int leftPosition, int rightPosition) { int currentPosition = 0; if(oper.getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { currentPosition = (int)(divOper.getLocationOnScreen().getX() - oper.getLocationOnScreen().getX()); } else { currentPosition = (int)(divOper.getLocationOnScreen().getY() - oper.getLocationOnScreen().getY()); } int nextPosition = 0; if (adj.getScrollDirection() == adj.DECREASE_SCROLL_DIRECTION) { nextPosition = (int)((currentPosition + leftPosition) / 2); moveToPosition(oper, divOper, nextPosition - currentPosition); if(currentPosition == ((adj.getScrollOrientation() == JSplitPane.HORIZONTAL_SPLIT) ? (int)(divOper.getLocationOnScreen().getX() - oper.getLocationOnScreen().getX()) : (int)(divOper.getLocationOnScreen().getY() - oper.getLocationOnScreen().getY()))) { return; } moveOnce(oper, divOper, adj, leftPosition, currentPosition); } else if(adj.getScrollDirection() == adj.INCREASE_SCROLL_DIRECTION) { nextPosition = (int)((currentPosition + rightPosition) / 2); moveToPosition(oper, divOper, nextPosition - currentPosition); if(currentPosition == ((adj.getScrollOrientation() == JSplitPane.HORIZONTAL_SPLIT) ? (int)(divOper.getLocationOnScreen().getX() - oper.getLocationOnScreen().getX()) : (int)(divOper.getLocationOnScreen().getY() - oper.getLocationOnScreen().getY()))) { return; } moveOnce(oper, divOper, adj, currentPosition, rightPosition); } else { // (currentLocation == dividerLocation) - stop point return; } } private void moveTo(JSplitPaneOperator oper, ComponentOperator divOper, int x, int y) { DriverManager.getMouseDriver(divOper). dragNDrop(divOper, divOper.getCenterX(), divOper.getCenterY(), x, y, oper.getDefaultMouseButton(), 0, oper.getTimeouts().create("ComponentOperator.BeforeDragTimeout"), oper.getTimeouts().create("ComponentOperator.AfterDragTimeout")); } private void moveToPosition(JSplitPaneOperator oper, ComponentOperator divOper, int nextPosition) { if(System.getProperty("java.version").startsWith("1.2")) { oper.setDividerLocation(nextPosition); } if(oper.getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { moveTo(oper, divOper, divOper.getCenterX() + nextPosition, divOper.getCenterY()); } else { moveTo(oper, divOper, divOper.getCenterX(), divOper.getCenterY() + nextPosition); } } private void expandTo(JSplitPaneOperator oper, int index) { ContainerOperator divOper = oper.getDivider(); JButtonOperator bo = new JButtonOperator((JButton)divOper. waitSubComponent(new JButtonOperator. JButtonFinder(ComponentSearcher. getTrueChooser("JButton")), index)); bo.copyEnvironment(divOper); ButtonDriver bdriver = DriverManager.getButtonDriver(bo); bdriver.push(bo); bdriver.push(bo); } } Jemmy2/src/org/netbeans/jemmy/drivers/scrolling/JScrollBarDriver.java0000644000175000017500000002510011446273577024767 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.scrolling; import java.awt.Point; import javax.swing.JScrollBar; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.MouseDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JButtonOperator; import org.netbeans.jemmy.operators.JScrollBarOperator; /** * ScrollDriver for javax.swing.JScrollBar component type. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JScrollBarDriver extends AbstractScrollDriver { private final static int SMALL_INCREMENT = 1; private final static int MINIMAL_DRAGGER_SIZE = 5; private final static int RELATIVE_DRAG_STEP_LENGTH = 20; private QueueTool queueTool; /** * Constructs a JScrollBarDriver. */ public JScrollBarDriver() { super(new String[] {"org.netbeans.jemmy.operators.JScrollBarOperator"}); queueTool = new QueueTool(); } @Override protected int position(ComponentOperator oper, int orientation) { return ((JScrollBarOperator)oper).getValue(); } public void scrollToMinimum(ComponentOperator oper, int orientation) { startDragging(oper); Point pnt = new Point(0, 0); drag(oper, pnt); Timeout sleepTime = oper.getTimeouts().create("Waiter.TimeDelta"); while(((JScrollBarOperator)oper).getValue() > ((JScrollBarOperator)oper).getMinimum()) { sleepTime.sleep(); } drop(oper, pnt); } public void scrollToMaximum(ComponentOperator oper, int orientation) { startDragging(oper); Point pnt = new Point(oper.getWidth() - 1, oper.getHeight() - 1); drag(oper, pnt); Timeout sleepTime = oper.getTimeouts().create("Waiter.TimeDelta"); while(((JScrollBarOperator)oper).getValue() > (((JScrollBarOperator)oper).getMaximum() - ((JScrollBarOperator)oper).getVisibleAmount())) { sleepTime.sleep(); } drop(oper, pnt); } protected void step(ComponentOperator oper, ScrollAdjuster adj) { JButtonOperator boper = findAButton(oper, adj.getScrollDirection()); DriverManager.getButtonDriver(boper).push(boper); } protected void jump(final ComponentOperator oper, final ScrollAdjuster adj) { final JButtonOperator lessButton = findAButton(oper, adj.DECREASE_SCROLL_DIRECTION); final JButtonOperator moreButton = findAButton(oper, adj.INCREASE_SCROLL_DIRECTION); queueTool.invokeSmoothly(new QueueTool.QueueAction("Choise expanding") { public Object launch() { if(adj.getScrollDirection() != ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION) { int x, y; if (((JScrollBarOperator)oper).getOrientation() == JScrollBar.HORIZONTAL) { if (adj.getScrollDirection() == ScrollAdjuster.INCREASE_SCROLL_DIRECTION) { x = moreButton.getX() - 1; } else if(adj.getScrollDirection() == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { x = lessButton .getX() + lessButton.getWidth(); } else { return(null); } y = lessButton.getHeight() / 2; } else if(((JScrollBarOperator)oper).getOrientation() == JScrollBar.VERTICAL) { if (adj.getScrollDirection() == ScrollAdjuster.INCREASE_SCROLL_DIRECTION) { y = moreButton.getY() - 1; } else if(adj.getScrollDirection() == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { y = lessButton .getY() + lessButton.getHeight(); } else { return(null); } x = lessButton.getWidth() / 2; } else { return(null); } DriverManager.getMouseDriver(oper). clickMouse(oper, x, y, 1, oper.getDefaultMouseButton(), 0, new Timeout("", 0)); } return(null); } }); } protected void startPushAndWait(ComponentOperator oper, int direction, int orientation) { JButtonOperator boper = findAButton(oper, direction); DriverManager.getButtonDriver(boper).press(boper); } protected void stopPushAndWait(ComponentOperator oper, int direction, int orientation) { JButtonOperator boper = findAButton(oper, direction); DriverManager.getButtonDriver(boper).release(boper); } protected Point startDragging(ComponentOperator oper) { JButtonOperator lessButton = findAButton(oper, ScrollAdjuster.DECREASE_SCROLL_DIRECTION); JButtonOperator moreButton = findAButton(oper, ScrollAdjuster.INCREASE_SCROLL_DIRECTION); Point pnt = getClickPoint((JScrollBarOperator)oper, lessButton, moreButton, ((JScrollBarOperator)oper).getValue()); MouseDriver mdriver = DriverManager.getMouseDriver(oper); mdriver.moveMouse(oper, pnt.x, pnt.y); mdriver.pressMouse(oper, pnt.x, pnt.y, oper.getDefaultMouseButton(), 0); return(pnt); } protected void drop(ComponentOperator oper, Point pnt) { DriverManager.getMouseDriver(oper). releaseMouse(oper, pnt.x, pnt.y, oper.getDefaultMouseButton(), 0); } protected void drag(ComponentOperator oper, Point pnt) { DriverManager.getMouseDriver(oper). dragMouse(oper, pnt.x, pnt.y, oper.getDefaultMouseButton(), 0); } protected Timeout getScrollDeltaTimeout(ComponentOperator oper) { return(oper.getTimeouts(). create("ScrollbarOperator.DragAndDropScrollingDelta")); } protected boolean canDragAndDrop(ComponentOperator oper) { if(!isSmallIncrement((JScrollBarOperator)oper)) { return(false); } boolean result = false; MouseDriver mdriver = DriverManager.getMouseDriver(oper); JButtonOperator less = findAButton(oper, ScrollAdjuster.DECREASE_SCROLL_DIRECTION); JButtonOperator more = findAButton(oper, ScrollAdjuster.INCREASE_SCROLL_DIRECTION); Point pnt = getClickPoint((JScrollBarOperator)oper, less, more, ((JScrollBarOperator)oper).getValue()); mdriver.moveMouse(oper, pnt.x, pnt.y); mdriver.pressMouse(oper, pnt.x, pnt.y, oper.getDefaultMouseButton(), 0); result = ((JScrollBarOperator)oper).getValueIsAdjusting(); mdriver.releaseMouse(oper, pnt.x, pnt.y, oper.getDefaultMouseButton(), 0); return(result && isSmallIncrement((JScrollBarOperator)oper)); } protected boolean canJump(ComponentOperator oper) { return(isSmallIncrement((JScrollBarOperator)oper)); } protected boolean canPushAndWait(ComponentOperator oper) { return(isSmallIncrement((JScrollBarOperator)oper)); } protected int getDragAndDropStepLength(ComponentOperator oper) { JButtonOperator less = findAButton(oper, ScrollAdjuster.DECREASE_SCROLL_DIRECTION); JButtonOperator more = findAButton(oper, ScrollAdjuster.INCREASE_SCROLL_DIRECTION); int width = oper.getWidth() - less.getWidth() - more.getWidth(); int height = oper.getHeight() - less.getHeight() - more.getHeight(); int max = (width > height) ? width : height; if(max >= RELATIVE_DRAG_STEP_LENGTH * 2) { return((int)(max / RELATIVE_DRAG_STEP_LENGTH)); } else { return(1); } } private boolean isSmallIncrement(JScrollBarOperator oper) { return(oper.getUnitIncrement(-1) <= SMALL_INCREMENT && oper.getUnitIncrement( 1) <= SMALL_INCREMENT); } private Point getClickPoint(JScrollBarOperator oper, JButtonOperator lessButton, JButtonOperator moreButton, int value) { int lenght = (oper.getOrientation() == JScrollBar.HORIZONTAL) ? oper.getWidth() - lessButton.getWidth() - moreButton.getWidth() : oper.getHeight() - lessButton.getHeight() - moreButton.getHeight(); int subpos = (int)(((float)lenght / (oper.getMaximum() - oper.getMinimum())) * value); if(oper.getOrientation() == JScrollBar.HORIZONTAL) { subpos = subpos + lessButton.getWidth(); } else { subpos = subpos + lessButton.getHeight(); } subpos = subpos + MINIMAL_DRAGGER_SIZE / 2 + 1; return((oper.getOrientation() == JScrollBar.HORIZONTAL) ? new Point(subpos, oper.getHeight() / 2) : new Point(oper.getWidth() / 2, subpos)); } private JButtonOperator findAButton(ComponentOperator oper, int direction) { return((direction == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) ? ((JScrollBarOperator)oper).getDecreaseButton() : ((JScrollBarOperator)oper).getIncreaseButton()); } } Jemmy2/src/org/netbeans/jemmy/drivers/scrolling/JSpinnerDriver.java0000644000175000017500000001254511245712237024517 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.scrolling; import javax.swing.SwingConstants; import org.netbeans.jemmy.drivers.LightSupportiveDriver; import org.netbeans.jemmy.drivers.ScrollDriver; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JButtonOperator; import org.netbeans.jemmy.operators.JSpinnerOperator; /** * A scroll driver serving JSpinner component. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JSpinnerDriver extends LightSupportiveDriver implements ScrollDriver { /** * Constructs a JSpinnerDriver object. */ public JSpinnerDriver() { super(new String[] {"org.netbeans.jemmy.operators.JSpinnerOperator"}); } public void scrollToMinimum(final ComponentOperator oper, int orientation) { Object minimum = ((JSpinnerOperator)oper).getMinimum(); if(minimum == null) { throw(new JSpinnerOperator.SpinnerModelException("Impossible to get a minimum of JSpinner model.", oper.getSource())); } scroll(oper, new ScrollAdjuster() { public int getScrollOrientation() { return(SwingConstants.VERTICAL); } public String getDescription() { return("Spin to minimum"); } public int getScrollDirection() { if(((JSpinnerOperator)oper).getModel().getPreviousValue() != null) { return(ScrollAdjuster.DECREASE_SCROLL_DIRECTION); } else { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } } }); } public void scrollToMaximum(final ComponentOperator oper, int orientation) { Object maximum = ((JSpinnerOperator)oper).getMaximum(); if(maximum == null) { throw(new JSpinnerOperator.SpinnerModelException("Impossible to get a maximum of JSpinner model.", oper.getSource())); } scroll(oper, new ScrollAdjuster() { public int getScrollOrientation() { return(SwingConstants.VERTICAL); } public String getDescription() { return("Spin to maximum"); } public int getScrollDirection() { if(((JSpinnerOperator)oper).getModel().getNextValue() != null) { return(ScrollAdjuster.INCREASE_SCROLL_DIRECTION); } else { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } } }); } public void scroll(ComponentOperator oper, ScrollAdjuster adj) { JButtonOperator increaseButton = ((JSpinnerOperator)oper).getIncreaseOperator(); JButtonOperator decreaseButton = ((JSpinnerOperator)oper).getDecreaseOperator(); if(adj.getScrollDirection() == ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION) { return; } int originalDirection = adj.getScrollDirection(); while(adj.getScrollDirection() == originalDirection) { if(originalDirection == ScrollAdjuster.INCREASE_SCROLL_DIRECTION) { increaseButton.push(); } else { decreaseButton.push(); } } } } Jemmy2/src/org/netbeans/jemmy/drivers/scrolling/JSliderAPIDriver.java0000644000175000017500000001414311446273577024665 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.scrolling; import java.awt.Point; import org.netbeans.jemmy.Timeout; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.JSliderOperator; /** * A scroll driver serving JSlider component. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class JSliderAPIDriver extends AbstractScrollDriver { private final static int SMALL_INCREMENT = 1; /** * Constructs a JSliderDriver object. */ public JSliderAPIDriver() { super(new String[] {"org.netbeans.jemmy.operators.JSliderOperator"}); } @Override protected int position(ComponentOperator oper, int orientation) { return ((JSliderOperator)oper).getValue(); } public void scrollToMinimum(final ComponentOperator oper, int orientation) { ((JSliderOperator)oper).setValue(((JSliderOperator)oper).getMinimum()); } public void scrollToMaximum(final ComponentOperator oper, int orientation) { ((JSliderOperator)oper).setValue(((JSliderOperator)oper).getMaximum()); } protected void step(ComponentOperator oper, ScrollAdjuster adj) { JSliderOperator scroll = (JSliderOperator)oper; int newValue = -1; if(adj.getScrollDirection() == adj.DECREASE_SCROLL_DIRECTION) { newValue = (scroll.getValue() > scroll.getMinimum() + getUnitIncrement(scroll)) ? scroll.getValue() - getUnitIncrement(scroll) : scroll.getMinimum(); } else if(adj.getScrollDirection() == adj.INCREASE_SCROLL_DIRECTION) { newValue = (scroll.getValue() < scroll.getMaximum() - getUnitIncrement(scroll)) ? scroll.getValue() + getUnitIncrement(scroll) : scroll.getMaximum(); } setValue(oper, newValue); } private void setValue(ComponentOperator oper, int value) { if(value != -1) { ((JSliderOperator)oper).setValue(value); } } protected Timeout getScrollDeltaTimeout(ComponentOperator oper) { return(oper.getTimeouts(). create("JSliderOperator.ScrollingDelta")); } protected void jump(final ComponentOperator oper, final ScrollAdjuster adj) { JSliderOperator scroll = (JSliderOperator)oper; int newValue = -1; if(adj.getScrollDirection() == adj.DECREASE_SCROLL_DIRECTION) { newValue = (scroll.getValue() > scroll.getMinimum() + getBlockIncrement(scroll)) ? scroll.getValue() - getBlockIncrement(scroll) : scroll.getMinimum(); } else if(adj.getScrollDirection() == adj.INCREASE_SCROLL_DIRECTION) { newValue = (scroll.getValue() < scroll.getMaximum() - getBlockIncrement(scroll)) ? scroll.getValue() + getBlockIncrement(scroll) : scroll.getMaximum(); } setValue(oper, newValue); } protected void startPushAndWait(ComponentOperator oper, int direction, int orientation) { } protected void stopPushAndWait(ComponentOperator oper, int direction, int orientation) { } protected Point startDragging(ComponentOperator oper) { return(null); } protected void drop(ComponentOperator oper, Point pnt) { } protected void drag(ComponentOperator oper, Point pnt) { } protected boolean canDragAndDrop(ComponentOperator oper) { return(false); } protected boolean canJump(ComponentOperator oper) { return(isSmallIncrement((JSliderOperator)oper)); } protected boolean canPushAndWait(ComponentOperator oper) { return(false); } protected int getDragAndDropStepLength(ComponentOperator oper) { return(1); } private int getUnitIncrement(JSliderOperator oper) { return((oper.getMinorTickSpacing() == 0) ? 1 : oper.getMinorTickSpacing()); } private int getBlockIncrement(JSliderOperator oper) { return((oper.getMajorTickSpacing() == 0) ? 1 : oper.getMajorTickSpacing()); } private boolean isSmallIncrement(JSliderOperator oper) { return(oper.getMajorTickSpacing() <= SMALL_INCREMENT && oper.getMajorTickSpacing() <= SMALL_INCREMENT); } } Jemmy2/src/org/netbeans/jemmy/drivers/scrolling/ScrollPaneDriver.java0000644000175000017500000001260211446273577025037 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.drivers.scrolling; import java.awt.Adjustable; import java.awt.Point; import java.awt.Scrollbar; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.jemmy.operators.ScrollPaneOperator; /** * ScrollDriver for java.awt.ScrollPane component type. * * @author Alexandre Iline(alexandre.iline@sun.com) */ public class ScrollPaneDriver extends AWTScrollDriver { private static final int CLICK_OFFSET = 5; /** * Constructs a ScrollPaneDriver. */ public ScrollPaneDriver() { super(new String[] {"org.netbeans.jemmy.operators.ScrollPaneOperator"}); } @Override protected int position(ComponentOperator oper, int orientation) { return (orientation == Adjustable.HORIZONTAL) ? ((ScrollPaneOperator)oper).getScrollPosition().x : ((ScrollPaneOperator)oper).getScrollPosition().y; } public void scrollToMinimum(ComponentOperator oper, final int orientation) { final Adjustable adj = (orientation == Scrollbar.HORIZONTAL) ? ((ScrollPaneOperator)oper).getHAdjustable() : ((ScrollPaneOperator)oper).getVAdjustable(); scroll(oper, new ScrollAdjuster() { public int getScrollDirection() { return((adj.getMinimum() < adj.getValue()) ? DECREASE_SCROLL_DIRECTION : DO_NOT_TOUCH_SCROLL_DIRECTION); } public int getScrollOrientation() { return(orientation); } public String getDescription() { return("Scroll to minimum"); } }); } public void scrollToMaximum(ComponentOperator oper, final int orientation) { final Adjustable adj = (orientation == Scrollbar.HORIZONTAL) ? ((ScrollPaneOperator)oper).getHAdjustable() : ((ScrollPaneOperator)oper).getVAdjustable(); scroll(oper, new ScrollAdjuster() { public int getScrollDirection() { return(((adj.getMaximum() - adj.getVisibleAmount()) > adj.getValue()) ? INCREASE_SCROLL_DIRECTION : DO_NOT_TOUCH_SCROLL_DIRECTION); } public int getScrollOrientation() { return(orientation); } public String getDescription() { return("Scroll to maximum"); } }); } protected Point getClickPoint(ComponentOperator oper, int direction, int orientation) { int x, y; if (orientation == Scrollbar.HORIZONTAL) { int offset = ((ScrollPaneOperator)oper). isScrollbarVisible(Scrollbar.VERTICAL) ? ((ScrollPaneOperator)oper).getVScrollbarWidth() : 0; if (direction == ScrollAdjuster.INCREASE_SCROLL_DIRECTION) { x = oper.getWidth() - 1 - CLICK_OFFSET - offset; } else if(direction == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { x = CLICK_OFFSET; } else { return(null); } y = oper.getHeight() - ((ScrollPaneOperator)oper).getHScrollbarHeight() / 2; } else if(orientation == Scrollbar.VERTICAL) { int offset = ((ScrollPaneOperator)oper). isScrollbarVisible(Scrollbar.HORIZONTAL) ? ((ScrollPaneOperator)oper).getHScrollbarHeight() : 0; if (direction == ScrollAdjuster.INCREASE_SCROLL_DIRECTION) { y = oper.getHeight() - 1 - CLICK_OFFSET - offset; } else if(direction == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { y = CLICK_OFFSET; } else { return(null); } x = oper.getWidth() - ((ScrollPaneOperator)oper).getVScrollbarWidth() / 2; } else { return(null); } return(new Point(x, y)); } } Jemmy2/src/org/netbeans/jemmy/FrameWaiter.java0000644000175000017500000004363411064436407020353 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.awt.Component; import java.awt.Frame; /** * * Contains methods to search and wait Frame. * A FrameWaiter is a utility class used to look or wait for Frames. * It contains methods to search for a Frame among the currently * showing Frames as well as methods that wait for a Frame to show * within an allotted time period. * *

Timeouts used:
* FrameWaiter.WaitFrameTimeout - time to wait frame displayed.
* FrameWaiter.AfterFrameTimeout - time to sleep after frame has been displayed.
* * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class FrameWaiter extends WindowWaiter implements Timeoutable, Outputable { private final static long WAIT_TIME = 60000; private final static long AFTER_WAIT_TIME = 0; private Timeouts timeouts; private TestOut output; /** * Constructor. */ public FrameWaiter() { super(); setTimeouts(JemmyProperties.getProperties().getTimeouts()); setOutput(JemmyProperties.getProperties().getOutput()); } /** * Searches for a Frame. * Search among the currently showing Frames for one that meets the search * criteria applied by the ComponentChooser parameter. * @param cc A component chooser used to define and apply the search criteria. * @return a reference to the first Frame that is showing and that * meets the search criteria. If no such Frame can be found, a * null reference is returned. */ public static Frame getFrame(ComponentChooser cc) { return((Frame)WindowWaiter.getWindow(new FrameSubChooser(cc))); } /** * Searches for a Frame. * The search proceeds among the currently showing Frames for the * index+1'th Frame that meets the criteria defined and * applied by the ComonentChooser parameter. * @param cc A component chooser used to define and apply the search criteria. * @param index The ordinal index of the Frame in the set of currently displayed * Frames. The first index is 0. * @return a reference to the index+1'th Frame that is showing * and that meets the search criteria. If there are fewer than * index+1 Frames, a null reference is returned. */ public static Frame getFrame(ComponentChooser cc, int index) { return((Frame)WindowWaiter.getWindow(new FrameSubChooser(cc), index)); } /** * Searches for a Frame by title. * The search proceeds among the currently showing Frames for the first * with a suitable title. * @param title Frame title or subtitle. * @param ce If true and the search is case sensitive, then a * match occurs when the title argument is a substring of a * Frame title. If false and the search is case sensitive, * then the title argument and the Frame title must be the same. * If true and the search is case insensitive, then a match occurs * when the title argument is a substring of the Frame title after * changing both to upper case. If false and the search is case * insensitive, then a match occurs when the title argument is a * substring of the Frame title after changing both to upper case. * @param cc If true the search is case sensitive; otherwise, the * search is case insensitive. * @return a reference to the first Frame that is showing and that has a * suitable title. If no such Frame can be found, a null * reference is returned. */ public static Frame getFrame(String title, boolean ce, boolean cc) { return((Frame)WindowWaiter.getWindow(new FrameByTitleChooser(title, ce, cc))); } /** * Searches for a Frame by title. * The search is for the index+1'th Frame among the currently * showing Frames that possess a suitable title. * * @param title Frame title or subtitle. * @param ce If true and the search is case sensitive, then a * match occurs when the title argument is a substring of a * Frame title. If false and the search is case sensitive, * then the title argument and the Frame title must be the same. * If true and the search is case insensitive, then a match occurs * when the title argument is a substring of the Frame title after * changing both to upper case. If false and the search is case * insensitive, then a match occurs when the title argument is a * substring of the Frame title after changing both to upper case. * @param cc If true the search is case sensitive; otherwise, the * search is case insensitive. * @param index The ordinal index of the Frame in the set of currently displayed * Frames. The first index is 0. * @return a reference to the index+1'th Frame that is showing * and that has a suitable title. If there are fewer than * index+1 Frames, a null reference is returned. */ public static Frame getFrame(String title, boolean ce, boolean cc, int index) { return((Frame)WindowWaiter.getWindow(new FrameByTitleChooser(title, ce, cc), index)); } static { Timeouts.initDefault("FrameWaiter.WaitFrameTimeout", WAIT_TIME); Timeouts.initDefault("FrameWaiter.AfterFrameTimeout", AFTER_WAIT_TIME); } /** * Defines current timeouts. * @param timeouts A collection of timeout assignments. * @see org.netbeans.jemmy.Timeoutable * @see org.netbeans.jemmy.Timeouts * @see #getTimeouts */ public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; Timeouts times = timeouts.cloneThis(); times.setTimeout("WindowWaiter.WaitWindowTimeout", timeouts.getTimeout("FrameWaiter.WaitFrameTimeout")); times.setTimeout("WindowWaiter.AfterWindowTimeout", timeouts.getTimeout("FrameWaiter.AfterFrameTimeout")); super.setTimeouts(times); } /** * Return current timeouts. * @return the collection of current timeout assignments. * @see org.netbeans.jemmy.Timeoutable * @see org.netbeans.jemmy.Timeouts * @see #setTimeouts */ public Timeouts getTimeouts() { return(timeouts); } /** * Defines print output streams or writers. * @param output Identify the streams or writers used for print output. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #getOutput */ public void setOutput(TestOut output) { this.output = output; super.setOutput(output); } /** * Returns print output streams or writers. * @return an object that contains references to objects for * printing to output and err streams. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #setOutput */ public TestOut getOutput() { return(output); } /** * Waits for a Frame to show. * Wait for the index+1'th Frame that meets the criteria * defined and applied by the ComonentChooser parameter to * show up. * * @param ch A component chooser used to define and apply the search criteria. * @param index The ordinal index of the Frame in the set of currently displayed * Frames. The first index is 0. * @return a reference to the index+1'th Frame that shows * and that meets the search criteria. If fewer than * index+1 Frames show up in the allotted time period then * a null reference is returned. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.WindowWaiter#actionProduced(Object) * @exception InterruptedException */ public Frame waitFrame(ComponentChooser ch, int index) throws InterruptedException { setTimeouts(timeouts); return((Frame)waitWindow(new FrameSubChooser(ch), index)); } /** * Waits for a Frame to show. * Wait for a Frame that meets the search criteria applied by the * ComponentChooser parameter to show up. * * @param ch A component chooser used to define and apply the search criteria. * @return a reference to the first Frame that shows and that * meets the search criteria. If no such Frame can be found within the * time period allotted, a null reference is returned. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.WindowWaiter#actionProduced(Object) * @exception InterruptedException */ public Frame waitFrame(ComponentChooser ch) throws InterruptedException { return(waitFrame(ch, 0)); } /** * Waits for a Frame to show. * Wait for the index+1'th Frame to show with a suitable title. * * @param title Frame title or subtitle. * @param compareExactly If true and the search is case sensitive, then a * match occurs when the title argument is a substring of a * Frame title. If false and the search is case sensitive, * then the title argument and the Frame title must be the same. * If true and the search is case insensitive, then a match occurs * when the title argument is a substring of the Frame title after * changing both to upper case. If false and the search is case * insensitive, then a match occurs when the title argument is a * substring of the Frame title after changing both to upper case. * @param compareCaseSensitive If true the search is case sensitive; * otherwise, the search is case insensitive. * @param index The ordinal index of the Frame in the set of currently displayed * Frames with the proper window ownership and a suitable title. The * first index is 0. * @return a reference to the index+1'th Frame to show and that has a * suitable title. If no such Frame can be found within the time period * allotted, a null reference is returned. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.WindowWaiter#actionProduced(Object) * @exception InterruptedException */ public Frame waitFrame(String title, boolean compareExactly, boolean compareCaseSensitive, int index) throws InterruptedException { return(waitFrame(new FrameByTitleChooser(title, compareExactly, compareCaseSensitive), index)); } /** * Waits for a Frame to show. * Wait for the first Frame to show with a suitable title. * * @param title Frame title or subtitle. * @param compareExactly If true and the search is case sensitive, then a * match occurs when the title argument is a substring of a * Frame title. If false and the search is case sensitive, * then the title argument and the Frame title must be the same. * If true and the search is case insensitive, then a match occurs * when the title argument is a substring of the Frame title after * changing both to upper case. If false and the search is case * insensitive, then a match occurs when the title argument is a * substring of the Frame title after changing both to upper case. * @param compareCaseSensitive If true the search is case sensitive; * otherwise, the search is case insensitive. * @return a reference to the first Frame to show and that has a * suitable title. If no such Frame can be found within the time period * allotted, a null reference is returned. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.WindowWaiter#actionProduced(Object) * @exception InterruptedException */ public Frame waitFrame(String title, boolean compareExactly, boolean compareCaseSensitive) throws InterruptedException { return(waitFrame(title, compareExactly, compareCaseSensitive, 0)); } /** * @see Waiter#getWaitingStartedMessage() */ protected String getWaitingStartedMessage() { return("Start to wait frame \"" + getComponentChooser().getDescription() + "\" opened"); } /** * Overrides WindowWaiter.getTimeoutExpiredMessage. * Returns the timeout expired message value. * @param timeSpent Time spent for waiting * @return a message tring * @see Waiter#getTimeoutExpiredMessage(long) */ protected String getTimeoutExpiredMessage(long timeSpent) { return("Frame \"" + getComponentChooser().getDescription() + "\" has not been opened in " + (new Long(timeSpent)).toString() + " milliseconds"); } /** * Overrides WindowWaiter.getActionProducedMessage. * Returns the action produced message value. * @param timeSpent Time spent for waiting. * @param result A message string. * @return a message tring * @see Waiter#getActionProducedMessage(long, Object) */ protected String getActionProducedMessage(long timeSpent, final Object result) { String resultToString = null; if(result instanceof Component) { // run toString in dispatch thread resultToString = (String)new QueueTool().invokeSmoothly( new QueueTool.QueueAction("result.toString()") { public Object launch() { return result.toString(); } } ); } else { resultToString = result.toString(); } return("Frame \"" + getComponentChooser().getDescription() + "\" has been opened in " + (new Long(timeSpent)).toString() + " milliseconds" + "\n " + resultToString); } /** * @see Waiter#getGoldenWaitingStartedMessage() */ protected String getGoldenWaitingStartedMessage() { return("Start to wait frame \"" + getComponentChooser().getDescription() + "\" opened"); } /** * @see Waiter#getGoldenTimeoutExpiredMessage() */ protected String getGoldenTimeoutExpiredMessage() { return("Frame \"" + getComponentChooser().getDescription() + "\" has not been opened"); } /** * @see Waiter#getGoldenActionProducedMessage() */ protected String getGoldenActionProducedMessage() { return("Frame \"" + getComponentChooser().getDescription() + "\" has been opened"); } private static class FrameSubChooser implements ComponentChooser { private ComponentChooser chooser; public FrameSubChooser(ComponentChooser c) { super(); chooser = c; } public boolean checkComponent(Component comp) { if(comp instanceof Frame) { return(comp.isShowing() && comp.isVisible() && chooser.checkComponent(comp)); } else { return(false); } } public String getDescription() { return(chooser.getDescription()); } } private static class FrameByTitleChooser implements ComponentChooser { String title; boolean compareExactly; boolean compareCaseSensitive; public FrameByTitleChooser(String t, boolean ce, boolean cc) { super(); title = t; compareExactly = ce; compareCaseSensitive = cc; } public boolean checkComponent(Component comp) { if(comp instanceof Frame) { if(((Frame)comp).isShowing() && comp.isVisible() && ((Frame)comp).getTitle() != null) { String titleToComp = ((Frame)comp).getTitle(); String contextToComp = title; if(compareCaseSensitive) { titleToComp = titleToComp.toUpperCase(); contextToComp = contextToComp.toUpperCase(); } if(compareExactly) { return(titleToComp.equals(contextToComp)); } else { return(titleToComp.indexOf(contextToComp) != -1); } } } return(false); } public String getDescription() { return(title); } } } Jemmy2/src/org/netbeans/jemmy/ComponentChooser.java0000644000175000017500000000553611064436407021431 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.awt.Component; /** * * This interface should be implemented to define the criteria * used to search for a component. * @see org.netbeans.jemmy.ComponentSearcher * @see org.netbeans.jemmy.WindowWaiter * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface ComponentChooser { /** * Check if the component argument meets the search criteria. * @param comp Component to check. * @return true when the component conforms to * the search criteria; false otherwise. */ public boolean checkComponent(Component comp); /** * Returns searched component description. * @return a String representing the description value */ public String getDescription(); } Jemmy2/src/org/netbeans/jemmy/version_info0000644000175000017500000000022211446273577017722 0ustar tonytonyManifest-version: 1.0 Main-Class: org.netbeans.jemmy.JemmyProperties Jemmy-MajorVersion: 2.3 Jemmy-MinorVersion: 1.1 Jemmy-Build: @BUILD_NUMBER@ Jemmy2/src/org/netbeans/jemmy/DefaultCharBindingMap.java0000644000175000017500000002040511245712347022250 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Enumeration; import java.util.Hashtable; /** * * Default implementation of CharBindingMap interface. * Provides a mapping for the following symbols:
* @see org.netbeans.jemmy.CharBindingMap * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class DefaultCharBindingMap implements CharBindingMap { private Hashtable chars; /** * Constructor. */ public DefaultCharBindingMap() { initMap(); } /** * Returns the code of the primary key used to type a symbol. * @param c Symbol code. * @return a key code. * @see CharBindingMap#getCharKey(char) * @see java.awt.event.InputEvent */ public int getCharKey(char c) { return(getKeyAndModifiers(c)[0]); } /** * Returns the modifiers that should be pressed to type a symbol. * @param c Symbol code. * @return a combination of InputEvent MASK fields. * @see CharBindingMap#getCharModifiers(char) * @see java.awt.event.InputEvent */ public int getCharModifiers(char c) { return(getKeyAndModifiers(c)[1]); } /** * Returns key + modifiers pair. * @param c Symbol code. * @return an array of two elements: key code and modifiers mask - * a combination of InputEvent MASK fields. */ public int[] getKeyAndModifiers(char c) { CharKey key = (CharKey)chars.get(new Character(c)); if(key != null) { return(new int[] {key.key, key.modifiers}); } else { return(new int[] {KeyEvent.VK_UNDEFINED, 0}); } } /** * Returns an array of all supported chars. * @return an array of chars representing the supported chars values. */ public char[] getSupportedChars() { char[] charArray = new char[chars.size()]; Enumeration keys = chars.keys(); int index = 0; while(keys.hasMoreElements()) { charArray[index] = ((Character)keys.nextElement()).charValue(); } return(charArray); } /** * Removes a char from supported. * @param c Symbol code. */ public void removeChar(char c) { chars.remove(new Character(c)); } /** * Adds a char to supported. * @param c Symbol code. * @param key key code. * @param modifiers a combination of InputEvent MASK fields. */ public void addChar(char c, int key, int modifiers) { chars.put(new Character(c), new CharKey(key, modifiers)); } private void initMap() { chars = new Hashtable(); //first add latters and digits represented by KeyEvent.VK_. fields Field[] fields = KeyEvent.class.getFields(); for(int i = 0; i < fields.length; i++) { String name = fields[i].getName(); if((fields[i].getModifiers() & Modifier.PUBLIC) != 0 && (fields[i].getModifiers() & Modifier.STATIC) != 0 && fields[i].getType() == Integer.TYPE && name.startsWith("VK_") && name.length() == 4) { String latter = name.substring(3, 4); try { int key = fields[i].getInt(null); addChar(latter.toLowerCase().charAt(0), key, 0); if(!latter.toUpperCase().equals(latter.toLowerCase())) { addChar(latter.toUpperCase().charAt(0), key, InputEvent.SHIFT_MASK); } } catch(IllegalAccessException e) { //never could happen! } } } //add special simbols addChar('\t', KeyEvent.VK_TAB , 0); addChar(' ', KeyEvent.VK_SPACE , 0); addChar('!', KeyEvent.VK_1 , InputEvent.SHIFT_MASK); addChar('"', KeyEvent.VK_QUOTE , InputEvent.SHIFT_MASK); addChar('#', KeyEvent.VK_3 , InputEvent.SHIFT_MASK); addChar('$', KeyEvent.VK_4 , InputEvent.SHIFT_MASK); addChar('%', KeyEvent.VK_5 , InputEvent.SHIFT_MASK); addChar('&', KeyEvent.VK_7 , InputEvent.SHIFT_MASK); addChar('\'', KeyEvent.VK_QUOTE , 0); addChar('(', KeyEvent.VK_9 , InputEvent.SHIFT_MASK); addChar(')', KeyEvent.VK_0 , InputEvent.SHIFT_MASK); addChar('*', KeyEvent.VK_8 , InputEvent.SHIFT_MASK); addChar('+', KeyEvent.VK_EQUALS , InputEvent.SHIFT_MASK); addChar(',', KeyEvent.VK_COMMA , 0); addChar('-', KeyEvent.VK_MINUS , 0); addChar('.', KeyEvent.VK_PERIOD , 0); addChar('/', KeyEvent.VK_SLASH , 0); addChar(':', KeyEvent.VK_SEMICOLON , InputEvent.SHIFT_MASK); addChar(';', KeyEvent.VK_SEMICOLON , 0); addChar('<', KeyEvent.VK_COMMA , InputEvent.SHIFT_MASK); addChar('=', KeyEvent.VK_EQUALS , 0); addChar('>', KeyEvent.VK_PERIOD , InputEvent.SHIFT_MASK); addChar('?', KeyEvent.VK_SLASH , InputEvent.SHIFT_MASK); addChar('@', KeyEvent.VK_2 , InputEvent.SHIFT_MASK); addChar('[', KeyEvent.VK_OPEN_BRACKET , 0); addChar('\\', KeyEvent.VK_BACK_SLASH , 0); addChar(']', KeyEvent.VK_CLOSE_BRACKET, 0); addChar('^', KeyEvent.VK_6 , InputEvent.SHIFT_MASK); addChar('_', KeyEvent.VK_MINUS , InputEvent.SHIFT_MASK); addChar('`', KeyEvent.VK_BACK_QUOTE , 0); addChar('{', KeyEvent.VK_OPEN_BRACKET , InputEvent.SHIFT_MASK); addChar('|', KeyEvent.VK_BACK_SLASH , InputEvent.SHIFT_MASK); addChar('}', KeyEvent.VK_CLOSE_BRACKET, InputEvent.SHIFT_MASK); addChar('~', KeyEvent.VK_BACK_QUOTE , InputEvent.SHIFT_MASK); addChar('\n', KeyEvent.VK_ENTER , 0); } private static class CharKey { public int key; public int modifiers; public CharKey(int key, int modifiers) { this.key = key; this.modifiers = modifiers; } } } Jemmy2/src/org/netbeans/jemmy/Waiter.java0000644000175000017500000002446711245712447017405 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.awt.Component; /** * * Waits for something defined by Waitable interface to be happened. * *

Timeouts used:
* Waiter.TimeDelta - time delta to check actionProduced result.
* Waiter.WaitingTime - maximal waiting time
* Waiter.AfterWaitingTime - time to sleep after waiting has been finished.
* * @see Timeouts * @see Waitable * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class Waiter implements Waitable, Timeoutable, Outputable{ private final static long TIME_DELTA = 10; private final static long WAIT_TIME = 60000; private final static long AFTER_WAIT_TIME = 0; private Waitable waitable; private long startTime = 0; private long endTime = -1; private Object result; private Timeouts timeouts; private String waitingTimeOrigin; private TestOut out; /** * Constructor. * @param w Waitable object defining waiting criteria. */ public Waiter(Waitable w) { super(); setTimeouts(JemmyProperties.getProperties().getTimeouts()); setOutput(JemmyProperties.getProperties().getOutput()); waitable = w; } /** * Can be used from subclass. */ protected Waiter() { super(); setTimeouts(JemmyProperties.getProperties().getTimeouts()); setOutput(JemmyProperties.getProperties().getOutput()); } static { Timeouts.initDefault("Waiter.TimeDelta", TIME_DELTA); Timeouts.initDefault("Waiter.WaitingTime", WAIT_TIME); Timeouts.initDefault("Waiter.AfterWaitingTime", AFTER_WAIT_TIME); } /** * Defines current timeouts. * * @param timeouts A collection of timeout assignments. * @see org.netbeans.jemmy.Timeoutable * @see org.netbeans.jemmy.Timeouts * @see #getTimeouts */ public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; } /** * Like {@link #setTimeouts(Timeouts)}, but clones the timeouts first, then * sets "Waiter.WaitingTime" to the timeout whose name is passed in. This * name is remembered for display in timeout error messages so people know * what to adjust. * @param timeouts to be cloned and in which to look up "useAsWaitingTime". * @param useAsWaitingTime the name of the timeout to apply to "Waiter.WaitingTime". * @return the cloned timeouts. */ public Timeouts setTimeoutsToCloneOf(Timeouts timeouts, String useAsWaitingTime) { Timeouts t = timeouts.cloneThis(); t.setTimeout("Waiter.WaitingTime", t.getTimeout(useAsWaitingTime)); setTimeouts(t); setWaitingTimeOrigin(useAsWaitingTime); return t; } /** * Sets the origin of the current "Waiter.WaitingTime" to be shown in timeout * error messages * @param origin is the name of the origin. */ public void setWaitingTimeOrigin(String origin) { waitingTimeOrigin = origin; } /** * Return current timeouts. * @return the collection of current timeout assignments. * @see org.netbeans.jemmy.Timeoutable * @see org.netbeans.jemmy.Timeouts * @see #setTimeouts */ public Timeouts getTimeouts() { return(timeouts); } /** * Defines print output streams or writers. * @param out Identify the streams or writers used for print output. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #getOutput */ public void setOutput(TestOut out) { this.out = out; } /** * Returns print output streams or writers. * @return an object that contains references to objects for * printing to output and err streams. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #setOutput */ public TestOut getOutput() { return(out); } /** * Waits for not null result of actionProduced method of Waitable implementation passed into constructor. * @param waitableObject Object to be passed into actionProduced method. * @return non null result of action. * @throws TimeoutExpiredException * @exception InterruptedException */ public Object waitAction(Object waitableObject) throws InterruptedException { startTime = System.currentTimeMillis(); out.printTrace(getWaitingStartedMessage()); out.printGolden(getGoldenWaitingStartedMessage()); long timeDelta = timeouts.getTimeout("Waiter.TimeDelta"); while((result = checkActionProduced(waitableObject)) == null) { Thread.currentThread().sleep(timeDelta); if(timeoutExpired()) { out.printError(getTimeoutExpiredMessage(timeFromStart())); out.printGolden(getGoldenTimeoutExpiredMessage()); throw(new TimeoutExpiredException(getActualDescription())); } } endTime = System.currentTimeMillis(); out.printTrace(getActionProducedMessage(endTime - startTime, result)); out.printGolden(getGoldenActionProducedMessage()); Thread.currentThread().sleep(timeouts.getTimeout("Waiter.AfterWaitingTime")); return(result); } /** * @see Waitable * @param obj */ public Object actionProduced(Object obj) { return(Boolean.TRUE); } /** * @see Waitable */ public String getDescription() { return("Unknown waiting"); } /** * Returns message to be printed before waiting start. * @return a message. */ protected String getWaitingStartedMessage() { return("Start to wait action \"" + getActualDescription() + "\""); } /** * Returns message to be printed when waiting timeout has been expired. * @param timeSpent time from waiting start (milliseconds) * @return a message. */ protected String getTimeoutExpiredMessage(long timeSpent) { return("\"" + getActualDescription() + "\" action has not been produced in " + (new Long(timeSpent)).toString() + " milliseconds"); } /** * Returns message to be printed when waiting has been successfully finished. * @param timeSpent time from waiting start (milliseconds) * @param result result of Waitable.actionproduced method. * @return a message. */ protected String getActionProducedMessage(long timeSpent, final Object result) { String resultToString; if(result instanceof Component) { // run toString in dispatch thread resultToString = (String)new QueueTool().invokeSmoothly( new QueueTool.QueueAction("result.toString()") { public Object launch() { return result.toString(); } } ); } else { resultToString = result.toString(); } return("\"" + getActualDescription() + "\" action has been produced in " + (new Long(timeSpent)).toString() + " milliseconds with result " + "\n : " + resultToString); } /** * Returns message to be printed int golden output before waiting start. * @return a message. */ protected String getGoldenWaitingStartedMessage() { return("Start to wait action \"" + getActualDescription() + "\""); } /** * Returns message to be printed int golden output when waiting timeout has been expired. * @return a message. */ protected String getGoldenTimeoutExpiredMessage() { return("\"" + getActualDescription() + "\" action has not been produced"); } /** * Returns message to be printed int golden output when waiting has been successfully finished. * @return a message. */ protected String getGoldenActionProducedMessage() { return("\"" + getActualDescription() + "\" action has been produced"); } /** * Returns time from waiting start. * @return Time spent for waiting already. */ protected long timeFromStart() { return(System.currentTimeMillis() - startTime); } private Object checkActionProduced(Object obj) { if(waitable != null) { return(waitable.actionProduced(obj)); } else { return(actionProduced(obj)); } } private String getActualDescription() { final String suffix = (null == waitingTimeOrigin)? "" : " (" + waitingTimeOrigin + ")"; if(waitable != null) { return(waitable.getDescription() + suffix); } else { return(getDescription() + suffix); } } private boolean timeoutExpired() { return(timeFromStart() > timeouts.getTimeout("Waiter.WaitingTime")); } } Jemmy2/src/org/netbeans/jemmy/CharBindingMap.java0000644000175000017500000000575311064436407020753 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; /** * * Defines char-to-key binding. The generation of a symbol will, * in general, require modifier keys to be pressed prior to pressing * a primary key. Classes that implement CharBindingMap * communicate what modifiers and primary key are required to generate * a given symbol. * @see org.netbeans.jemmy.DefaultCharBindingMap * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface CharBindingMap { /** * Returns the code of the primary key used to type a symbol. * @param c Symbol code. * @return a key code. * @see java.awt.event.InputEvent */ public int getCharKey(char c); /** * Returns the modifiers that should be pressed to type a symbol. * @param c Symbol code. * @return a combination of InputEvent MASK fields. * @see java.awt.event.InputEvent */ public int getCharModifiers(char c); } Jemmy2/src/org/netbeans/jemmy/operators/0000755000175000017500000000000011572745223017311 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/operators/TextAreaOperator.java0000644000175000017500000003653111245712237023411 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.TextArea; import java.util.Hashtable; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; /** * This operator type covers java.awt.textArea component. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class TextAreaOperator extends TextComponentOperator implements Timeoutable, Outputable { /** * Identifier for a "text" property. * @see #getDump */ public static final String TEXT_DPROP = "Text"; private final static long PUSH_KEY_TIMEOUT = 0; private final static long BETWEEN_KEYS_TIMEOUT = 0; private final static long CHANGE_CARET_POSITION_TIMEOUT = 60000; private final static long TYPE_TEXT_TIMEOUT = 60000; private Timeouts timeouts; private TestOut output; /** * Constructor. * @param b The java.awt.TextArea managed by * this instance. */ public TextAreaOperator(TextArea b) { super(b); } /** * Constructs a TextAreaOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public TextAreaOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((TextArea)cont. waitSubComponent(new TextAreaFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a TextAreaOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public TextAreaOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits for a component in a container to show. The component is * identified as the index+1'th * java.awt.TextArea that shows, lies below * the container in the display containment hierarchy, * and that has the desired text. Uses cont's timeout and output * for waiting and to init this operator. * @param cont The operator for a container containing the sought for textArea. * @param text TextArea text. * @param index Ordinal component index. The first component has index 0. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public TextAreaOperator(ContainerOperator cont, String text, int index) { this((TextArea)waitComponent(cont, new TextAreaByTextFinder(text, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits for a component in a container to show. The component is * identified as the first * java.awt.TextArea that shows, lies below * the container in the display containment hierarchy, * and that has the desired text. Uses cont's timeout and output * for waiting and to init this operator. * @param cont The operator for a container containing the sought for textArea. * @param text TextArea text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public TextAreaOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont The operator for a container containing the sought for textArea. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public TextAreaOperator(ContainerOperator cont, int index) { this((TextArea) waitComponent(cont, new TextAreaFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont The operator for a container containing the sought for textArea. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public TextAreaOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches TextArea in a container. * @param cont Container in which to search for the component. The container * lies above the component in the display containment hierarchy. The containment * need not be direct. * @param chooser org.netbeans.jemmy.ComponentChooser implementation, defining and * applying search criteria. * @param index Ordinal component index. The first index is 0. * @return TextArea instance or null if component was not found. */ public static TextArea findTextArea(Container cont, ComponentChooser chooser, int index) { return((TextArea)findComponent(cont, new TextAreaFinder(chooser), index)); } /** * Searches for the first TextArea in a container. * @param cont Container in which to search for the component. The container * lies above the component in the display containment hierarchy. The containment * need not be direct. * @param chooser org.netbeans.jemmy.ComponentChooser implementation, defining and * applying search criteria. * @return TextArea instance or null if component was not found. */ public static TextArea findTextArea(Container cont, ComponentChooser chooser) { return(findTextArea(cont, chooser, 0)); } /** * Searches TextArea by text. * @param cont Container to search component in. * @param text TextArea text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return TextArea instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static TextArea findTextArea(Container cont, String text, boolean ce, boolean ccs, int index) { return(findTextArea(cont, new TextAreaByTextFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches TextArea by text. * @param cont Container to search component in. * @param text TextArea text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return TextArea instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static TextArea findTextArea(Container cont, String text, boolean ce, boolean ccs) { return(findTextArea(cont, text, ce, ccs, 0)); } /** * Waits TextArea in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return TextArea instance. */ public static TextArea waitTextArea(Container cont, ComponentChooser chooser, int index) { return((TextArea)waitComponent(cont, new TextAreaFinder(chooser), index)); } /** * Waits 0'th TextArea in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return TextArea instance. */ public static TextArea waitTextArea(Container cont, ComponentChooser chooser){ return(waitTextArea(cont, chooser, 0)); } /** * Waits TextArea by text. * @param cont Container to search component in. * @param text TextArea text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return TextArea instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static TextArea waitTextArea(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitTextArea(cont, new TextAreaByTextFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits TextArea by text. * @param cont Container to search component in. * @param text TextArea text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return TextArea instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static TextArea waitTextArea(Container cont, String text, boolean ce, boolean ccs) { return(waitTextArea(cont, text, ce, ccs, 0)); } static { Timeouts.initDefault("TextAreaOperator.PushKeyTimeout", PUSH_KEY_TIMEOUT); Timeouts.initDefault("TextAreaOperator.BetweenKeysTimeout", BETWEEN_KEYS_TIMEOUT); Timeouts.initDefault("TextAreaOperator.ChangeCaretPositionTimeout", CHANGE_CARET_POSITION_TIMEOUT); Timeouts.initDefault("TextAreaOperator.TypeTextTimeout", TYPE_TEXT_TIMEOUT); } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public Hashtable getDump() { Hashtable result = super.getDump(); result.put(TEXT_DPROP, ((TextArea)getSource()).getText()); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps TextArea.getColumns() through queue*/ public int getColumns() { return(runMapping(new MapIntegerAction("getColumns") { public int map() { return(((TextArea)getSource()).getColumns()); }}));} /**Maps TextArea.getMinimumSize(int, int) through queue*/ public Dimension getMinimumSize(final int i, final int i1) { return((Dimension)runMapping(new MapAction("getMinimumSize") { public Object map() { return(((TextArea)getSource()).getMinimumSize(i, i1)); }}));} /**Maps TextArea.getPreferredSize(int, int) through queue*/ public Dimension getPreferredSize(final int i, final int i1) { return((Dimension)runMapping(new MapAction("getPreferredSize") { public Object map() { return(((TextArea)getSource()).getPreferredSize(i, i1)); }}));} /**Maps TextArea.getRows() through queue*/ public int getRows() { return(runMapping(new MapIntegerAction("getRows") { public int map() { return(((TextArea)getSource()).getRows()); }}));} /**Maps TextArea.getScrollbarVisibility() through queue*/ public int getScrollbarVisibility() { return(runMapping(new MapIntegerAction("getScrollbarVisibility") { public int map() { return(((TextArea)getSource()).getScrollbarVisibility()); }}));} /**Maps TextArea.replaceRange(String, int, int) through queue*/ public void replaceRange(final String string, final int i, final int i1) { runMapping(new MapVoidAction("replaceRange") { public void map() { ((TextArea)getSource()).replaceRange(string, i, i1); }});} /**Maps TextArea.setColumns(int) through queue*/ public void setColumns(final int i) { runMapping(new MapVoidAction("setColumns") { public void map() { ((TextArea)getSource()).setColumns(i); }});} /**Maps TextArea.setRows(int) through queue*/ public void setRows(final int i) { runMapping(new MapVoidAction("setRows") { public void map() { ((TextArea)getSource()).setRows(i); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Allows to find component by text. */ public static class TextAreaByTextFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs TextAreaByTextFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public TextAreaByTextFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs TextAreaByTextFinder. * @param lb a text pattern */ public TextAreaByTextFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof TextArea) { if(((TextArea)comp).getText() != null) { return(comparator.equals(((TextArea)comp).getText(), label)); } } return(false); } public String getDescription() { return("TextArea with text \"" + label + "\""); } } /** * Checks component type. */ public static class TextAreaFinder extends Finder { /** * Constructs TextAreaFinder. * @param sf other searching criteria. */ public TextAreaFinder(ComponentChooser sf) { super(TextArea.class, sf); } /** * Constructs TextAreaFinder. */ public TextAreaFinder() { super(TextArea.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/AbstractButtonOperator.java0000644000175000017500000010130711245712237024625 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Insets; import java.awt.event.ActionListener; import java.awt.event.ItemListener; import java.util.Hashtable; import javax.swing.AbstractButton; import javax.swing.ButtonModel; import javax.swing.Icon; import javax.swing.event.ChangeListener; import javax.swing.plaf.ButtonUI; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.ButtonDriver; import org.netbeans.jemmy.drivers.DriverManager; /** * *

Timeouts used:
* AbstractButtonOperator.PushButtonTimeout - time between button pressing and releasing
* ComponentOperator.WaitComponentTimeout - time to wait button displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait button enabled
* ComponentOperator.WaitStateTimeout - time to wait for text
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class AbstractButtonOperator extends JComponentOperator implements Timeoutable, Outputable{ /** * Identifier for a text property. * @see #getDump */ public static final String TEXT_DPROP = "Text"; /** * Identifier for a selected text property. * @see #getDump */ public static final String IS_SELECTED_DPROP = "Selected"; /** * Default value for AbstractButtonOperator.PushButtonTimeout timeout. */ private final static long PUSH_BUTTON_TIMEOUT = 0; private Timeouts timeouts; private TestOut output; ButtonDriver driver; /** * Constructor. * @param b The java.awt.AbstractButton managed by * this instance. */ public AbstractButtonOperator(AbstractButton b) { super(b); driver = DriverManager.getButtonDriver(getClass()); } /** * Constructs an AbstractButtonOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public AbstractButtonOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((AbstractButton)cont. waitSubComponent(new AbstractButtonFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs an AbstractButtonOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. */ public AbstractButtonOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits for a component in a container to show. The component is * identified as the index+1'th * javax.swing.AbstractButton that shows, lies below * the container in the display containment hierarchy, * and that has the desired text. Uses cont's timeout and output * for waiting and to init this operator. * @param cont The operator for a container containing the sought for button. * @param text Button text. * @param index Ordinal component index. The first component has index 0. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public AbstractButtonOperator(ContainerOperator cont, String text, int index) { this((AbstractButton)waitComponent(cont, new AbstractButtonByLabelFinder(text, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits for a component in a container to show. The component is * identified as the first * javax.swing.AbstractButton that shows, lies below * the container in the display containment hierarchy, * and that has the desired text. Uses cont's timeout and output * for waiting and to init this operator. * @param cont The operator for a container containing the sought for button. * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public AbstractButtonOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont The operator for a container containing the sought for button. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public AbstractButtonOperator(ContainerOperator cont, int index) { this((AbstractButton) waitComponent(cont, new AbstractButtonFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont The operator for a container containing the sought for button. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public AbstractButtonOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches AbstractButton in a container. * @param cont Container in which to search for the component. The container * lies above the component in the display containment hierarchy. The containment * need not be direct. * @param chooser org.netbeans.jemmy.ComponentChooser implementation, defining and * applying search criteria. * @param index Ordinal component index. The first index is 0. * @return AbstractButton instance or null if component was not found. */ public static AbstractButton findAbstractButton(Container cont, ComponentChooser chooser, int index) { return((AbstractButton)findComponent(cont, new AbstractButtonFinder(chooser), index)); } /** * Searches for the first AbstractButton in a container. * @param cont Container in which to search for the component. The container * lies above the component in the display containment hierarchy. The containment * need not be direct. * @param chooser org.netbeans.jemmy.ComponentChooser implementation, defining and * applying search criteria. * @return AbstractButton instance or null if component was not found. */ public static AbstractButton findAbstractButton(Container cont, ComponentChooser chooser) { return(findAbstractButton(cont, chooser, 0)); } /** * Searches AbstractButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return AbstractButton instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static AbstractButton findAbstractButton(Container cont, String text, boolean ce, boolean ccs, int index) { return(findAbstractButton(cont, new AbstractButtonByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches AbstractButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return AbstractButton instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static AbstractButton findAbstractButton(Container cont, String text, boolean ce, boolean ccs) { return(findAbstractButton(cont, text, ce, ccs, 0)); } /** * Waits AbstractButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return AbstractButton instance. * @throws TimeoutExpiredException */ public static AbstractButton waitAbstractButton(Container cont, ComponentChooser chooser, int index) { return((AbstractButton)waitComponent(cont, new AbstractButtonFinder(chooser), index)); } /** * Waits 0'th AbstractButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return AbstractButton instance. * @throws TimeoutExpiredException */ public static AbstractButton waitAbstractButton(Container cont, ComponentChooser chooser){ return(waitAbstractButton(cont, chooser, 0)); } /** * Waits AbstractButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return AbstractButton instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static AbstractButton waitAbstractButton(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitAbstractButton(cont, new AbstractButtonByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits AbstractButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return AbstractButton instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static AbstractButton waitAbstractButton(Container cont, String text, boolean ce, boolean ccs) { return(waitAbstractButton(cont, text, ce, ccs, 0)); } static { Timeouts.initDefault("AbstractButtonOperator.PushButtonTimeout", PUSH_BUTTON_TIMEOUT); } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = DriverManager.getButtonDriver(this); } /** * Pushs the button using a ButtonDriver registered for this operator. */ public void push() { output.printLine("Push button\n :" + toStringSource()); output.printGolden("Push button"); makeComponentVisible(); try { waitComponentEnabled(); } catch(InterruptedException e) { throw(new JemmyException("Interrupted", e)); } driver.push(this); } /** * Runs push() method in a separate thread. */ public void pushNoBlock() { produceNoBlocking(new NoBlockingAction("Button pushing") { public Object doAction(Object param) { push(); return(null); } }); } /** * Changes selection if necessary. * Uses push() method in order to do so. * @param selected a button selection. */ public void changeSelection(boolean selected) { if(isSelected() != selected) { push(); } if(getVerification()) { waitSelected(selected); } } /** * Runs changeSelection(boolean) method in a separate thread. * @param selected a button selection. */ public void changeSelectionNoBlock(boolean selected) { produceNoBlocking(new NoBlockingAction("Button selection changing") { public Object doAction(Object param) { changeSelection(((Boolean)param).booleanValue()); return(null); } }, selected ? Boolean.TRUE : Boolean.FALSE); } /** * Press the button by mouse. * @throws TimeoutExpiredException */ public void press() { output.printLine("Press button\n :" + toStringSource()); output.printGolden("Press button"); makeComponentVisible(); try { waitComponentEnabled(); } catch(InterruptedException e) { throw(new JemmyException("Interrupted", e)); } driver.press(this); } /** * Releases the button by mouse. * @throws TimeoutExpiredException */ public void release() { output.printLine("Release button\n :" + toStringSource()); output.printGolden("Release button"); try { waitComponentEnabled(); } catch(InterruptedException e) { throw(new JemmyException("Interrupted", e)); } driver.release(this); } /** * Waits for button to be selected. * @param selected a button selection. */ public void waitSelected(final boolean selected) { getOutput().printLine("Wait button to be selected \n : "+ toStringSource()); getOutput().printGolden("Wait button to be selected"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(isSelected() == selected); } public String getDescription() { return("Items has been " + (selected ? "" : "un") + "selected"); } }); } /** * Waits for text. Uses getComparator() comparator. * @param text Text to wait for. */ public void waitText(String text) { getOutput().printLine("Wait \"" + text + "\" text in component \n : "+ toStringSource()); getOutput().printGolden("Wait \"" + text + "\" text"); waitState(new AbstractButtonByLabelFinder(text, getComparator())); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); if(((AbstractButton)getSource()).getText() != null) { result.put(TEXT_DPROP, ((AbstractButton)getSource()).getText()); } result.put(IS_SELECTED_DPROP, ((AbstractButton)getSource()).isSelected() ? "true" : "false"); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps AbstractButton.addActionListener(ActionListener) through queue*/ public void addActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("addActionListener") { public void map() { ((AbstractButton)getSource()).addActionListener(actionListener); }});} /**Maps AbstractButton.addChangeListener(ChangeListener) through queue*/ public void addChangeListener(final ChangeListener changeListener) { runMapping(new MapVoidAction("addChangeListener") { public void map() { ((AbstractButton)getSource()).addChangeListener(changeListener); }});} /**Maps AbstractButton.addItemListener(ItemListener) through queue*/ public void addItemListener(final ItemListener itemListener) { runMapping(new MapVoidAction("addItemListener") { public void map() { ((AbstractButton)getSource()).addItemListener(itemListener); }});} /**Maps AbstractButton.doClick() through queue*/ public void doClick() { runMapping(new MapVoidAction("doClick") { public void map() { ((AbstractButton)getSource()).doClick(); }});} /**Maps AbstractButton.doClick(int) through queue*/ public void doClick(final int i) { runMapping(new MapVoidAction("doClick") { public void map() { ((AbstractButton)getSource()).doClick(i); }});} /**Maps AbstractButton.getActionCommand() through queue*/ public String getActionCommand() { return((String)runMapping(new MapAction("getActionCommand") { public Object map() { return(((AbstractButton)getSource()).getActionCommand()); }}));} /**Maps AbstractButton.getDisabledIcon() through queue*/ public Icon getDisabledIcon() { return((Icon)runMapping(new MapAction("getDisabledIcon") { public Object map() { return(((AbstractButton)getSource()).getDisabledIcon()); }}));} /**Maps AbstractButton.getDisabledSelectedIcon() through queue*/ public Icon getDisabledSelectedIcon() { return((Icon)runMapping(new MapAction("getDisabledSelectedIcon") { public Object map() { return(((AbstractButton)getSource()).getDisabledSelectedIcon()); }}));} /**Maps AbstractButton.getHorizontalAlignment() through queue*/ public int getHorizontalAlignment() { return(runMapping(new MapIntegerAction("getHorizontalAlignment") { public int map() { return(((AbstractButton)getSource()).getHorizontalAlignment()); }}));} /**Maps AbstractButton.getHorizontalTextPosition() through queue*/ public int getHorizontalTextPosition() { return(runMapping(new MapIntegerAction("getHorizontalTextPosition") { public int map() { return(((AbstractButton)getSource()).getHorizontalTextPosition()); }}));} /**Maps AbstractButton.getIcon() through queue*/ public Icon getIcon() { return((Icon)runMapping(new MapAction("getIcon") { public Object map() { return(((AbstractButton)getSource()).getIcon()); }}));} /**Maps AbstractButton.getMargin() through queue*/ public Insets getMargin() { return((Insets)runMapping(new MapAction("getMargin") { public Object map() { return(((AbstractButton)getSource()).getMargin()); }}));} /**Maps AbstractButton.getMnemonic() through queue*/ public int getMnemonic() { return(runMapping(new MapIntegerAction("getMnemonic") { public int map() { return(((AbstractButton)getSource()).getMnemonic()); }}));} /**Maps AbstractButton.getModel() through queue*/ public ButtonModel getModel() { return((ButtonModel)runMapping(new MapAction("getModel") { public Object map() { return(((AbstractButton)getSource()).getModel()); }}));} /**Maps AbstractButton.getPressedIcon() through queue*/ public Icon getPressedIcon() { return((Icon)runMapping(new MapAction("getPressedIcon") { public Object map() { return(((AbstractButton)getSource()).getPressedIcon()); }}));} /**Maps AbstractButton.getRolloverIcon() through queue*/ public Icon getRolloverIcon() { return((Icon)runMapping(new MapAction("getRolloverIcon") { public Object map() { return(((AbstractButton)getSource()).getRolloverIcon()); }}));} /**Maps AbstractButton.getRolloverSelectedIcon() through queue*/ public Icon getRolloverSelectedIcon() { return((Icon)runMapping(new MapAction("getRolloverSelectedIcon") { public Object map() { return(((AbstractButton)getSource()).getRolloverSelectedIcon()); }}));} /**Maps AbstractButton.getSelectedIcon() through queue*/ public Icon getSelectedIcon() { return((Icon)runMapping(new MapAction("getSelectedIcon") { public Object map() { return(((AbstractButton)getSource()).getSelectedIcon()); }}));} /**Maps AbstractButton.getSelectedObjects() through queue*/ public Object[] getSelectedObjects() { return((Object[])runMapping(new MapAction("getSelectedObjects") { public Object map() { return(((AbstractButton)getSource()).getSelectedObjects()); }}));} /**Maps AbstractButton.getText() through queue*/ public String getText() { return((String)runMapping(new MapAction("getText") { public Object map() { return(((AbstractButton)getSource()).getText()); }}));} /**Maps AbstractButton.getUI() through queue*/ public ButtonUI getUI() { return((ButtonUI)runMapping(new MapAction("getUI") { public Object map() { return(((AbstractButton)getSource()).getUI()); }}));} /**Maps AbstractButton.getVerticalAlignment() through queue*/ public int getVerticalAlignment() { return(runMapping(new MapIntegerAction("getVerticalAlignment") { public int map() { return(((AbstractButton)getSource()).getVerticalAlignment()); }}));} /**Maps AbstractButton.getVerticalTextPosition() through queue*/ public int getVerticalTextPosition() { return(runMapping(new MapIntegerAction("getVerticalTextPosition") { public int map() { return(((AbstractButton)getSource()).getVerticalTextPosition()); }}));} /**Maps AbstractButton.isBorderPainted() through queue*/ public boolean isBorderPainted() { return(runMapping(new MapBooleanAction("isBorderPainted") { public boolean map() { return(((AbstractButton)getSource()).isBorderPainted()); }}));} /**Maps AbstractButton.isContentAreaFilled() through queue*/ public boolean isContentAreaFilled() { return(runMapping(new MapBooleanAction("isContentAreaFilled") { public boolean map() { return(((AbstractButton)getSource()).isContentAreaFilled()); }}));} /**Maps AbstractButton.isFocusPainted() through queue*/ public boolean isFocusPainted() { return(runMapping(new MapBooleanAction("isFocusPainted") { public boolean map() { return(((AbstractButton)getSource()).isFocusPainted()); }}));} /**Maps AbstractButton.isRolloverEnabled() through queue*/ public boolean isRolloverEnabled() { return(runMapping(new MapBooleanAction("isRolloverEnabled") { public boolean map() { return(((AbstractButton)getSource()).isRolloverEnabled()); }}));} /**Maps AbstractButton.isSelected() through queue*/ public boolean isSelected() { return(runMapping(new MapBooleanAction("isSelected") { public boolean map() { return(((AbstractButton)getSource()).isSelected()); }}));} /**Maps AbstractButton.removeActionListener(ActionListener) through queue*/ public void removeActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("removeActionListener") { public void map() { ((AbstractButton)getSource()).removeActionListener(actionListener); }});} /**Maps AbstractButton.removeChangeListener(ChangeListener) through queue*/ public void removeChangeListener(final ChangeListener changeListener) { runMapping(new MapVoidAction("removeChangeListener") { public void map() { ((AbstractButton)getSource()).removeChangeListener(changeListener); }});} /**Maps AbstractButton.removeItemListener(ItemListener) through queue*/ public void removeItemListener(final ItemListener itemListener) { runMapping(new MapVoidAction("removeItemListener") { public void map() { ((AbstractButton)getSource()).removeItemListener(itemListener); }});} /**Maps AbstractButton.setActionCommand(String) through queue*/ public void setActionCommand(final String string) { runMapping(new MapVoidAction("setActionCommand") { public void map() { ((AbstractButton)getSource()).setActionCommand(string); }});} /**Maps AbstractButton.setBorderPainted(boolean) through queue*/ public void setBorderPainted(final boolean b) { runMapping(new MapVoidAction("setBorderPainted") { public void map() { ((AbstractButton)getSource()).setBorderPainted(b); }});} /**Maps AbstractButton.setContentAreaFilled(boolean) through queue*/ public void setContentAreaFilled(final boolean b) { runMapping(new MapVoidAction("setContentAreaFilled") { public void map() { ((AbstractButton)getSource()).setContentAreaFilled(b); }});} /**Maps AbstractButton.setDisabledIcon(Icon) through queue*/ public void setDisabledIcon(final Icon icon) { runMapping(new MapVoidAction("setDisabledIcon") { public void map() { ((AbstractButton)getSource()).setDisabledIcon(icon); }});} /**Maps AbstractButton.setDisabledSelectedIcon(Icon) through queue*/ public void setDisabledSelectedIcon(final Icon icon) { runMapping(new MapVoidAction("setDisabledSelectedIcon") { public void map() { ((AbstractButton)getSource()).setDisabledSelectedIcon(icon); }});} /**Maps AbstractButton.setFocusPainted(boolean) through queue*/ public void setFocusPainted(final boolean b) { runMapping(new MapVoidAction("setFocusPainted") { public void map() { ((AbstractButton)getSource()).setFocusPainted(b); }});} /**Maps AbstractButton.setHorizontalAlignment(int) through queue*/ public void setHorizontalAlignment(final int i) { runMapping(new MapVoidAction("setHorizontalAlignment") { public void map() { ((AbstractButton)getSource()).setHorizontalAlignment(i); }});} /**Maps AbstractButton.setHorizontalTextPosition(int) through queue*/ public void setHorizontalTextPosition(final int i) { runMapping(new MapVoidAction("setHorizontalTextPosition") { public void map() { ((AbstractButton)getSource()).setHorizontalTextPosition(i); }});} /**Maps AbstractButton.setIcon(Icon) through queue*/ public void setIcon(final Icon icon) { runMapping(new MapVoidAction("setIcon") { public void map() { ((AbstractButton)getSource()).setIcon(icon); }});} /**Maps AbstractButton.setMargin(Insets) through queue*/ public void setMargin(final Insets insets) { runMapping(new MapVoidAction("setMargin") { public void map() { ((AbstractButton)getSource()).setMargin(insets); }});} /**Maps AbstractButton.setMnemonic(char) through queue*/ public void setMnemonic(final char c) { runMapping(new MapVoidAction("setMnemonic") { public void map() { ((AbstractButton)getSource()).setMnemonic(c); }});} /**Maps AbstractButton.setMnemonic(int) through queue*/ public void setMnemonic(final int i) { runMapping(new MapVoidAction("setMnemonic") { public void map() { ((AbstractButton)getSource()).setMnemonic(i); }});} /**Maps AbstractButton.setModel(ButtonModel) through queue*/ public void setModel(final ButtonModel buttonModel) { runMapping(new MapVoidAction("setModel") { public void map() { ((AbstractButton)getSource()).setModel(buttonModel); }});} /**Maps AbstractButton.setPressedIcon(Icon) through queue*/ public void setPressedIcon(final Icon icon) { runMapping(new MapVoidAction("setPressedIcon") { public void map() { ((AbstractButton)getSource()).setPressedIcon(icon); }});} /**Maps AbstractButton.setRolloverEnabled(boolean) through queue*/ public void setRolloverEnabled(final boolean b) { runMapping(new MapVoidAction("setRolloverEnabled") { public void map() { ((AbstractButton)getSource()).setRolloverEnabled(b); }});} /**Maps AbstractButton.setRolloverIcon(Icon) through queue*/ public void setRolloverIcon(final Icon icon) { runMapping(new MapVoidAction("setRolloverIcon") { public void map() { ((AbstractButton)getSource()).setRolloverIcon(icon); }});} /**Maps AbstractButton.setRolloverSelectedIcon(Icon) through queue*/ public void setRolloverSelectedIcon(final Icon icon) { runMapping(new MapVoidAction("setRolloverSelectedIcon") { public void map() { ((AbstractButton)getSource()).setRolloverSelectedIcon(icon); }});} /**Maps AbstractButton.setSelected(boolean) through queue*/ public void setSelected(final boolean b) { runMapping(new MapVoidAction("setSelected") { public void map() { ((AbstractButton)getSource()).setSelected(b); }});} /**Maps AbstractButton.setSelectedIcon(Icon) through queue*/ public void setSelectedIcon(final Icon icon) { runMapping(new MapVoidAction("setSelectedIcon") { public void map() { ((AbstractButton)getSource()).setSelectedIcon(icon); }});} /**Maps AbstractButton.setText(String) through queue*/ public void setText(final String string) { runMapping(new MapVoidAction("setText") { public void map() { ((AbstractButton)getSource()).setText(string); }});} /**Maps AbstractButton.setUI(ButtonUI) through queue*/ public void setUI(final ButtonUI buttonUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((AbstractButton)getSource()).setUI(buttonUI); }});} /**Maps AbstractButton.setVerticalAlignment(int) through queue*/ public void setVerticalAlignment(final int i) { runMapping(new MapVoidAction("setVerticalAlignment") { public void map() { ((AbstractButton)getSource()).setVerticalAlignment(i); }});} /**Maps AbstractButton.setVerticalTextPosition(int) through queue*/ public void setVerticalTextPosition(final int i) { runMapping(new MapVoidAction("setVerticalTextPosition") { public void map() { ((AbstractButton)getSource()).setVerticalTextPosition(i); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Allows to find component by text. */ public static class AbstractButtonByLabelFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs AbstractButtonByLabelFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public AbstractButtonByLabelFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs AbstractButtonByLabelFinder. * @param lb a text pattern */ public AbstractButtonByLabelFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof AbstractButton) { if(((AbstractButton)comp).getText() != null) { return(comparator.equals(((AbstractButton)comp).getText(), label)); } } return(false); } public String getDescription() { return("AbstractButton with text \"" + label + "\""); } } /** * Checks component type. */ public static class AbstractButtonFinder extends Finder { /** * Constructs AbstractButtonFinder. * @param sf other searching criteria. */ public AbstractButtonFinder(ComponentChooser sf) { super(AbstractButton.class, sf); } /** * Constructs AbstractButtonFinder. */ public AbstractButtonFinder() { super(AbstractButton.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/TextFieldOperator.java0000644000175000017500000003705011245712237023561 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.TextField; import java.awt.event.ActionListener; import java.util.Hashtable; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; /** * * This operator type covers java.awt.TextField component. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class TextFieldOperator extends TextComponentOperator implements Timeoutable, Outputable { /** * Identifier for a "text" property. * @see #getDump */ public static final String TEXT_DPROP = "Text"; private final static long PUSH_KEY_TIMEOUT = 0; private final static long BETWEEN_KEYS_TIMEOUT = 0; private final static long CHANGE_CARET_POSITION_TIMEOUT = 60000; private final static long TYPE_TEXT_TIMEOUT = 60000; private Timeouts timeouts; private TestOut output; /** * Constructor. * @param b The java.awt.TextField managed by * this instance. */ public TextFieldOperator(TextField b) { super(b); } /** * Constructs a TextFieldOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public TextFieldOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((TextField)cont. waitSubComponent(new TextFieldFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a TextFieldOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public TextFieldOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits for a component in a container to show. The component is * identified as the index+1'th * java.awt.TextField that shows, lies below * the container in the display containment hierarchy, * and that has the desired text. Uses cont's timeout and output * for waiting and to init this operator. * @param cont The operator for a container containing the sought for textField. * @param text TextField text. * @param index Ordinal component index. The first component has index 0. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public TextFieldOperator(ContainerOperator cont, String text, int index) { this((TextField)waitComponent(cont, new TextFieldByTextFinder(text, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits for a component in a container to show. The component is * identified as the first * java.awt.TextField that shows, lies below * the container in the display containment hierarchy, * and that has the desired text. Uses cont's timeout and output * for waiting and to init this operator. * @param cont The operator for a container containing the sought for textField. * @param text TextField text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public TextFieldOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont The operator for a container containing the sought for textField. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public TextFieldOperator(ContainerOperator cont, int index) { this((TextField) waitComponent(cont, new TextFieldFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont The operator for a container containing the sought for textField. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public TextFieldOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches TextField in a container. * @param cont Container in which to search for the component. The container * lies above the component in the display containment hierarchy. The containment * need not be direct. * @param chooser org.netbeans.jemmy.ComponentChooser implementation, defining and * applying search criteria. * @param index Ordinal component index. The first index is 0. * @return TextField instance or null if component was not found. */ public static TextField findTextField(Container cont, ComponentChooser chooser, int index) { return((TextField)findComponent(cont, new TextFieldFinder(chooser), index)); } /** * Searches for the first TextField in a container. * @param cont Container in which to search for the component. The container * lies above the component in the display containment hierarchy. The containment * need not be direct. * @param chooser org.netbeans.jemmy.ComponentChooser implementation, defining and * applying search criteria. * @return TextField instance or null if component was not found. */ public static TextField findTextField(Container cont, ComponentChooser chooser) { return(findTextField(cont, chooser, 0)); } /** * Searches TextField by text. * @param cont Container to search component in. * @param text TextField text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return TextField instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static TextField findTextField(Container cont, String text, boolean ce, boolean ccs, int index) { return(findTextField(cont, new TextFieldByTextFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches TextField by text. * @param cont Container to search component in. * @param text TextField text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return TextField instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static TextField findTextField(Container cont, String text, boolean ce, boolean ccs) { return(findTextField(cont, text, ce, ccs, 0)); } /** * Waits TextField in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return TextField instance. */ public static TextField waitTextField(Container cont, ComponentChooser chooser, int index) { return((TextField)waitComponent(cont, new TextFieldFinder(chooser), index)); } /** * Waits 0'th TextField in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return TextField instance. */ public static TextField waitTextField(Container cont, ComponentChooser chooser){ return(waitTextField(cont, chooser, 0)); } /** * Waits TextField by text. * @param cont Container to search component in. * @param text TextField text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return TextField instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static TextField waitTextField(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitTextField(cont, new TextFieldByTextFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits TextField by text. * @param cont Container to search component in. * @param text TextField text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return TextField instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static TextField waitTextField(Container cont, String text, boolean ce, boolean ccs) { return(waitTextField(cont, text, ce, ccs, 0)); } static { Timeouts.initDefault("TextFieldOperator.PushKeyTimeout", PUSH_KEY_TIMEOUT); Timeouts.initDefault("TextFieldOperator.BetweenKeysTimeout", BETWEEN_KEYS_TIMEOUT); Timeouts.initDefault("TextFieldOperator.ChangeCaretPositionTimeout", CHANGE_CARET_POSITION_TIMEOUT); Timeouts.initDefault("TextFieldOperator.TypeTextTimeout", TYPE_TEXT_TIMEOUT); } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public Hashtable getDump() { Hashtable result = super.getDump(); result.put(TEXT_DPROP, ((TextField)getSource()).getText()); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps TextField.addActionListener(ActionListener) through queue*/ public void addActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("addActionListener") { public void map() { ((TextField)getSource()).addActionListener(actionListener); }});} /**Maps TextField.echoCharIsSet() through queue*/ public boolean echoCharIsSet() { return(runMapping(new MapBooleanAction("echoCharIsSet") { public boolean map() { return(((TextField)getSource()).echoCharIsSet()); }}));} /**Maps TextField.getColumns() through queue*/ public int getColumns() { return(runMapping(new MapIntegerAction("getColumns") { public int map() { return(((TextField)getSource()).getColumns()); }}));} /**Maps TextField.getEchoChar() through queue*/ public char getEchoChar() { return(runMapping(new MapCharacterAction("getEchoChar") { public char map() { return(((TextField)getSource()).getEchoChar()); }}));} /**Maps TextField.getMinimumSize(int) through queue*/ public Dimension getMinimumSize(final int i) { return((Dimension)runMapping(new MapAction("getMinimumSize") { public Object map() { return(((TextField)getSource()).getMinimumSize(i)); }}));} /**Maps TextField.getPreferredSize(int) through queue*/ public Dimension getPreferredSize(final int i) { return((Dimension)runMapping(new MapAction("getPreferredSize") { public Object map() { return(((TextField)getSource()).getPreferredSize(i)); }}));} /**Maps TextField.removeActionListener(ActionListener) through queue*/ public void removeActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("removeActionListener") { public void map() { ((TextField)getSource()).removeActionListener(actionListener); }});} /**Maps TextField.setColumns(int) through queue*/ public void setColumns(final int i) { runMapping(new MapVoidAction("setColumns") { public void map() { ((TextField)getSource()).setColumns(i); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Allows to find component by text. */ public static class TextFieldByTextFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs TextFieldByTextFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public TextFieldByTextFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs TextFieldByTextFinder. * @param lb a text pattern */ public TextFieldByTextFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof TextField) { if(((TextField)comp).getText() != null) { return(comparator.equals(((TextField)comp).getText(), label)); } } return(false); } public String getDescription() { return("TextField with text \"" + label + "\""); } } /** * Checks component type. */ public static class TextFieldFinder extends Finder { /** * Constructs TextFieldFinder. * @param sf other searching criteria. */ public TextFieldFinder(ComponentChooser sf) { super(TextField.class, sf); } /** * Constructs TextFieldFinder. */ public TextFieldFinder() { super(TextField.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JComboBoxOperator.java0000644000175000017500000011444211245712447023517 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.util.Hashtable; import javax.swing.ComboBoxEditor; import javax.swing.ComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.JTextField; import javax.swing.ListCellRenderer; import javax.swing.JComboBox.KeySelectionManager; import javax.swing.event.ListDataEvent; import javax.swing.plaf.ComboBoxUI; import javax.swing.plaf.basic.ComboPopup; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.Waiter; import org.netbeans.jemmy.WindowWaiter; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.ListDriver; import org.netbeans.jemmy.util.EmptyVisualizer; /** *

Timeouts used:
* JComboBoxOperator.BeforeSelectingTimeout - time to sleep after list opened and before item selected
* JComboBoxOperator.WaitListTimeout - time to wait list opened
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait component enabled
* ComponentOperator.WaitStateTimeout - time to wait for item to be selected
* AbstractButtonOperator.PushButtonTimeout - time between combo button pressing and releasing
* ComponentOperator.MouseClickTimeout - time between mouse pressing and releasing during item selecting
* JTextComponentOperator.PushKeyTimeout - time between key pressing and releasing during text typing
* JTextComponentOperator.BetweenKeysTimeout - time to sleep between two chars typing
* JTextComponentOperator.ChangeCaretPositionTimeout - maximum time to chenge caret position
* JTextComponentOperator.TypeTextTimeout - maximum time to type text
. * * @see Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JComboBoxOperator extends JComponentOperator implements Timeoutable, Outputable { /** * Identifier for a "text" property. * @see #getDump */ public static final String TEXT_DPROP = "Text"; /** * Identifier for a "item" property values. * @see #getDump */ public static final String ITEM_PREFIX_DPROP = "Item"; private final static long BEFORE_SELECTING_TIMEOUT = 0; private final static long WAIT_LIST_TIMEOUT = 60000; private TestOut output; private Timeouts timeouts; private JButtonOperator button; private JTextFieldOperator text; ListDriver driver; /** * Constructs a JComboBoxOperator object. * @param b a component */ public JComboBoxOperator(JComboBox b) { super(b); driver = DriverManager.getListDriver(getClass()); } /** * Constructs a JComboBoxOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JComboBoxOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JComboBox)cont. waitSubComponent(new JComboBoxFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JComboBoxOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JComboBoxOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of item which is currently selected. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JComboBoxOperator(ContainerOperator cont, String text, int index) { this((JComboBox)waitComponent(cont, new JComboBoxByItemFinder(text, -1, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of item which is currently selected. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JComboBoxOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JComboBoxOperator(ContainerOperator cont, int index) { this((JComboBox) waitComponent(cont, new JComboBoxFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JComboBoxOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JComboBox in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JComboBox instance or null if component was not found. */ public static JComboBox findJComboBox(Container cont, ComponentChooser chooser, int index) { return((JComboBox)findComponent(cont, new JComboBoxFinder(chooser), index)); } /** * Searches 0'th JComboBox in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JComboBox instance or null if component was not found. */ public static JComboBox findJComboBox(Container cont, ComponentChooser chooser) { return(findJComboBox(cont, chooser, 0)); } /** * Searches JComboBox by item. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param itemIndex Index of item to compare text. If -1, selected item is checked. * @param index Ordinal component index. * @return JComboBox instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JComboBox findJComboBox(Container cont, String text, boolean ce, boolean ccs, int itemIndex, int index) { return(findJComboBox(cont, new JComboBoxByItemFinder(text, itemIndex, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches JComboBox by item. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param itemIndex Index of item to compare text. If -1, selected item is checked. * @return JComboBox instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JComboBox findJComboBox(Container cont, String text, boolean ce, boolean ccs, int itemIndex) { return(findJComboBox(cont, text, ce, ccs, itemIndex, 0)); } /** * Waits JComboBox in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JComboBox instance or null if component was not found. * @throws TimeoutExpiredException */ public static JComboBox waitJComboBox(Container cont, ComponentChooser chooser, int index) { return((JComboBox)waitComponent(cont, new JComboBoxFinder(chooser), index)); } /** * Waits 0'th JComboBox in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JComboBox instance or null if component was not found. * @throws TimeoutExpiredException */ public static JComboBox waitJComboBox(Container cont, ComponentChooser chooser) { return(waitJComboBox(cont, chooser, 0)); } /** * Waits JComboBox by item. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param itemIndex Index of item to compare text. If -1, selected item is checked. * @param index Ordinal component index. * @return JComboBox instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JComboBox waitJComboBox(Container cont, String text, boolean ce, boolean ccs, int itemIndex, int index) { return(waitJComboBox(cont, new JComboBoxByItemFinder(text, itemIndex, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits JComboBox by item. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param itemIndex Index of item to compare text. If -1, selected item is checked. * @return JComboBox instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JComboBox waitJComboBox(Container cont, String text, boolean ce, boolean ccs, int itemIndex) { return(waitJComboBox(cont, text, ce, ccs, itemIndex, 0)); } static { Timeouts.initDefault("JComboBoxOperator.BeforeSelectingTimeout", BEFORE_SELECTING_TIMEOUT); Timeouts.initDefault("JComboBoxOperator.WaitListTimeout", WAIT_LIST_TIMEOUT); } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut output) { super.setOutput(output); this.output = output; } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (ListDriver)DriverManager. getDriver(DriverManager.LIST_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Searches JButton inside component. * @return JButton which is used to expand this JComboBox. */ public JButton findJButton() { return((JButton)waitSubComponent(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp instanceof JButton); } public String getDescription() { return("Button for combobox popup menu opening"); } })); } /** * Searches JTextField inside component. * @return JTextField if JComboBox is editable, null otherwise. */ public JTextField findJTextField() { return((JTextField)waitSubComponent(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp instanceof JTextField); } public String getDescription() { return("ComboBox's text field"); } })); } /** * Creates an operator for button returned by * findJButton() method. * @return new JButtonOperator instance. */ public JButtonOperator getButton() { if(button == null) { button = new JButtonOperator(findJButton()); button.copyEnvironment(this); button.setOutput(getOutput().createErrorOutput()); } return(button); } /** * Creates an operator for button returned by * findJTextField() method. * @return new JTextField instance. */ public JTextFieldOperator getTextField() { if(((JComboBox)getSource()).isEditable()) { text = new JTextFieldOperator(findJTextField()); text.copyEnvironment(this); text.setOutput(getOutput().createErrorOutput()); } return(text); } /** * Waits combobox's list to be displayed. * @return JList object if it was displayed in JComboBoxOperator.WaitListTimeout millisecont, * null otherwise. * @throws TimeoutExpiredException */ public JList waitList() { Waiter pw = new ListWater(); pw.setOutput(output.createErrorOutput()); pw.setTimeoutsToCloneOf(timeouts, "JComboBoxOperator.WaitListTimeout"); try { return((JList)pw.waitAction(null)); } catch(InterruptedException e) { output.printStackTrace(e); } return(null); } /** * Push combobox's button to expand or collapse combobox. * @throws TimeoutExpiredException */ public void pushComboButton() { makeComponentVisible(); getButton().push(); } /** * Finds an item between list items. * @param item a text pattern. * @param comparator a searching criteria. * @return an item index. */ public int findItemIndex(String item, StringComparator comparator) { ComboBoxModel model = getModel(); for(int i = 0; i < model.getSize(); i++) { if(comparator.equals(model.getElementAt(i).toString(), item)) { return(i); } } return(-1); } /** * Waits for an item available between list items. * @param item a text pattern. * @param comparator a searching criteria. * @return an item index or throws TimeoutExpiredException if item not found. */ public int waitItem(final String item, final StringComparator comparator) { getOutput().printLine("Wait item \"" + item + "\" available in combo box \n : "+ toStringSource()); getOutput().printGolden("Wait item \"" + item + "\" available in combo box."); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return findItemIndex(item, comparator) > -1; } public String getDescription() { return "Item \"" + item + "\" available in combo box."; } }); return findItemIndex(item, comparator); } /** * Waits for an item of given index available between list items. * @param itemIndex index of desired item * @return an item index or throws TimeoutExpiredException if item not found. */ public int waitItem(final int itemIndex) { getOutput().printLine("Wait item of index \"" + itemIndex + "\" available in combo box \n : "+ toStringSource()); getOutput().printGolden("Wait item of index \"" + itemIndex + "\" available in combo box."); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { // given itemIndex is within size of combo box return getModel().getSize() > itemIndex; } public String getDescription() { return "Item \"" + itemIndex + "\" available in combo box."; } }); return itemIndex; } /** * Selects an item by text. * @param item a text pattern. * @param comparator a searching criteria. */ public void selectItem(String item, StringComparator comparator) { output.printLine("Select \"" + item + "\" item in combobox\n : " + toStringSource()); output.printGolden("Select \"" + item + "\" item in combobox"); selectItem(waitItem(item, comparator)); } /** * Selects combobox item. * @param item Item text. * @param ce Compare exactly. * @param cc Compare case sensitivelly. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException * @deprecated Use selectItem(String) or selectItem(String, StringComparator) */ public void selectItem(String item, boolean ce, boolean cc) { selectItem(item, new DefaultStringComparator(ce, cc)); } /** * Selects combobox item. * Uses StringComparator assigned to this object. * @param item Item text. * @throws TimeoutExpiredException */ public void selectItem(String item) { selectItem(item, getComparator()); } /** * Selects combobox item. * If verification mode is on, checks that right item has been selected. * @param index Item index. * @throws TimeoutExpiredException */ public void selectItem(int index) { output.printLine("Select " + Integer.toString(index) + "\'th item in combobox\n : " + toStringSource()); output.printGolden("Select " + Integer.toString(index) + "\'th item in combobox"); try { waitComponentEnabled(); } catch(InterruptedException e) { throw new JemmyException("Interrupted", e); } driver.selectItem(this, waitItem(index)); if(getVerification()) { waitItemSelected(index); } } /** * Types text in the editable combobox. * If combobox has no focus, does simple mouse click on it first. * @param text text to type. * @throws TimeoutExpiredException */ public void typeText(String text) { makeComponentVisible(); JTextFieldOperator tfo = getTextField(); tfo.copyEnvironment(this); tfo.setVisualizer(new EmptyVisualizer()); tfo.typeText(text); } /** * Clears text in the editable combobox using left-arrow and delete keys. * If combobox has no focus, does simple mouse click on it first. * @throws TimeoutExpiredException */ public void clearText() { makeComponentVisible(); JTextFieldOperator tfo = getTextField(); tfo.copyEnvironment(this); tfo.setVisualizer(new EmptyVisualizer()); tfo.clearText(); } /** * Requests a focus, clears text, types new one and pushes Enter. * @param text New text value. Shouln't include final '\n'. * @throws TimeoutExpiredException */ public void enterText(String text) { makeComponentVisible(); JTextFieldOperator tfo = getTextField(); tfo.copyEnvironment(this); tfo.setVisualizer(new EmptyVisualizer()); tfo.enterText(text); } /** * Waits for item to be selected. * @param index Item index. */ public void waitItemSelected(final int index) { getOutput().printLine("Wait " + Integer.toString(index) + "'th item to be selected in component \n : "+ toStringSource()); getOutput().printGolden("Wait " + Integer.toString(index) + "'th item to be selected"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(getSelectedIndex() == index); } public String getDescription() { return("Has " + Integer.toString(index) + "'th item selected"); } }); } /** * Waits for item to be selected. Uses getComparator() comparator. * @param item wait an item to be selected. */ public void waitItemSelected(final String item) { getOutput().printLine("Wait \"" + item + "\" item to be selected in component \n : "+ toStringSource()); getOutput().printGolden("WaitWait \"" + item + "\" item to be selected"); waitState(new JComboBoxByItemFinder(item, -1, getComparator())); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); if(((JComboBox)getSource()).getSelectedItem() != null && ((JComboBox)getSource()).getSelectedItem().toString() != null) { result.put(TEXT_DPROP, ((JComboBox)getSource()).getSelectedItem().toString()); } String[] items = new String[((JComboBox)getSource()).getItemCount()]; for(int i = 0; i < ((JComboBox)getSource()).getItemCount(); i++) { if(((JComboBox)getSource()).getItemAt(i) != null && ((JComboBox)getSource()).getItemAt(i).toString() != null) { items[i] = ((JComboBox)getSource()).getItemAt(i).toString(); } } addToDump(result, ITEM_PREFIX_DPROP, items); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JComboBox.actionPerformed(ActionEvent) through queue*/ public void actionPerformed(final ActionEvent actionEvent) { runMapping(new MapVoidAction("actionPerformed") { public void map() { ((JComboBox)getSource()).actionPerformed(actionEvent); }});} /**Maps JComboBox.addActionListener(ActionListener) through queue*/ public void addActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("addActionListener") { public void map() { ((JComboBox)getSource()).addActionListener(actionListener); }});} /**Maps JComboBox.addItem(Object) through queue*/ public void addItem(final Object object) { runMapping(new MapVoidAction("addItem") { public void map() { ((JComboBox)getSource()).addItem(object); }});} /**Maps JComboBox.addItemListener(ItemListener) through queue*/ public void addItemListener(final ItemListener itemListener) { runMapping(new MapVoidAction("addItemListener") { public void map() { ((JComboBox)getSource()).addItemListener(itemListener); }});} /**Maps JComboBox.configureEditor(ComboBoxEditor, Object) through queue*/ public void configureEditor(final ComboBoxEditor comboBoxEditor, final Object object) { runMapping(new MapVoidAction("configureEditor") { public void map() { ((JComboBox)getSource()).configureEditor(comboBoxEditor, object); }});} /**Maps JComboBox.contentsChanged(ListDataEvent) through queue*/ public void contentsChanged(final ListDataEvent listDataEvent) { runMapping(new MapVoidAction("contentsChanged") { public void map() { ((JComboBox)getSource()).contentsChanged(listDataEvent); }});} /**Maps JComboBox.getActionCommand() through queue*/ public String getActionCommand() { return((String)runMapping(new MapAction("getActionCommand") { public Object map() { return(((JComboBox)getSource()).getActionCommand()); }}));} /**Maps JComboBox.getEditor() through queue*/ public ComboBoxEditor getEditor() { return((ComboBoxEditor)runMapping(new MapAction("getEditor") { public Object map() { return(((JComboBox)getSource()).getEditor()); }}));} /**Maps JComboBox.getItemAt(int) through queue*/ public Object getItemAt(final int i) { return((Object)runMapping(new MapAction("getItemAt") { public Object map() { return(((JComboBox)getSource()).getItemAt(i)); }}));} /**Maps JComboBox.getItemCount() through queue*/ public int getItemCount() { return(runMapping(new MapIntegerAction("getItemCount") { public int map() { return(((JComboBox)getSource()).getItemCount()); }}));} /**Maps JComboBox.getKeySelectionManager() through queue*/ public KeySelectionManager getKeySelectionManager() { return((KeySelectionManager)runMapping(new MapAction("getKeySelectionManager") { public Object map() { return(((JComboBox)getSource()).getKeySelectionManager()); }}));} /**Maps JComboBox.getMaximumRowCount() through queue*/ public int getMaximumRowCount() { return(runMapping(new MapIntegerAction("getMaximumRowCount") { public int map() { return(((JComboBox)getSource()).getMaximumRowCount()); }}));} /**Maps JComboBox.getModel() through queue*/ public ComboBoxModel getModel() { return((ComboBoxModel)runMapping(new MapAction("getModel") { public Object map() { return(((JComboBox)getSource()).getModel()); }}));} /**Maps JComboBox.getRenderer() through queue*/ public ListCellRenderer getRenderer() { return((ListCellRenderer)runMapping(new MapAction("getRenderer") { public Object map() { return(((JComboBox)getSource()).getRenderer()); }}));} /**Maps JComboBox.getSelectedIndex() through queue*/ public int getSelectedIndex() { return(runMapping(new MapIntegerAction("getSelectedIndex") { public int map() { return(((JComboBox)getSource()).getSelectedIndex()); }}));} /**Maps JComboBox.getSelectedItem() through queue*/ public Object getSelectedItem() { return((Object)runMapping(new MapAction("getSelectedItem") { public Object map() { return(((JComboBox)getSource()).getSelectedItem()); }}));} /**Maps JComboBox.getSelectedObjects() through queue*/ public Object[] getSelectedObjects() { return((Object[])runMapping(new MapAction("getSelectedObjects") { public Object map() { return(((JComboBox)getSource()).getSelectedObjects()); }}));} /**Maps JComboBox.getUI() through queue*/ public ComboBoxUI getUI() { return((ComboBoxUI)runMapping(new MapAction("getUI") { public Object map() { return(((JComboBox)getSource()).getUI()); }}));} /**Maps JComboBox.hidePopup() through queue*/ public void hidePopup() { runMapping(new MapVoidAction("hidePopup") { public void map() { ((JComboBox)getSource()).hidePopup(); }});} /**Maps JComboBox.insertItemAt(Object, int) through queue*/ public void insertItemAt(final Object object, final int i) { runMapping(new MapVoidAction("insertItemAt") { public void map() { ((JComboBox)getSource()).insertItemAt(object, i); }});} /**Maps JComboBox.intervalAdded(ListDataEvent) through queue*/ public void intervalAdded(final ListDataEvent listDataEvent) { runMapping(new MapVoidAction("intervalAdded") { public void map() { ((JComboBox)getSource()).intervalAdded(listDataEvent); }});} /**Maps JComboBox.intervalRemoved(ListDataEvent) through queue*/ public void intervalRemoved(final ListDataEvent listDataEvent) { runMapping(new MapVoidAction("intervalRemoved") { public void map() { ((JComboBox)getSource()).intervalRemoved(listDataEvent); }});} /**Maps JComboBox.isEditable() through queue*/ public boolean isEditable() { return(runMapping(new MapBooleanAction("isEditable") { public boolean map() { return(((JComboBox)getSource()).isEditable()); }}));} /**Maps JComboBox.isLightWeightPopupEnabled() through queue*/ public boolean isLightWeightPopupEnabled() { return(runMapping(new MapBooleanAction("isLightWeightPopupEnabled") { public boolean map() { return(((JComboBox)getSource()).isLightWeightPopupEnabled()); }}));} /**Maps JComboBox.isPopupVisible() through queue*/ public boolean isPopupVisible() { return(runMapping(new MapBooleanAction("isPopupVisible") { public boolean map() { return(((JComboBox)getSource()).isPopupVisible()); }}));} /**Maps JComboBox.processKeyEvent(KeyEvent) through queue*/ public void processKeyEvent(final KeyEvent keyEvent) { runMapping(new MapVoidAction("processKeyEvent") { public void map() { ((JComboBox)getSource()).processKeyEvent(keyEvent); }});} /**Maps JComboBox.removeActionListener(ActionListener) through queue*/ public void removeActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("removeActionListener") { public void map() { ((JComboBox)getSource()).removeActionListener(actionListener); }});} /**Maps JComboBox.removeAllItems() through queue*/ public void removeAllItems() { runMapping(new MapVoidAction("removeAllItems") { public void map() { ((JComboBox)getSource()).removeAllItems(); }});} /**Maps JComboBox.removeItem(Object) through queue*/ public void removeItem(final Object object) { runMapping(new MapVoidAction("removeItem") { public void map() { ((JComboBox)getSource()).removeItem(object); }});} /**Maps JComboBox.removeItemAt(int) through queue*/ public void removeItemAt(final int i) { runMapping(new MapVoidAction("removeItemAt") { public void map() { ((JComboBox)getSource()).removeItemAt(i); }});} /**Maps JComboBox.removeItemListener(ItemListener) through queue*/ public void removeItemListener(final ItemListener itemListener) { runMapping(new MapVoidAction("removeItemListener") { public void map() { ((JComboBox)getSource()).removeItemListener(itemListener); }});} /**Maps JComboBox.selectWithKeyChar(char) through queue*/ public boolean selectWithKeyChar(final char c) { return(runMapping(new MapBooleanAction("selectWithKeyChar") { public boolean map() { return(((JComboBox)getSource()).selectWithKeyChar(c)); }}));} /**Maps JComboBox.setActionCommand(String) through queue*/ public void setActionCommand(final String string) { runMapping(new MapVoidAction("setActionCommand") { public void map() { ((JComboBox)getSource()).setActionCommand(string); }});} /**Maps JComboBox.setEditable(boolean) through queue*/ public void setEditable(final boolean b) { runMapping(new MapVoidAction("setEditable") { public void map() { ((JComboBox)getSource()).setEditable(b); }});} /**Maps JComboBox.setEditor(ComboBoxEditor) through queue*/ public void setEditor(final ComboBoxEditor comboBoxEditor) { runMapping(new MapVoidAction("setEditor") { public void map() { ((JComboBox)getSource()).setEditor(comboBoxEditor); }});} /**Maps JComboBox.setKeySelectionManager(KeySelectionManager) through queue*/ public void setKeySelectionManager(final KeySelectionManager keySelectionManager) { runMapping(new MapVoidAction("setKeySelectionManager") { public void map() { ((JComboBox)getSource()).setKeySelectionManager(keySelectionManager); }});} /**Maps JComboBox.setLightWeightPopupEnabled(boolean) through queue*/ public void setLightWeightPopupEnabled(final boolean b) { runMapping(new MapVoidAction("setLightWeightPopupEnabled") { public void map() { ((JComboBox)getSource()).setLightWeightPopupEnabled(b); }});} /**Maps JComboBox.setMaximumRowCount(int) through queue*/ public void setMaximumRowCount(final int i) { runMapping(new MapVoidAction("setMaximumRowCount") { public void map() { ((JComboBox)getSource()).setMaximumRowCount(i); }});} /**Maps JComboBox.setModel(ComboBoxModel) through queue*/ public void setModel(final ComboBoxModel comboBoxModel) { runMapping(new MapVoidAction("setModel") { public void map() { ((JComboBox)getSource()).setModel(comboBoxModel); }});} /**Maps JComboBox.setPopupVisible(boolean) through queue*/ public void setPopupVisible(final boolean b) { runMapping(new MapVoidAction("setPopupVisible") { public void map() { ((JComboBox)getSource()).setPopupVisible(b); }});} /**Maps JComboBox.setRenderer(ListCellRenderer) through queue*/ public void setRenderer(final ListCellRenderer listCellRenderer) { runMapping(new MapVoidAction("setRenderer") { public void map() { ((JComboBox)getSource()).setRenderer(listCellRenderer); }});} /**Maps JComboBox.setSelectedIndex(int) through queue*/ public void setSelectedIndex(final int i) { runMapping(new MapVoidAction("setSelectedIndex") { public void map() { ((JComboBox)getSource()).setSelectedIndex(i); }});} /**Maps JComboBox.setSelectedItem(Object) through queue*/ public void setSelectedItem(final Object object) { runMapping(new MapVoidAction("setSelectedItem") { public void map() { ((JComboBox)getSource()).setSelectedItem(object); }});} /**Maps JComboBox.setUI(ComboBoxUI) through queue*/ public void setUI(final ComboBoxUI comboBoxUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JComboBox)getSource()).setUI(comboBoxUI); }});} /**Maps JComboBox.showPopup() through queue*/ public void showPopup() { runMapping(new MapVoidAction("showPopup") { public void map() { ((JComboBox)getSource()).showPopup(); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Allows to find component by an item. */ public static class JComboBoxByItemFinder implements ComponentChooser { String label; int itemIndex; StringComparator comparator; /** * Constructs JComboBoxByItemFinder. * @param lb a text pattern * @param ii item index to check. If equal to -1, selected item is checked. * @param comparator specifies string comparision algorithm. */ public JComboBoxByItemFinder(String lb, int ii, StringComparator comparator) { label = lb; itemIndex = ii; this.comparator = comparator; } /** * Constructs JComboBoxByItemFinder. * @param lb a text pattern * @param ii item index to check. If equal to -1, selected item is checked. */ public JComboBoxByItemFinder(String lb, int ii) { this(lb, ii, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JComboBox) { if(label == null) { return(true); } if(((JComboBox)comp).getModel().getSize() > itemIndex) { int ii = itemIndex; if(ii == -1) { ii = ((JComboBox)comp).getSelectedIndex(); if(ii == -1) { return(false); } } return(comparator.equals(((JComboBox)comp).getModel().getElementAt(ii).toString(), label)); } } return(false); } public String getDescription() { return("JComboBox with text \"" + label + "\" in " + (new Integer(itemIndex)).toString() + "'th item"); } } /** * Checks component type. */ public static class JComboBoxFinder extends Finder { /** * Constructs JComboBoxFinder. * @param sf other searching criteria. */ public JComboBoxFinder(ComponentChooser sf) { super(JComboBox.class, sf); } /** * Constructs JComboBoxFinder. */ public JComboBoxFinder() { super(JComboBox.class); } } private class PopupWindowChooser implements ComponentChooser { ComponentChooser pChooser; public PopupWindowChooser(ComponentChooser pChooser) { this.pChooser = pChooser; } public boolean checkComponent(Component comp) { ComponentSearcher cs = new ComponentSearcher((Container)comp); cs.setOutput(TestOut.getNullOutput()); return(cs.findComponent(pChooser) != null); } public String getDescription() { return("Popup window"); } } private class ListWater extends Waiter { ComponentChooser cChooser; ComponentChooser pChooser; public ListWater() { super(); cChooser = new ComponentChooser() { public boolean checkComponent(Component comp) { if(comp instanceof JList) { Container cont = (Container)comp; while((cont = cont.getParent()) != null) { if(cont instanceof ComboPopup) { return(true); } } } return(false); } public String getDescription() { return("Popup menu"); } }; pChooser = new PopupWindowChooser(cChooser); } public Object actionProduced(Object obj) { Window popupWindow = null; if(pChooser.checkComponent(getWindow())) { popupWindow = getWindow(); } else { popupWindow = WindowWaiter.getWindow(getWindow(), pChooser); } if(popupWindow != null) { ComponentSearcher sc = new ComponentSearcher(popupWindow); sc.setOutput(TestOut.getNullOutput()); return(sc.findComponent(cChooser)); } else { return(null); } } public String getDescription() { return("Wait popup expanded"); } } } Jemmy2/src/org/netbeans/jemmy/operators/JColorChooserOperator.java0000644000175000017500000004030411245712347024402 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Color; import java.awt.Container; import java.util.Hashtable; import javax.swing.JColorChooser; import javax.swing.JComponent; import javax.swing.JTabbedPane; import javax.swing.colorchooser.AbstractColorChooserPanel; import javax.swing.colorchooser.ColorSelectionModel; import javax.swing.plaf.ColorChooserUI; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; /** * * Class provides methods to cover main JColorChooser component functionality. * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JColorChooserOperator extends JComponentOperator implements Outputable { /** * Identifier for a "color" property. * @see #getDump */ public static final String COLOR_DPROP = "Color"; /** * Identifier for a "selected page" property. * @see #getDump */ public static final String SELECTED_PAGE_DPROP = "Selected page"; private static final String RGB_TITLE = "RGB"; private TestOut output; private JTabbedPaneOperator tabbed; private JTextFieldOperator red; private JTextFieldOperator green; private JTextFieldOperator blue; /** * Constructor. * @param comp a component */ public JColorChooserOperator(JColorChooser comp) { super(comp); setTimeouts(JemmyProperties.getProperties().getTimeouts()); setOutput(JemmyProperties.getProperties().getOutput()); tabbed = new JTabbedPaneOperator(this); } /** * Constructs a JColorChooserOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JColorChooserOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JColorChooser)cont. waitSubComponent(new JColorChooserFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JColorChooserOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JColorChooserOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @param index Ordinal component index. * */ public JColorChooserOperator(ContainerOperator cont, int index) { this((JColorChooser) waitComponent(cont, new JColorChooserFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * */ public JColorChooserOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JColorChooser in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JColorChooser instance or null if component was not found. */ public static JColorChooser findJColorChooser(Container cont, ComponentChooser chooser, int index) { return((JColorChooser)findComponent(cont, new JColorChooserFinder(chooser), index)); } /** * Searches 0'th JColorChooser in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JColorChooser instance or null if component was not found. */ public static JColorChooser findJColorChooser(Container cont, ComponentChooser chooser) { return(findJColorChooser(cont, chooser, 0)); } /** * Searches JColorChooser in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JColorChooser instance or null if component was not found. */ public static JColorChooser findJColorChooser(Container cont, int index) { return(findJColorChooser(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JColorChooser instance"), index)); } /** * Searches 0'th JColorChooser in container. * @param cont Container to search component in. * @return JColorChooser instance or null if component was not found. */ public static JColorChooser findJColorChooser(Container cont) { return(findJColorChooser(cont, 0)); } /** * Waits JColorChooser in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JColorChooser instance or null if component was not displayed. * */ public static JColorChooser waitJColorChooser(Container cont, ComponentChooser chooser, int index) { return((JColorChooser)waitComponent(cont, new JColorChooserFinder(chooser), index)); } /** * Waits 0'th JColorChooser in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JColorChooser instance or null if component was not displayed. * */ public static JColorChooser waitJColorChooser(Container cont, ComponentChooser chooser) { return(waitJColorChooser(cont, chooser, 0)); } /** * Waits JColorChooser in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JColorChooser instance or null if component was not displayed. * */ public static JColorChooser waitJColorChooser(Container cont, int index) { return(waitJColorChooser(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JColorChooser instance"), index)); } /** * Waits 0'th JColorChooser in container. * @param cont Container to search component in. * @return JColorChooser instance or null if component was not displayed. * */ public static JColorChooser waitJColorChooser(Container cont) { return(waitJColorChooser(cont, 0)); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } /** * Switches tab to "RGB" page. */ public void switchToRGB() { if(!tabbed.getTitleAt(tabbed.getSelectedIndex()). equals(RGB_TITLE)) { tabbed.selectPage(RGB_TITLE); } blue = new JTextFieldOperator(this, 2); green = new JTextFieldOperator(this, 1); red = new JTextFieldOperator(this, 0); } /** * Enters red color component value. * Switches to "RGB" page first. * @param value red color component * @see #switchToRGB() * @see #enterColor(int, int, int) * @see #enterColor(java.awt.Color) * @see #enterColor(int) */ public void enterRed(int value) { switchToRGB(); red.setText(Integer.toString(value)); } /** * Enters green color component value. * Switches to "RGB" page first. * @param value green color component * @see #switchToRGB() * @see #enterColor(int, int, int) * @see #enterColor(java.awt.Color) * @see #enterColor(int) */ public void enterGreen(int value) { switchToRGB(); green.setText(Integer.toString(value)); } /** * Enters blue color component value. * Switches to "RGB" page first. * @param value blue color component * @see #switchToRGB() * @see #enterColor(int, int, int) * @see #enterColor(java.awt.Color) * @see #enterColor(int) */ public void enterBlue(int value) { switchToRGB(); blue.setText(Integer.toString(value)); } /** * Enters all color components values. * Switches to "RGB" page first. * @param red red color component * @param green green color component * @param blue blue color component * @see #switchToRGB() * @see #enterColor(java.awt.Color) * @see #enterColor(int) */ public void enterColor(int red, int green, int blue) { switchToRGB(); enterRed(red); enterGreen(green); enterBlue(blue); } /** * Enters color. * Switches to "RGB" page first. * @param color a color * @see #switchToRGB() * @see #enterColor(int, int, int) * @see #enterColor(int) */ public void enterColor(Color color) { enterColor(color.getRed(), color.getGreen(), color.getBlue()); } /** * Enters color. * Switches to "RGB" page first. * @param color a color * @see #switchToRGB() * @see #enterColor(int, int, int) * @see #enterColor(java.awt.Color) */ public void enterColor(int color) { enterColor(new Color(color)); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); result.put(COLOR_DPROP, ((JColorChooser)getSource()).getColor().toString()); JTabbedPane tb = (JTabbedPane)tabbed.getSource(); result.put(SELECTED_PAGE_DPROP, tb.getTitleAt(tb.getSelectedIndex())); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JColorChooser.addChooserPanel(AbstractColorChooserPanel) through queue*/ public void addChooserPanel(final AbstractColorChooserPanel abstractColorChooserPanel) { runMapping(new MapVoidAction("addChooserPanel") { public void map() { ((JColorChooser)getSource()).addChooserPanel(abstractColorChooserPanel); }});} /**Maps JColorChooser.getChooserPanels() through queue*/ public AbstractColorChooserPanel[] getChooserPanels() { return((AbstractColorChooserPanel[])runMapping(new MapAction("getChooserPanels") { public Object map() { return(((JColorChooser)getSource()).getChooserPanels()); }}));} /**Maps JColorChooser.getColor() through queue*/ public Color getColor() { return((Color)runMapping(new MapAction("getColor") { public Object map() { return(((JColorChooser)getSource()).getColor()); }}));} /**Maps JColorChooser.getPreviewPanel() through queue*/ public JComponent getPreviewPanel() { return((JComponent)runMapping(new MapAction("getPreviewPanel") { public Object map() { return(((JColorChooser)getSource()).getPreviewPanel()); }}));} /**Maps JColorChooser.getSelectionModel() through queue*/ public ColorSelectionModel getSelectionModel() { return((ColorSelectionModel)runMapping(new MapAction("getSelectionModel") { public Object map() { return(((JColorChooser)getSource()).getSelectionModel()); }}));} /**Maps JColorChooser.getUI() through queue*/ public ColorChooserUI getUI() { return((ColorChooserUI)runMapping(new MapAction("getUI") { public Object map() { return(((JColorChooser)getSource()).getUI()); }}));} /**Maps JColorChooser.removeChooserPanel(AbstractColorChooserPanel) through queue*/ public AbstractColorChooserPanel removeChooserPanel(final AbstractColorChooserPanel abstractColorChooserPanel) { return((AbstractColorChooserPanel)runMapping(new MapAction("removeChooserPanel") { public Object map() { return(((JColorChooser)getSource()).removeChooserPanel(abstractColorChooserPanel)); }}));} /**Maps JColorChooser.setChooserPanels(AbstractColorChooserPanel[]) through queue*/ public void setChooserPanels(final AbstractColorChooserPanel[] abstractColorChooserPanel) { runMapping(new MapVoidAction("setChooserPanels") { public void map() { ((JColorChooser)getSource()).setChooserPanels(abstractColorChooserPanel); }});} /**Maps JColorChooser.setColor(int) through queue*/ public void setColor(final int i) { runMapping(new MapVoidAction("setColor") { public void map() { ((JColorChooser)getSource()).setColor(i); }});} /**Maps JColorChooser.setColor(int, int, int) through queue*/ public void setColor(final int i, final int i1, final int i2) { runMapping(new MapVoidAction("setColor") { public void map() { ((JColorChooser)getSource()).setColor(i, i1, i2); }});} /**Maps JColorChooser.setColor(Color) through queue*/ public void setColor(final Color color) { runMapping(new MapVoidAction("setColor") { public void map() { ((JColorChooser)getSource()).setColor(color); }});} /**Maps JColorChooser.setPreviewPanel(JComponent) through queue*/ public void setPreviewPanel(final JComponent jComponent) { runMapping(new MapVoidAction("setPreviewPanel") { public void map() { ((JColorChooser)getSource()).setPreviewPanel(jComponent); }});} /**Maps JColorChooser.setSelectionModel(ColorSelectionModel) through queue*/ public void setSelectionModel(final ColorSelectionModel colorSelectionModel) { runMapping(new MapVoidAction("setSelectionModel") { public void map() { ((JColorChooser)getSource()).setSelectionModel(colorSelectionModel); }});} /**Maps JColorChooser.setUI(ColorChooserUI) through queue*/ public void setUI(final ColorChooserUI colorChooserUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JColorChooser)getSource()).setUI(colorChooserUI); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Checks component type. */ public static class JColorChooserFinder extends Finder { /** * Constructs JColorChooserFinder. * @param sf other searching criteria. */ public JColorChooserFinder(ComponentChooser sf) { super(JColorChooser.class, sf); } /** * Constructs JColorChooserFinder. */ public JColorChooserFinder() { super(JColorChooser.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JTableOperator.java0000644000175000017500000022520211245712447023033 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.util.EventObject; import java.util.Hashtable; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ListSelectionEvent; import javax.swing.event.TableColumnModelEvent; import javax.swing.event.TableModelEvent; import javax.swing.plaf.TableUI; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.Waiter; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.TableDriver; import org.netbeans.jemmy.util.EmptyVisualizer; /** *

Timeouts used:
* JTableOperator.WaitEditingTimeout - time to wait cell editing
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.WaitStateTimeout - time to wait for cell contents
* JTextComponentOperator.ChangeCaretPositionTimeout - maximum time to chenge caret position
* JTextComponentOperator.TypeTextTimeout - maximum time to type text
* JScrollBarOperator.WholeScrollTimeout - time for the whole scrolling
. * * @see Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JTableOperator extends JComponentOperator implements Outputable, Timeoutable { /** * Identifier for a "cell" property. * @see #getDump */ public static final String CELL_PREFIX_DPROP = "Cell"; /** * Identifier for a "column" property. * @see #getDump */ public static final String COLUMN_PREFIX_DPROP = "Column"; /** * Identifier for a "selected column" property. * @see #getDump */ public static final String SELECTED_COLUMN_PREFIX_DPROP = "SelectedColumn"; /** * Identifier for a "selected row" property. * @see #getDump */ public static final String SELECTED_ROW_PREFIX_DPROP = "SelectedRow"; /** * Identifier for a "column count" property. * @see #getDump */ public static final String COLUMN_COUNT_DPROP = "Column count"; /** * Identifier for a "row count" property. * @see #getDump */ public static final String ROW_COUNT_DPROP = "Row count"; private final static long WAIT_EDITING_TIMEOUT = 60000; private TestOut output; private Timeouts timeouts; TableDriver driver; /** * Constructor. * @param b a component */ public JTableOperator(JTable b) { super(b); driver = DriverManager.getTableDriver(getClass()); } /** * Constructs a JTableOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JTableOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JTable)cont. waitSubComponent(new JTableFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JTableOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JTableOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits by cell text first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of a cell which is currently selected. * @param row a cell row to check. * @param column a cell row to check. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTableOperator(ContainerOperator cont, String text, int row, int column, int index) { this((JTable)waitComponent(cont, new JTableByCellFinder(text, row, column, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits by cell text first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of a cell which is currently selected. * @param row a cell row to check. * @param column a cell row to check. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTableOperator(ContainerOperator cont, String text, int row, int column) { this(cont, text, row, column, 0); } /** * Constructor. * Waits by text in selected cell first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of a cell which is currently selected. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTableOperator(ContainerOperator cont, String text, int index) { this(cont, text, -1, -1, index); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of a cell which is currently selected. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTableOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JTableOperator(ContainerOperator cont, int index) { this((JTable) waitComponent(cont, new JTableFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JTableOperator(ContainerOperator cont) { this(cont, 0); } //////////////////////////////////////////////////////// //Static finds // //////////////////////////////////////////////////////// /** * Searches JTable in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JTable instance or null if component was not found. */ public static JTable findJTable(Container cont, ComponentChooser chooser, int index) { return((JTable)findComponent(cont, new JTableFinder(chooser), index)); } /** * Searches 0'th JTable in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JTable instance or null if component was not found. */ public static JTable findJTable(Container cont, ComponentChooser chooser) { return(findJTable(cont, chooser, 0)); } /** * Searches JTable by cell. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param row Index of row to compare text. If -1, selected row is checked. * @param column Index of column to compare text. If -1, selected column is checked. * @param index Ordinal component index. * @return JTable instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTable findJTable(Container cont, String text, boolean ce, boolean ccs, int row, int column, int index) { return(findJTable(cont, new JTableByCellFinder(text, row, column, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches JTable by cell. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param row Index of row to compare text. If -1, selected row is checked. * @param column Index of column to compare text. If -1, selected column is checked. * @return JTable instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTable findJTable(Container cont, String text, boolean ce, boolean ccs, int row, int column) { return(findJTable(cont, text, ce, ccs, row, column, 0)); } /** * Waits JTable in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JTable instance or null if component was not found. * @throws TimeoutExpiredException */ public static JTable waitJTable(Container cont, ComponentChooser chooser, int index) { return((JTable)waitComponent(cont, new JTableFinder(chooser), index)); } /** * Waits 0'th JTable in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JTable instance or null if component was not found. * @throws TimeoutExpiredException */ public static JTable waitJTable(Container cont, ComponentChooser chooser) { return(waitJTable(cont, chooser, 0)); } /** * Waits JTable by cell. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param row Index of row to compare text. If -1, selected row is checked. * @param column Index of column to compare text. If -1, selected column is checked. * @param index Ordinal component index. * @return JTable instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JTable waitJTable(Container cont, String text, boolean ce, boolean ccs, int row, int column, int index) { return(waitJTable(cont, new JTableByCellFinder(text, row, column, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits JTable by cell. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param row Index of row to compare text. If -1, selected row is checked. * @param column Index of column to compare text. If -1, selected column is checked. * @return JTable instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JTable waitJTable(Container cont, String text, boolean ce, boolean ccs, int row, int column) { return(waitJTable(cont, text, ce, ccs, row, column, 0)); } static { Timeouts.initDefault("JTableOperator.WaitEditingTimeout", WAIT_EDITING_TIMEOUT); } //////////////////////////////////////////////////////// //Environment // //////////////////////////////////////////////////////// public void setTimeouts(Timeouts times) { this.timeouts = times; super.setTimeouts(timeouts); } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output); } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (TableDriver)DriverManager. getDriver(DriverManager.TABLE_DRIVER_ID, getClass(), anotherOperator.getProperties()); } //////////////////////////////////////////////////////// //Find methods // //////////////////////////////////////////////////////// //text, comparator and index /** * Searches cell coordinates. * @param text a text pattern * @param comparator a string comparision algorithm * @param index an ordinal cell index * @return Point indicating coordinates (x - column, y - row) */ public Point findCell(String text, StringComparator comparator, int index) { return(findCell(new BySubStringTableCellChooser(text, comparator), index)); } /** * Searches cell coordinates in the specified rows and columns. * @param text a text pattern * @param comparator a string comparision algorithm * @param rows rows to search in * @param columns columns to search in * @param index an ordinal cell index * @return Point indicating coordinates (x - column, y - row) */ public Point findCell(String text, StringComparator comparator, int[] rows, int[] columns, int index) { return(findCell(new BySubStringTableCellChooser(text, comparator), rows, columns, index)); } /** * Searches cell row index. * @param text a text pattern * @param comparator a string comparision algorithm * @param index an ordinal cell index * @return a row index. */ public int findCellRow(String text, StringComparator comparator, int index) { return(findCell(text, comparator, index).y); } /** * Searches cell row index. Searching is performed between cells in one column. * @param text a text pattern * @param comparator a string comparision algorithm * @param column a column index to search in * @param index an ordinal cell index * @return a row index. */ public int findCellRow(String text, StringComparator comparator, int column, int index) { return(findCell(text, comparator, null, new int[] {column}, index).y); } /** * Searches cell column visible index. * @param text a text pattern * @param comparator a string comparision algorithm * @param index an ordinal cell index * @return a column index. */ public int findCellColumn(String text, StringComparator comparator, int index) { return(findCell(text, comparator, index).x); } /** * Searches cell column index. Searching is performed between cells in one row. * @param text a text pattern * @param comparator a string comparision algorithm * @param row a row index to search in * @param index an ordinal cell index * @return a column index. */ public int findCellColumn(String text, StringComparator comparator, int row, int index) { return(findCell(text, comparator, new int[] {row}, null, index).x); } //booleans - deprecated /** * Searches cell row by cell text. * @param text Text to search by. * @param ce Compare exactly. * @param ccs Compare case sensitively. * @param index Ordinal index in suitable cells. * @return a row index. * @see #findCellRow(String, int) * @deprecated Use findCellRow(String, int) or findCellRow(String, StringComparator, int) */ public int findCellRow(String text, boolean ce, boolean ccs, int index) { return(findCell(text, ce, ccs, index).y); } /** * Searches cell column by cell text. * @param text Text to search by. * @param ce Compare exactly. * @param ccs Compare case sensitively. * @param index Ordinal index in suitable cells. * @return a column index. * @see #findCellColumn(String, int) * @deprecated Use findCellColumn(String, int) or findCellColumn(String, StringComparator, int) */ public int findCellColumn(String text, boolean ce, boolean ccs, int index) { return(findCell(text, ce, ccs, index).x); } /** * Searches first cell row by cell text. * @param text Text to search by. * @param ce Compare exactly. * @param ccs Compare case sensitively. * @return a row index. * @see #findCellRow(String) * @deprecated Use findCellRow(String) or findCellRow(String, StringComparator) */ public int findCellRow(String text, boolean ce, boolean ccs) { return(findCellRow(text, ce, ccs, 0)); } /** * Searches first cell column by cell text. * @param text Text to search by. * @param ce Compare exactly. * @param ccs Compare case sensitively. * @return a column index. * @see #findCellColumn(String) * @deprecated Use findCellColumn(String) or findCellColumn(String, StringComparator) */ public int findCellColumn(String text, boolean ce, boolean ccs) { return(findCellColumn(text, ce, ccs, 0)); } //text and comparator only /** * Searches cell row index. * @param text a text pattern * @param comparator a string comparision algorithm * @return a row index. */ public int findCellRow(String text, StringComparator comparator) { return(findCellRow(text, comparator, 0)); } /** * Searches cell column visible index. * @param text a text pattern * @param comparator a string comparision algorithm * @return a column index. */ public int findCellColumn(String text, StringComparator comparator) { return(findCellColumn(text, comparator, 0)); } //text and index /** * Searches cell row by cell text. * @param text Text to search by. * @param index Ordinal index in suitable cells. * @return a row index. */ public int findCellRow(String text, int index) { return(findCell(text, index).y); } /** * Searches cell row index. Searching is performed between cells in one column. * @param text a text pattern * @param column a column index to search in * @param index Ordinal index in suitable cells. * @return a row index. */ public int findCellRow(String text, int column, int index) { return(findCell(text, null, new int[] {column}, index).y); } /** * Searches cell column by cell text. * @param text Text to search by. * @param index Ordinal index in suitable cells. * @return a column index. */ public int findCellColumn(String text, int index) { return(findCell(text, index).x); } /** * Searches cell column index. Searching is performed between cells in one row. * @param text a text pattern * @param row a row index to search in * @param index Ordinal index in suitable cells. * @return a column index. */ public int findCellColumn(String text, int row, int index) { return(findCell(text, new int[] {row}, null, index).x); } /** * Searches cell coordinates. * @param text a text pattern * @param index an ordinal cell index * @return Point indicating coordinates (x - column, y - row) */ public Point findCell(String text, int index) { return(findCell(text, getComparator(), index)); } /** * Searches cell coordinates in the specified rows and columns. * @param text a text pattern * @param rows rows to search in * @param columns columns to search in * @param index an ordinal cell index * @return Point indicating coordinates (x - column, y - row) */ public Point findCell(String text, int[] rows, int[] columns, int index) { return(findCell(new BySubStringTableCellChooser(text, getComparator()), rows, columns, index)); } //text only /** * Searches first cell row by cell text. * @param text Text to search by. * @return a row index. */ public int findCellRow(String text) { return(findCellRow(text, 0)); } /** * Searches first cell column by cell text. * @param text Text to search by. * @return a column index. */ public int findCellColumn(String text) { return(findCellColumn(text, 0)); } //component chooser and index /** * Searches cell row by rendered component. * @param chooser Component verifying object. * @param index Ordinal index in suitable cells. * @return a row index. */ public int findCellRow(ComponentChooser chooser, int index) { return(findCell(chooser, index).y); } /** * Searches cell row index. Searching is performed between cells in one column. * @param chooser Component verifying object. * @param column a column index to search in * @param index Ordinal index in suitable cells. * @return a row index. */ public int findCellRow(ComponentChooser chooser, int column, int index) { return(findCell(chooser, null, new int[] {column}, index).y); } /** * Searches cell column by rendered component. * @param chooser Component verifying object. * @param index Ordinal index in suitable cells. * @return a column index. */ public int findCellColumn(ComponentChooser chooser, int index) { return(findCell(chooser, index).x); } /** * Searches cell column index. Searching is performed between cells in one row. * @param chooser Component verifying object. * @param row a row index to search in * @param index Ordinal index in suitable cells. * @return a column index. */ public int findCellColumn(ComponentChooser chooser, int row, int index) { return(findCell(chooser, new int[] {row}, null, index).x); } /** * Searches cell coordinates. * @param chooser Component verifying object. * @param index an ordinal cell index * @return Point indicating coordinates (x - column, y - row) */ public Point findCell(ComponentChooser chooser, int index) { return(findCell(new ByRenderedComponentTableCellChooser(chooser), index)); } /** * Searches cell coordinates. * @param chooser Component verifying object. * @param rows rows to search in * @param columns columns to search in * @param index an ordinal cell index * @return Point indicating coordinates (x - column, y - row) */ public Point findCell(ComponentChooser chooser, int[] rows, int[] columns, int index) { return(findCell(new ByRenderedComponentTableCellChooser(chooser), rows, columns, index)); } //component chooser only /** * Searches cell row by rendered component. * @param chooser Component verifying object. * @return a row index. */ public int findCellRow(ComponentChooser chooser) { return(findCellRow(chooser, 0)); } /** * Searches cell column by rendered component. * @param chooser Component verifying object. * @return a column index. */ public int findCellColumn(ComponentChooser chooser) { return(findCellColumn(chooser, 0)); } /** * Searches cell coordinates. * @param chooser Component verifying object. * @return Point indicating coordinates (x - column, y - row) */ public Point findCell(ComponentChooser chooser) { return(findCell(chooser, 0)); } //cell chooser and index /** * Searches cell row by TableCellChooser. * @param chooser Cell verifying object. * @param index Ordinal index in suitable cells. * @return a row index. */ public int findCellRow(TableCellChooser chooser, int index) { return(findCell(chooser, index).y); } /** * Searches cell row index. Searching is performed between cells in one column. * @param chooser Cell verifying object. * @param column a column index to search in * @param index Ordinal index in suitable cells. * @return a row index. */ public int findCellRow(TableCellChooser chooser, int column, int index) { return(findCell(chooser, null, new int[] {column}, index).y); } /** * Searches cell column by TableCellChooser. * @param chooser ComponentCell verifying object. * @param index Ordinal index in suitable cells. * @return a column index. */ public int findCellColumn(TableCellChooser chooser, int index) { return(findCell(chooser, index).x); } /** * Searches cell column index. Searching is performed between cells in one row. * @param chooser Cell verifying object. * @param row a row index to search in * @param index Ordinal index in suitable cells. * @return a column index. */ public int findCellColumn(TableCellChooser chooser, int row, int index) { return(findCell(chooser, new int[] {row}, null, index).x); } /** * Searches cell coordinates. * @param chooser cell verifying object. * @param index an ordinal cell index * @return Point indicating coordinates (x - column, y - row) */ public Point findCell(TableCellChooser chooser, int index) { return(findCell(chooser, null, null, index)); } /** * Searches cell coordinates in the specified rows and columns. * @param chooser cell verifying object. * @param rows rows to search in * @param columns columns to search in * @param index an ordinal cell index * @return Point indicating coordinates (x - column, y - row) */ public Point findCell(TableCellChooser chooser, int[] rows, int[] columns, int index) { TableModel model = getModel(); int[] realRows; if(rows != null) { realRows = rows; } else { realRows = new int[model.getRowCount()]; for(int i = 0; i < model.getRowCount(); i++) { realRows[i] = i; } } int[] realColumns; if(columns != null) { realColumns = columns; } else { realColumns = new int[model.getColumnCount()]; for(int i = 0; i < model.getColumnCount(); i++) { realColumns[i] = i; } } int count = 0; for(int i = 0; i < realRows.length; i++) { for(int j = 0; j < realColumns.length; j++) { if(chooser.checkCell(this, realRows[i], realColumns[j])) { if(count == index) { return(new Point(realColumns[j], realRows[i])); } else { count++; } } } } return(new Point(-1, -1)); } //cell chooser only /** * Searches cell row by TableCellChooser. * @param chooser Cell verifying object. * @return a row index. */ public int findCellRow(TableCellChooser chooser) { return(findCellRow(chooser, 0)); } /** * Searches cell column by TableCellChooser. * @param chooser Cell verifying object. * @return a column index. */ public int findCellColumn(TableCellChooser chooser) { return(findCellColumn(chooser, 0)); } /** * Searches cell coordinates. * @param chooser cell verifying object. * @return Point indicating coordinates (x - column, y - row) */ public Point findCell(TableCellChooser chooser) { return(findCell(chooser, 0)); } //////////////////////////////////////////////////////// //Actions // //////////////////////////////////////////////////////// /** * Does mouse click on the cell. * @param row a row index * @param column a column index * @param clickCount a number of clicks * @param button a mouse button (value of InputEvent.BUTTON*_MASK field) * @param modifiers Modifiers (combination of InputEvent.*_MASK values) */ public void clickOnCell(final int row, final int column, final int clickCount, final int button, final int modifiers) { output.printLine("Click on (" + Integer.toString(row) + ", " + Integer.toString(column) + ") cell"); output.printGolden("Click on cell"); makeComponentVisible(); scrollToCell(row, column); getQueueTool().invokeSmoothly(new QueueTool.QueueAction("Path selecting") { public Object launch() { Point point = getPointToClick(row, column); clickMouse(point.x, point.y, clickCount, button, modifiers); return(null); } }); } /** * Does mouse click on the cell with no modifiers. * @param row a row index * @param column a column index * @param clickCount a number of clicks * @param button a mouse button (value of InputEvent.BUTTON*_MASK field) */ public void clickOnCell(int row, int column, int clickCount, int button) { clickOnCell(row, column, clickCount, button, 0); } /** * Does mouse click on the cell by default mouse button with no modifiers. * @param row a row index * @param column a column index * @param clickCount a number of clicks */ public void clickOnCell(int row, int column, int clickCount) { clickOnCell(row, column, clickCount, getDefaultMouseButton()); } /** * Does single mouse click on the cell. * @param row a row index * @param column a column index */ public void clickOnCell(int row, int column) { clickOnCell(row, column, 1); } /** * Double clicks on cell to turns it to the editing mode. * @param row a row index * @param column a column index * @throws TimeoutExpiredException */ public void clickForEdit(int row, int column) { clickOnCell(row, column, 2); } /** * Changes text of the cell pointed by row and column indexes. * @param row a row index * @param column a column index * @param newText a text to enter * @deprecated Use changeCellObject(int, int, Object) instead. * @see #changeCellObject(int, int, Object) * @throws TimeoutExpiredException */ public void changeCellText(int row, int column, String newText) { changeCellObject(row, column, newText); } /** * Changes value of the cell pointed by row and column indexes. * uses editor defined by setCellEditor method. * @param row a row index * @param column a column index * @param newValue an object to chenge cell value to. * @throws TimeoutExpiredException */ public void changeCellObject(int row, int column, Object newValue) { driver.editCell(this, row, column, newValue); } /** * Scrolls to a cell if the table lies on a JScrollPane component. * @param row a row index * @param column a column index * @throws TimeoutExpiredException */ public void scrollToCell(int row, int column) { output.printTrace("Scroll JTable to (" + Integer.toString(row) + "," + Integer.toString(column) +") cell\n : " + toStringSource()); output.printGolden("Scroll JTable to (" + Integer.toString(row) + "," + Integer.toString(column) + ")"); makeComponentVisible(); //try to find JScrollPane under. JScrollPane scroll = (JScrollPane)getContainer(new JScrollPaneOperator. JScrollPaneFinder(ComponentSearcher. getTrueChooser("JScrollPane"))); if(scroll == null) { return; } JScrollPaneOperator scroller = new JScrollPaneOperator(scroll); scroller.copyEnvironment(this); scroller.setVisualizer(new EmptyVisualizer()); Rectangle rect = getCellRect(row, column, false); scroller.scrollToComponentRectangle(getSource(), (int)rect.getX(), (int)rect.getY(), (int)rect.getWidth(), (int)rect.getHeight()); } /** * Selects a specified cell. * @param row a row index * @param column a column index */ public void selectCell(int row, int column) { driver.selectCell(this, row, column); } /** * Searches a column by name. * @param name a text pattern * @param comparator a string comparision algorithm * @return a column index */ public int findColumn(String name, StringComparator comparator) { int columnCount = getColumnCount(); for(int i = 0; i < columnCount; i++) { if(comparator.equals(getColumnName(i), name)) { return(i); } } return(-1); } /** * Searches a column by name. * @param name a text pattern * @return a column index */ public int findColumn(String name) { return(findColumn(name, getComparator())); } /** * Calls popup menu on specified cell. * @param row a row index * @param column a column index * @return the menu */ public JPopupMenu callPopupOnCell(int row, int column) { output.printLine("Call popup on (" + row + ", " + column + ") cell"); output.printGolden("Call popup on cell"); makeComponentVisible(); Point point = getPointToClick(row, column); return(JPopupMenuOperator.callPopup(getSource(), (int)point.getX(), (int)point.getY(), getPopupMouseButton())); } //////////////////////////////////////////////////////// //Gets // //////////////////////////////////////////////////////// /** * Ask renderer for component to be displayed. * @param row cell row index. * @param column cell column visible index. * @param isSelected True if the specified cell was selected. * @param cellHasFocus True if the specified cell has the focus. * @return Component to be displayed. */ public Component getRenderedComponent(int row, int column, boolean isSelected, boolean cellHasFocus) { return(getCellRenderer(row, column). getTableCellRendererComponent((JTable)getSource(), getValueAt(row, column), isSelected, cellHasFocus, row, column)); } /** * Ask renderer for component to be displayed. * Uses isCellSelected(itemIndex) to determine whether cell is selected. * Supposes item do not have focus. * @param row cell row index. * @param column cell column visible index. * @return Component to be displayed. */ public Component getRenderedComponent(int row, int column) { return(getRenderedComponent(row, column, isCellSelected(row, column), false)); } /** * Returns a point at the center of the cell rectangle. * @param row a row index * @param column a column index * @return a Point in component's coordinate system. */ public Point getPointToClick(int row, int column) { Rectangle rect = getCellRect(row, column, false); return(new Point((int)(rect.getX() + rect.getWidth() / 2), (int)(rect.getY() + rect.getHeight() / 2))); } /** * Creates an operator for a teble header assigned to this table. * @return an JTableHeaderOperator operator */ public JTableHeaderOperator getHeaderOperator() { return(new JTableHeaderOperator(getTableHeader())); } /** * Waits for an editor. * @param chooser a chhoser specifying criteria to distinguish cell editor. * @param row a row index * @param column a column index * @return a component displayed over the cell and fitting the criteria specified by chooser */ public Component waitCellComponent(ComponentChooser chooser, int row, int column) { CellComponentWaiter waiter = new CellComponentWaiter(chooser, row, column); waiter.setOutput(getOutput()); waiter.setTimeoutsToCloneOf(getTimeouts(), "JTableOperator.WaitEditingTimeout"); try { return((Component)waiter.waitAction(null)); } catch(InterruptedException e) { throw(new JemmyException("Waiting has been interrupted", e)); } } /** * Waits for certain cell contents. * @param cellText Text comparing to cell text by getComparator() comparator. * @param row cell row index. If -1, selected one is checked. * @param column cell column visible index. If -1, selected one is checked. */ public void waitCell(String cellText, int row, int column) { getOutput().printLine("Wait \"" + cellText + "\" text at (" + Integer.toString(row) + "," + Integer.toString(column) + ")" + " position in component \n : "+ toStringSource()); getOutput().printGolden("Wait \"" + cellText + "\" text at (" + Integer.toString(row) + "," + Integer.toString(column) + ")" + " position"); waitState(new JTableByCellFinder(cellText, row, column, getComparator())); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); TableModel model = ((JTable)getSource()).getModel(); int colCount = model.getColumnCount(); int rowCount = model.getRowCount(); String[][] items = new String[rowCount][colCount]; for(int i = 0; i < rowCount; i++) { for(int j = 0; j < colCount; j++) { if(model.getValueAt(i, j) != null) { items[i][j] = model.getValueAt(i, j).toString(); } else { items[i][j] = "null"; } } } addToDump(result, CELL_PREFIX_DPROP, items); String[] columns = new String[colCount]; for(int j = 0; j < colCount; j++) { columns[j] = ((JTable)getSource()).getColumnName(j); } addToDump(result, COLUMN_PREFIX_DPROP, columns); int[] selColNums = ((JTable)getSource()).getSelectedColumns(); String[] selColumns = new String[selColNums.length]; for(int j = 0; j < selColNums.length; j++) { selColumns[j] = Integer.toString(selColNums[j]); } addToDump(result, SELECTED_COLUMN_PREFIX_DPROP, selColumns); int[] selRowNums = ((JTable)getSource()).getSelectedRows(); String[] selRows = new String[selRowNums.length]; for(int i = 0; i < selRowNums.length; i++) { selRows[i] = Integer.toString(selRowNums[i]); } addToDump(result, SELECTED_ROW_PREFIX_DPROP, selRows); result.put(COLUMN_COUNT_DPROP, Integer.toString(colCount)); result.put(ROW_COUNT_DPROP, Integer.toString(rowCount)); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JTable.addColumn(TableColumn) through queue*/ public void addColumn(final TableColumn tableColumn) { runMapping(new MapVoidAction("addColumn") { public void map() { ((JTable)getSource()).addColumn(tableColumn); }});} /**Maps JTable.addColumnSelectionInterval(int, int) through queue*/ public void addColumnSelectionInterval(final int i, final int i1) { runMapping(new MapVoidAction("addColumnSelectionInterval") { public void map() { ((JTable)getSource()).addColumnSelectionInterval(i, i1); }});} /**Maps JTable.addRowSelectionInterval(int, int) through queue*/ public void addRowSelectionInterval(final int i, final int i1) { runMapping(new MapVoidAction("addRowSelectionInterval") { public void map() { ((JTable)getSource()).addRowSelectionInterval(i, i1); }});} /**Maps JTable.clearSelection() through queue*/ public void clearSelection() { runMapping(new MapVoidAction("clearSelection") { public void map() { ((JTable)getSource()).clearSelection(); }});} /**Maps JTable.columnAdded(TableColumnModelEvent) through queue*/ public void columnAdded(final TableColumnModelEvent tableColumnModelEvent) { runMapping(new MapVoidAction("columnAdded") { public void map() { ((JTable)getSource()).columnAdded(tableColumnModelEvent); }});} /**Maps JTable.columnAtPoint(Point) through queue*/ public int columnAtPoint(final Point point) { return(runMapping(new MapIntegerAction("columnAtPoint") { public int map() { return(((JTable)getSource()).columnAtPoint(point)); }}));} /**Maps JTable.columnMarginChanged(ChangeEvent) through queue*/ public void columnMarginChanged(final ChangeEvent changeEvent) { runMapping(new MapVoidAction("columnMarginChanged") { public void map() { ((JTable)getSource()).columnMarginChanged(changeEvent); }});} /**Maps JTable.columnMoved(TableColumnModelEvent) through queue*/ public void columnMoved(final TableColumnModelEvent tableColumnModelEvent) { runMapping(new MapVoidAction("columnMoved") { public void map() { ((JTable)getSource()).columnMoved(tableColumnModelEvent); }});} /**Maps JTable.columnRemoved(TableColumnModelEvent) through queue*/ public void columnRemoved(final TableColumnModelEvent tableColumnModelEvent) { runMapping(new MapVoidAction("columnRemoved") { public void map() { ((JTable)getSource()).columnRemoved(tableColumnModelEvent); }});} /**Maps JTable.columnSelectionChanged(ListSelectionEvent) through queue*/ public void columnSelectionChanged(final ListSelectionEvent listSelectionEvent) { runMapping(new MapVoidAction("columnSelectionChanged") { public void map() { ((JTable)getSource()).columnSelectionChanged(listSelectionEvent); }});} /**Maps JTable.convertColumnIndexToModel(int) through queue*/ public int convertColumnIndexToModel(final int i) { return(runMapping(new MapIntegerAction("convertColumnIndexToModel") { public int map() { return(((JTable)getSource()).convertColumnIndexToModel(i)); }}));} /**Maps JTable.convertColumnIndexToView(int) through queue*/ public int convertColumnIndexToView(final int i) { return(runMapping(new MapIntegerAction("convertColumnIndexToView") { public int map() { return(((JTable)getSource()).convertColumnIndexToView(i)); }}));} /**Maps JTable.createDefaultColumnsFromModel() through queue*/ public void createDefaultColumnsFromModel() { runMapping(new MapVoidAction("createDefaultColumnsFromModel") { public void map() { ((JTable)getSource()).createDefaultColumnsFromModel(); }});} /**Maps JTable.editCellAt(int, int) through queue*/ public boolean editCellAt(final int i, final int i1) { return(runMapping(new MapBooleanAction("editCellAt") { public boolean map() { return(((JTable)getSource()).editCellAt(i, i1)); }}));} /**Maps JTable.editCellAt(int, int, EventObject) through queue*/ public boolean editCellAt(final int i, final int i1, final EventObject eventObject) { return(runMapping(new MapBooleanAction("editCellAt") { public boolean map() { return(((JTable)getSource()).editCellAt(i, i1, eventObject)); }}));} /**Maps JTable.editingCanceled(ChangeEvent) through queue*/ public void editingCanceled(final ChangeEvent changeEvent) { runMapping(new MapVoidAction("editingCanceled") { public void map() { ((JTable)getSource()).editingCanceled(changeEvent); }});} /**Maps JTable.editingStopped(ChangeEvent) through queue*/ public void editingStopped(final ChangeEvent changeEvent) { runMapping(new MapVoidAction("editingStopped") { public void map() { ((JTable)getSource()).editingStopped(changeEvent); }});} /**Maps JTable.getAutoCreateColumnsFromModel() through queue*/ public boolean getAutoCreateColumnsFromModel() { return(runMapping(new MapBooleanAction("getAutoCreateColumnsFromModel") { public boolean map() { return(((JTable)getSource()).getAutoCreateColumnsFromModel()); }}));} /**Maps JTable.getAutoResizeMode() through queue*/ public int getAutoResizeMode() { return(runMapping(new MapIntegerAction("getAutoResizeMode") { public int map() { return(((JTable)getSource()).getAutoResizeMode()); }}));} /**Maps JTable.getCellEditor() through queue*/ public TableCellEditor getCellEditor() { return((TableCellEditor)runMapping(new MapAction("getCellEditor") { public Object map() { return(((JTable)getSource()).getCellEditor()); }}));} /**Maps JTable.getCellEditor(int, int) through queue*/ public TableCellEditor getCellEditor(final int i, final int i1) { return((TableCellEditor)runMapping(new MapAction("getCellEditor") { public Object map() { return(((JTable)getSource()).getCellEditor(i, i1)); }}));} /**Maps JTable.getCellRect(int, int, boolean) through queue*/ public Rectangle getCellRect(final int i, final int i1, final boolean b) { return((Rectangle)runMapping(new MapAction("getCellRect") { public Object map() { return(((JTable)getSource()).getCellRect(i, i1, b)); }}));} /**Maps JTable.getCellRenderer(int, int) through queue*/ public TableCellRenderer getCellRenderer(final int i, final int i1) { return((TableCellRenderer)runMapping(new MapAction("getCellRenderer") { public Object map() { return(((JTable)getSource()).getCellRenderer(i, i1)); }}));} /**Maps JTable.getCellSelectionEnabled() through queue*/ public boolean getCellSelectionEnabled() { return(runMapping(new MapBooleanAction("getCellSelectionEnabled") { public boolean map() { return(((JTable)getSource()).getCellSelectionEnabled()); }}));} /**Maps JTable.getColumn(Object) through queue*/ public TableColumn getColumn(final Object object) { return((TableColumn)runMapping(new MapAction("getColumn") { public Object map() { return(((JTable)getSource()).getColumn(object)); }}));} /**Maps JTable.getColumnClass(int) through queue*/ public Class getColumnClass(final int i) { return((Class)runMapping(new MapAction("getColumnClass") { public Object map() { return(((JTable)getSource()).getColumnClass(i)); }}));} /**Maps JTable.getColumnCount() through queue*/ public int getColumnCount() { return(runMapping(new MapIntegerAction("getColumnCount") { public int map() { return(((JTable)getSource()).getColumnCount()); }}));} /**Maps JTable.getColumnModel() through queue*/ public TableColumnModel getColumnModel() { return((TableColumnModel)runMapping(new MapAction("getColumnModel") { public Object map() { return(((JTable)getSource()).getColumnModel()); }}));} /**Maps JTable.getColumnName(int) through queue*/ public String getColumnName(final int i) { return((String)runMapping(new MapAction("getColumnName") { public Object map() { return(((JTable)getSource()).getColumnName(i)); }}));} /**Maps JTable.getColumnSelectionAllowed() through queue*/ public boolean getColumnSelectionAllowed() { return(runMapping(new MapBooleanAction("getColumnSelectionAllowed") { public boolean map() { return(((JTable)getSource()).getColumnSelectionAllowed()); }}));} /**Maps JTable.getDefaultEditor(Class) through queue*/ public TableCellEditor getDefaultEditor(final Class clss) { return((TableCellEditor)runMapping(new MapAction("getDefaultEditor") { public Object map() { return(((JTable)getSource()).getDefaultEditor(clss)); }}));} /**Maps JTable.getDefaultRenderer(Class) through queue*/ public TableCellRenderer getDefaultRenderer(final Class clss) { return((TableCellRenderer)runMapping(new MapAction("getDefaultRenderer") { public Object map() { return(((JTable)getSource()).getDefaultRenderer(clss)); }}));} /**Maps JTable.getEditingColumn() through queue*/ public int getEditingColumn() { return(runMapping(new MapIntegerAction("getEditingColumn") { public int map() { return(((JTable)getSource()).getEditingColumn()); }}));} /**Maps JTable.getEditingRow() through queue*/ public int getEditingRow() { return(runMapping(new MapIntegerAction("getEditingRow") { public int map() { return(((JTable)getSource()).getEditingRow()); }}));} /**Maps JTable.getEditorComponent() through queue*/ public Component getEditorComponent() { return((Component)runMapping(new MapAction("getEditorComponent") { public Object map() { return(((JTable)getSource()).getEditorComponent()); }}));} /**Maps JTable.getGridColor() through queue*/ public Color getGridColor() { return((Color)runMapping(new MapAction("getGridColor") { public Object map() { return(((JTable)getSource()).getGridColor()); }}));} /**Maps JTable.getIntercellSpacing() through queue*/ public Dimension getIntercellSpacing() { return((Dimension)runMapping(new MapAction("getIntercellSpacing") { public Object map() { return(((JTable)getSource()).getIntercellSpacing()); }}));} /**Maps JTable.getModel() through queue*/ public TableModel getModel() { return((TableModel)runMapping(new MapAction("getModel") { public Object map() { return(((JTable)getSource()).getModel()); }}));} /**Maps JTable.getPreferredScrollableViewportSize() through queue*/ public Dimension getPreferredScrollableViewportSize() { return((Dimension)runMapping(new MapAction("getPreferredScrollableViewportSize") { public Object map() { return(((JTable)getSource()).getPreferredScrollableViewportSize()); }}));} /**Maps JTable.getRowCount() through queue*/ public int getRowCount() { return(runMapping(new MapIntegerAction("getRowCount") { public int map() { return(((JTable)getSource()).getRowCount()); }}));} /**Maps JTable.getRowHeight() through queue*/ public int getRowHeight() { return(runMapping(new MapIntegerAction("getRowHeight") { public int map() { return(((JTable)getSource()).getRowHeight()); }}));} /**Maps JTable.getRowMargin() through queue*/ public int getRowMargin() { return(runMapping(new MapIntegerAction("getRowMargin") { public int map() { return(((JTable)getSource()).getRowMargin()); }}));} /**Maps JTable.getRowSelectionAllowed() through queue*/ public boolean getRowSelectionAllowed() { return(runMapping(new MapBooleanAction("getRowSelectionAllowed") { public boolean map() { return(((JTable)getSource()).getRowSelectionAllowed()); }}));} /**Maps JTable.getScrollableBlockIncrement(Rectangle, int, int) through queue*/ public int getScrollableBlockIncrement(final Rectangle rectangle, final int i, final int i1) { return(runMapping(new MapIntegerAction("getScrollableBlockIncrement") { public int map() { return(((JTable)getSource()).getScrollableBlockIncrement(rectangle, i, i1)); }}));} /**Maps JTable.getScrollableTracksViewportHeight() through queue*/ public boolean getScrollableTracksViewportHeight() { return(runMapping(new MapBooleanAction("getScrollableTracksViewportHeight") { public boolean map() { return(((JTable)getSource()).getScrollableTracksViewportHeight()); }}));} /**Maps JTable.getScrollableTracksViewportWidth() through queue*/ public boolean getScrollableTracksViewportWidth() { return(runMapping(new MapBooleanAction("getScrollableTracksViewportWidth") { public boolean map() { return(((JTable)getSource()).getScrollableTracksViewportWidth()); }}));} /**Maps JTable.getScrollableUnitIncrement(Rectangle, int, int) through queue*/ public int getScrollableUnitIncrement(final Rectangle rectangle, final int i, final int i1) { return(runMapping(new MapIntegerAction("getScrollableUnitIncrement") { public int map() { return(((JTable)getSource()).getScrollableUnitIncrement(rectangle, i, i1)); }}));} /**Maps JTable.getSelectedColumn() through queue*/ public int getSelectedColumn() { return(runMapping(new MapIntegerAction("getSelectedColumn") { public int map() { return(((JTable)getSource()).getSelectedColumn()); }}));} /**Maps JTable.getSelectedColumnCount() through queue*/ public int getSelectedColumnCount() { return(runMapping(new MapIntegerAction("getSelectedColumnCount") { public int map() { return(((JTable)getSource()).getSelectedColumnCount()); }}));} /**Maps JTable.getSelectedColumns() through queue*/ public int[] getSelectedColumns() { return((int[])runMapping(new MapAction("getSelectedColumns") { public Object map() { return(((JTable)getSource()).getSelectedColumns()); }}));} /**Maps JTable.getSelectedRow() through queue*/ public int getSelectedRow() { return(runMapping(new MapIntegerAction("getSelectedRow") { public int map() { return(((JTable)getSource()).getSelectedRow()); }}));} /**Maps JTable.getSelectedRowCount() through queue*/ public int getSelectedRowCount() { return(runMapping(new MapIntegerAction("getSelectedRowCount") { public int map() { return(((JTable)getSource()).getSelectedRowCount()); }}));} /**Maps JTable.getSelectedRows() through queue*/ public int[] getSelectedRows() { return((int[])runMapping(new MapAction("getSelectedRows") { public Object map() { return(((JTable)getSource()).getSelectedRows()); }}));} /**Maps JTable.getSelectionBackground() through queue*/ public Color getSelectionBackground() { return((Color)runMapping(new MapAction("getSelectionBackground") { public Object map() { return(((JTable)getSource()).getSelectionBackground()); }}));} /**Maps JTable.getSelectionForeground() through queue*/ public Color getSelectionForeground() { return((Color)runMapping(new MapAction("getSelectionForeground") { public Object map() { return(((JTable)getSource()).getSelectionForeground()); }}));} /**Maps JTable.getSelectionModel() through queue*/ public ListSelectionModel getSelectionModel() { return((ListSelectionModel)runMapping(new MapAction("getSelectionModel") { public Object map() { return(((JTable)getSource()).getSelectionModel()); }}));} /**Maps JTable.getShowHorizontalLines() through queue*/ public boolean getShowHorizontalLines() { return(runMapping(new MapBooleanAction("getShowHorizontalLines") { public boolean map() { return(((JTable)getSource()).getShowHorizontalLines()); }}));} /**Maps JTable.getShowVerticalLines() through queue*/ public boolean getShowVerticalLines() { return(runMapping(new MapBooleanAction("getShowVerticalLines") { public boolean map() { return(((JTable)getSource()).getShowVerticalLines()); }}));} /**Maps JTable.getTableHeader() through queue*/ public JTableHeader getTableHeader() { return((JTableHeader)runMapping(new MapAction("getTableHeader") { public Object map() { return(((JTable)getSource()).getTableHeader()); }}));} /**Maps JTable.getUI() through queue*/ public TableUI getUI() { return((TableUI)runMapping(new MapAction("getUI") { public Object map() { return(((JTable)getSource()).getUI()); }}));} /**Maps JTable.getValueAt(int, int) through queue*/ public Object getValueAt(final int i, final int i1) { return((Object)runMapping(new MapAction("getValueAt") { public Object map() { return(((JTable)getSource()).getValueAt(i, i1)); }}));} /**Maps JTable.isCellEditable(int, int) through queue*/ public boolean isCellEditable(final int i, final int i1) { return(runMapping(new MapBooleanAction("isCellEditable") { public boolean map() { return(((JTable)getSource()).isCellEditable(i, i1)); }}));} /**Maps JTable.isCellSelected(int, int) through queue*/ public boolean isCellSelected(final int i, final int i1) { return(runMapping(new MapBooleanAction("isCellSelected") { public boolean map() { return(((JTable)getSource()).isCellSelected(i, i1)); }}));} /**Maps JTable.isColumnSelected(int) through queue*/ public boolean isColumnSelected(final int i) { return(runMapping(new MapBooleanAction("isColumnSelected") { public boolean map() { return(((JTable)getSource()).isColumnSelected(i)); }}));} /**Maps JTable.isEditing() through queue*/ public boolean isEditing() { return(runMapping(new MapBooleanAction("isEditing") { public boolean map() { return(((JTable)getSource()).isEditing()); }}));} /**Maps JTable.isRowSelected(int) through queue*/ public boolean isRowSelected(final int i) { return(runMapping(new MapBooleanAction("isRowSelected") { public boolean map() { return(((JTable)getSource()).isRowSelected(i)); }}));} /**Maps JTable.moveColumn(int, int) through queue*/ public void moveColumn(final int i, final int i1) { runMapping(new MapVoidAction("moveColumn") { public void map() { ((JTable)getSource()).moveColumn(i, i1); }});} /**Maps JTable.prepareEditor(TableCellEditor, int, int) through queue*/ public Component prepareEditor(final TableCellEditor tableCellEditor, final int i, final int i1) { return((Component)runMapping(new MapAction("prepareEditor") { public Object map() { return(((JTable)getSource()).prepareEditor(tableCellEditor, i, i1)); }}));} /**Maps JTable.prepareRenderer(TableCellRenderer, int, int) through queue*/ public Component prepareRenderer(final TableCellRenderer tableCellRenderer, final int i, final int i1) { return((Component)runMapping(new MapAction("prepareRenderer") { public Object map() { return(((JTable)getSource()).prepareRenderer(tableCellRenderer, i, i1)); }}));} /**Maps JTable.removeColumn(TableColumn) through queue*/ public void removeColumn(final TableColumn tableColumn) { runMapping(new MapVoidAction("removeColumn") { public void map() { ((JTable)getSource()).removeColumn(tableColumn); }});} /**Maps JTable.removeColumnSelectionInterval(int, int) through queue*/ public void removeColumnSelectionInterval(final int i, final int i1) { runMapping(new MapVoidAction("removeColumnSelectionInterval") { public void map() { ((JTable)getSource()).removeColumnSelectionInterval(i, i1); }});} /**Maps JTable.removeEditor() through queue*/ public void removeEditor() { runMapping(new MapVoidAction("removeEditor") { public void map() { ((JTable)getSource()).removeEditor(); }});} /**Maps JTable.removeRowSelectionInterval(int, int) through queue*/ public void removeRowSelectionInterval(final int i, final int i1) { runMapping(new MapVoidAction("removeRowSelectionInterval") { public void map() { ((JTable)getSource()).removeRowSelectionInterval(i, i1); }});} /**Maps JTable.rowAtPoint(Point) through queue*/ public int rowAtPoint(final Point point) { return(runMapping(new MapIntegerAction("rowAtPoint") { public int map() { return(((JTable)getSource()).rowAtPoint(point)); }}));} /**Maps JTable.selectAll() through queue*/ public void selectAll() { runMapping(new MapVoidAction("selectAll") { public void map() { ((JTable)getSource()).selectAll(); }});} /**Maps JTable.setAutoCreateColumnsFromModel(boolean) through queue*/ public void setAutoCreateColumnsFromModel(final boolean b) { runMapping(new MapVoidAction("setAutoCreateColumnsFromModel") { public void map() { ((JTable)getSource()).setAutoCreateColumnsFromModel(b); }});} /**Maps JTable.setAutoResizeMode(int) through queue*/ public void setAutoResizeMode(final int i) { runMapping(new MapVoidAction("setAutoResizeMode") { public void map() { ((JTable)getSource()).setAutoResizeMode(i); }});} /**Maps JTable.setCellEditor(TableCellEditor) through queue*/ public void setCellEditor(final TableCellEditor tableCellEditor) { runMapping(new MapVoidAction("setCellEditor") { public void map() { ((JTable)getSource()).setCellEditor(tableCellEditor); }});} /**Maps JTable.setCellSelectionEnabled(boolean) through queue*/ public void setCellSelectionEnabled(final boolean b) { runMapping(new MapVoidAction("setCellSelectionEnabled") { public void map() { ((JTable)getSource()).setCellSelectionEnabled(b); }});} /**Maps JTable.setColumnModel(TableColumnModel) through queue*/ public void setColumnModel(final TableColumnModel tableColumnModel) { runMapping(new MapVoidAction("setColumnModel") { public void map() { ((JTable)getSource()).setColumnModel(tableColumnModel); }});} /**Maps JTable.setColumnSelectionAllowed(boolean) through queue*/ public void setColumnSelectionAllowed(final boolean b) { runMapping(new MapVoidAction("setColumnSelectionAllowed") { public void map() { ((JTable)getSource()).setColumnSelectionAllowed(b); }});} /**Maps JTable.setColumnSelectionInterval(int, int) through queue*/ public void setColumnSelectionInterval(final int i, final int i1) { runMapping(new MapVoidAction("setColumnSelectionInterval") { public void map() { ((JTable)getSource()).setColumnSelectionInterval(i, i1); }});} /**Maps JTable.setDefaultEditor(Class, TableCellEditor) through queue*/ public void setDefaultEditor(final Class clss, final TableCellEditor tableCellEditor) { runMapping(new MapVoidAction("setDefaultEditor") { public void map() { ((JTable)getSource()).setDefaultEditor(clss, tableCellEditor); }});} /**Maps JTable.setDefaultRenderer(Class, TableCellRenderer) through queue*/ public void setDefaultRenderer(final Class clss, final TableCellRenderer tableCellRenderer) { runMapping(new MapVoidAction("setDefaultRenderer") { public void map() { ((JTable)getSource()).setDefaultRenderer(clss, tableCellRenderer); }});} /**Maps JTable.setEditingColumn(int) through queue*/ public void setEditingColumn(final int i) { runMapping(new MapVoidAction("setEditingColumn") { public void map() { ((JTable)getSource()).setEditingColumn(i); }});} /**Maps JTable.setEditingRow(int) through queue*/ public void setEditingRow(final int i) { runMapping(new MapVoidAction("setEditingRow") { public void map() { ((JTable)getSource()).setEditingRow(i); }});} /**Maps JTable.setGridColor(Color) through queue*/ public void setGridColor(final Color color) { runMapping(new MapVoidAction("setGridColor") { public void map() { ((JTable)getSource()).setGridColor(color); }});} /**Maps JTable.setIntercellSpacing(Dimension) through queue*/ public void setIntercellSpacing(final Dimension dimension) { runMapping(new MapVoidAction("setIntercellSpacing") { public void map() { ((JTable)getSource()).setIntercellSpacing(dimension); }});} /**Maps JTable.setModel(TableModel) through queue*/ public void setModel(final TableModel tableModel) { runMapping(new MapVoidAction("setModel") { public void map() { ((JTable)getSource()).setModel(tableModel); }});} /**Maps JTable.setPreferredScrollableViewportSize(Dimension) through queue*/ public void setPreferredScrollableViewportSize(final Dimension dimension) { runMapping(new MapVoidAction("setPreferredScrollableViewportSize") { public void map() { ((JTable)getSource()).setPreferredScrollableViewportSize(dimension); }});} /**Maps JTable.setRowHeight(int) through queue*/ public void setRowHeight(final int i) { runMapping(new MapVoidAction("setRowHeight") { public void map() { ((JTable)getSource()).setRowHeight(i); }});} /**Maps JTable.setRowMargin(int) through queue*/ public void setRowMargin(final int i) { runMapping(new MapVoidAction("setRowMargin") { public void map() { ((JTable)getSource()).setRowMargin(i); }});} /**Maps JTable.setRowSelectionAllowed(boolean) through queue*/ public void setRowSelectionAllowed(final boolean b) { runMapping(new MapVoidAction("setRowSelectionAllowed") { public void map() { ((JTable)getSource()).setRowSelectionAllowed(b); }});} /**Maps JTable.setRowSelectionInterval(int, int) through queue*/ public void setRowSelectionInterval(final int i, final int i1) { runMapping(new MapVoidAction("setRowSelectionInterval") { public void map() { ((JTable)getSource()).setRowSelectionInterval(i, i1); }});} /**Maps JTable.setSelectionBackground(Color) through queue*/ public void setSelectionBackground(final Color color) { runMapping(new MapVoidAction("setSelectionBackground") { public void map() { ((JTable)getSource()).setSelectionBackground(color); }});} /**Maps JTable.setSelectionForeground(Color) through queue*/ public void setSelectionForeground(final Color color) { runMapping(new MapVoidAction("setSelectionForeground") { public void map() { ((JTable)getSource()).setSelectionForeground(color); }});} /**Maps JTable.setSelectionMode(int) through queue*/ public void setSelectionMode(final int i) { runMapping(new MapVoidAction("setSelectionMode") { public void map() { ((JTable)getSource()).setSelectionMode(i); }});} /**Maps JTable.setSelectionModel(ListSelectionModel) through queue*/ public void setSelectionModel(final ListSelectionModel listSelectionModel) { runMapping(new MapVoidAction("setSelectionModel") { public void map() { ((JTable)getSource()).setSelectionModel(listSelectionModel); }});} /**Maps JTable.setShowGrid(boolean) through queue*/ public void setShowGrid(final boolean b) { runMapping(new MapVoidAction("setShowGrid") { public void map() { ((JTable)getSource()).setShowGrid(b); }});} /**Maps JTable.setShowHorizontalLines(boolean) through queue*/ public void setShowHorizontalLines(final boolean b) { runMapping(new MapVoidAction("setShowHorizontalLines") { public void map() { ((JTable)getSource()).setShowHorizontalLines(b); }});} /**Maps JTable.setShowVerticalLines(boolean) through queue*/ public void setShowVerticalLines(final boolean b) { runMapping(new MapVoidAction("setShowVerticalLines") { public void map() { ((JTable)getSource()).setShowVerticalLines(b); }});} /**Maps JTable.setTableHeader(JTableHeader) through queue*/ public void setTableHeader(final JTableHeader jTableHeader) { runMapping(new MapVoidAction("setTableHeader") { public void map() { ((JTable)getSource()).setTableHeader(jTableHeader); }});} /**Maps JTable.setUI(TableUI) through queue*/ public void setUI(final TableUI tableUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JTable)getSource()).setUI(tableUI); }});} /**Maps JTable.setValueAt(Object, int, int) through queue*/ public void setValueAt(final Object object, final int i, final int i1) { runMapping(new MapVoidAction("setValueAt") { public void map() { ((JTable)getSource()).setValueAt(object, i, i1); }});} /**Maps JTable.tableChanged(TableModelEvent) through queue*/ public void tableChanged(final TableModelEvent tableModelEvent) { runMapping(new MapVoidAction("tableChanged") { public void map() { ((JTable)getSource()).tableChanged(tableModelEvent); }});} /**Maps JTable.valueChanged(ListSelectionEvent) through queue*/ public void valueChanged(final ListSelectionEvent listSelectionEvent) { runMapping(new MapVoidAction("valueChanged") { public void map() { ((JTable)getSource()).valueChanged(listSelectionEvent); }});} //End of mapping // //////////////////////////////////////////////////////// private Point findCell(String text, boolean ce, boolean ccs, int index) { return(findCell(text, new DefaultStringComparator(ce, ccs), index)); } /** * Iterface to choose table cell. */ public interface TableCellChooser { /** * Should be true if item is good. * @param oper Operator used to search item. * @param row Row be checked. * @param column Column be checked. * @return true if cell fits the criteria */ public boolean checkCell(JTableOperator oper, int row, int column); /** * Item description. * @return the description. */ public String getDescription(); } private class BySubStringTableCellChooser implements TableCellChooser { String subString; StringComparator comparator; public BySubStringTableCellChooser(String subString, StringComparator comparator) { this.subString = subString; this.comparator = comparator; } public boolean checkCell(JTableOperator oper, int row, int column) { Object value = ((JTable)oper.getSource()).getModel().getValueAt(row, column); return(comparator.equals((value != null) ? value.toString() : null, subString)); } public String getDescription() { return("Cell containing \"" + subString + "\" string"); } } private class ByRenderedComponentTableCellChooser implements TableCellChooser { ComponentChooser chooser; public ByRenderedComponentTableCellChooser(ComponentChooser chooser) { this.chooser = chooser; } public boolean checkCell(JTableOperator oper, int row, int column) { return(chooser.checkComponent(oper.getRenderedComponent(row, column))); } public String getDescription() { return(chooser.getDescription()); } } /** * Allows to find component by cell text. */ public static class JTableByCellFinder implements ComponentChooser { String label; int row; int column; StringComparator comparator; /** * Constructs JTableByCellFinder. * @param lb a text pattern * @param r a row index to look in. If equal to -1, selected row is checked. * @param c a column index to look in. If equal to -1, selected column is checked. * @param comparator specifies string comparision algorithm. */ public JTableByCellFinder(String lb, int r, int c, StringComparator comparator) { label = lb; row = r; column = c; this.comparator = comparator; } /** * Constructs JTableByCellFinder. * @param lb a text pattern * @param r a row index to look in. If equal to -1, selected row is checked. * @param c a column index to look in. If equal to -1, selected column is checked. */ public JTableByCellFinder(String lb, int r, int c) { this(lb, r, c, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JTable) { if(label == null) { return(true); } if(((JTable)comp).getRowCount() > row && ((JTable)comp).getColumnCount() > column) { int r = row; if(r == -1) { int[] rows = ((JTable)comp).getSelectedRows(); if(rows.length != 0) { r = rows[0]; } else { return(false); } } int c = column; if(c == -1) { int[] columns = ((JTable)comp).getSelectedColumns(); if(columns.length != 0) { c = columns[0]; } else { return(false); } } Object value = ((JTable)comp).getValueAt(r, c); if(value == null) { return(false); } return(comparator.equals(value.toString(), label)); } } return(false); } public String getDescription() { return("JTable with text \"" + label + "\" in (" + (new Integer(row)).toString() + ", " + (new Integer(column)).toString() + ") cell"); } } /** * Checks component type. */ public static class JTableFinder extends Finder { /** * Constructs JTableFinder. * @param sf other searching criteria. */ public JTableFinder(ComponentChooser sf) { super(JTable.class, sf); } /** * Constructs JTableFinder. */ public JTableFinder() { super(JTable.class); } } private class CellComponentWaiter extends Waiter { private ComponentChooser chooser; private int row, column; public CellComponentWaiter(ComponentChooser chooser, int row, int column) { this.chooser = chooser; this.row = row; this.column = column; } public Object actionProduced(Object obj) { Point pnt = getPointToClick(row, column); Component comp = getComponentAt(pnt.x, pnt.y); if(comp != null && chooser.checkComponent(comp)) { return(comp); } else { return(null); } } public String getDescription() { return(chooser.getDescription()); } } } Jemmy2/src/org/netbeans/jemmy/operators/JTextFieldOperator.java0000644000175000017500000003463111245712237023675 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Container; import java.awt.event.ActionListener; import javax.swing.BoundedRangeModel; import javax.swing.JTextField; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.TimeoutExpiredException; /** *

Timeouts used:
* JTextComponentOperator.PushKeyTimeout - time between key pressing and releasing during text typing
* JTextComponentOperator.BetweenKeysTimeout - time to sleep between two chars typing
* JTextComponentOperator.ChangeCaretPositionTimeout - maximum time to chenge caret position
* JTextComponentOperator.TypeTextTimeout - maximum time to type text
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.WaitFocusTimeout - time to wait component focus
* JScrollBarOperator.OneScrollClickTimeout - time for one scroll click
* JScrollBarOperator.WholeScrollTimeout - time for the whole scrolling
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JTextFieldOperator extends JTextComponentOperator{ /** * Constructor. * @param b a component */ public JTextFieldOperator(JTextField b) { super(b); } /** * Constructs a JTextFieldOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JTextFieldOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JTextField)cont. waitSubComponent(new JTextFieldFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JTextFieldOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JTextFieldOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTextFieldOperator(ContainerOperator cont, String text, int index) { this((JTextField) waitComponent(cont, new JTextFieldFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, cont.getComparator())), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTextFieldOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JTextFieldOperator(ContainerOperator cont, int index) { this((JTextField) waitComponent(cont, new JTextFieldFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JTextFieldOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JTextField in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JTextField instance or null if component was not found. */ public static JTextField findJTextField(Container cont, ComponentChooser chooser, int index) { return((JTextField)findJTextComponent(cont, new JTextFieldFinder(chooser), index)); } /** * Searches JTextField in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JTextField instance or null if component was not found. */ public static JTextField findJTextField(Container cont, ComponentChooser chooser) { return(findJTextField(cont, chooser, 0)); } /** * Searches JTextField by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JTextField instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTextField findJTextField(Container cont, String text, boolean ce, boolean ccs, int index) { return(findJTextField(cont, new JTextFieldFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Searches JTextField by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JTextField instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTextField findJTextField(Container cont, String text, boolean ce, boolean ccs) { return(findJTextField(cont, text, ce, ccs, 0)); } /** * Waits JTextField in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JTextField instance. * @throws TimeoutExpiredException */ public static JTextField waitJTextField(Container cont, ComponentChooser chooser, int index){ return((JTextField)waitJTextComponent(cont, new JTextFieldFinder(chooser), index)); } /** * Waits JTextField in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JTextField instance. * @throws TimeoutExpiredException */ public static JTextField waitJTextField(Container cont, ComponentChooser chooser) { return(waitJTextField(cont, chooser, 0)); } /** * Waits JTextField by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JTextField instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JTextField waitJTextField(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitJTextField(cont, new JTextFieldFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Waits JTextField by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JTextField instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JTextField waitJTextField(Container cont, String text, boolean ce, boolean ccs) { return(waitJTextField(cont, text, ce, ccs, 0)); } /** * Wait some text to be displayed starting from certain position. * @param text a text to wait. * @param position start position. */ public void waitText(String text, int position) { super.waitText(removeNewLines(text), position); } /** * Wait some text to be displayed. * @param text a text to wait. */ public void waitText(String text) { super.waitText(removeNewLines(text)); } //////////////////////////////////////////////////////// //Mapping // /**Maps JTextField.addActionListener(ActionListener) through queue*/ public void addActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("addActionListener") { public void map() { ((JTextField)getSource()).addActionListener(actionListener); }});} /**Maps JTextField.getColumns() through queue*/ public int getColumns() { return(runMapping(new MapIntegerAction("getColumns") { public int map() { return(((JTextField)getSource()).getColumns()); }}));} /**Maps JTextField.getHorizontalAlignment() through queue*/ public int getHorizontalAlignment() { return(runMapping(new MapIntegerAction("getHorizontalAlignment") { public int map() { return(((JTextField)getSource()).getHorizontalAlignment()); }}));} /**Maps JTextField.getHorizontalVisibility() through queue*/ public BoundedRangeModel getHorizontalVisibility() { return((BoundedRangeModel)runMapping(new MapAction("getHorizontalVisibility") { public Object map() { return(((JTextField)getSource()).getHorizontalVisibility()); }}));} /**Maps JTextField.getScrollOffset() through queue*/ public int getScrollOffset() { return(runMapping(new MapIntegerAction("getScrollOffset") { public int map() { return(((JTextField)getSource()).getScrollOffset()); }}));} /**Maps JTextField.postActionEvent() through queue*/ public void postActionEvent() { runMapping(new MapVoidAction("postActionEvent") { public void map() { ((JTextField)getSource()).postActionEvent(); }});} /**Maps JTextField.removeActionListener(ActionListener) through queue*/ public void removeActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("removeActionListener") { public void map() { ((JTextField)getSource()).removeActionListener(actionListener); }});} /**Maps JTextField.setActionCommand(String) through queue*/ public void setActionCommand(final String string) { runMapping(new MapVoidAction("setActionCommand") { public void map() { ((JTextField)getSource()).setActionCommand(string); }});} /**Maps JTextField.setColumns(int) through queue*/ public void setColumns(final int i) { runMapping(new MapVoidAction("setColumns") { public void map() { ((JTextField)getSource()).setColumns(i); }});} /**Maps JTextField.setHorizontalAlignment(int) through queue*/ public void setHorizontalAlignment(final int i) { runMapping(new MapVoidAction("setHorizontalAlignment") { public void map() { ((JTextField)getSource()).setHorizontalAlignment(i); }});} /**Maps JTextField.setScrollOffset(int) through queue*/ public void setScrollOffset(final int i) { runMapping(new MapVoidAction("setScrollOffset") { public void map() { ((JTextField)getSource()).setScrollOffset(i); }});} //End of mapping // //////////////////////////////////////////////////////// private String removeNewLines(String text) { StringBuffer buff = new StringBuffer(text); int i = 0; while(i < buff.length()) { if(buff.charAt(i) != '\n') { i++; } else { buff.deleteCharAt(i); } } return(buff.toString()); } /** * Checks component type. */ public static class JTextFieldFinder extends Finder { /** * Constructs JTextFieldFinder. * @param sf other searching criteria. */ public JTextFieldFinder(ComponentChooser sf) { super(JTextField.class, sf); } /** * Constructs JTextFieldFinder. */ public JTextFieldFinder() { super(JTextField.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JLabelOperator.java0000644000175000017500000004176411245712237023031 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.util.Hashtable; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.plaf.LabelUI; import org.netbeans.jemmy.ComponentChooser; /** *

Timeouts used:
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.WaitStateTimeout - time to wait for text
. * * @see org.netbeans.jemmy.Timeouts * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JLabelOperator extends JComponentOperator { /** * Identifier for a "text" property. * @see #getDump */ public static final String TEXT_DPROP = "Text"; /** * Constructor. * @param b a component */ public JLabelOperator(JLabel b) { super(b); } /** * Constructs a JLabelOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JLabelOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JLabel)cont. waitSubComponent(new JLabelFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JLabelOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JLabelOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public JLabelOperator(ContainerOperator cont, String text, int index) { this((JLabel)waitComponent(cont, new JLabelByLabelFinder(text, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public JLabelOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * */ public JLabelOperator(ContainerOperator cont, int index) { this((JLabel) waitComponent(cont, new JLabelFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * */ public JLabelOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JLabel in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JLabel instance or null if component was not found. */ public static JLabel findJLabel(Container cont, ComponentChooser chooser, int index) { return((JLabel)findComponent(cont, new JLabelFinder(chooser), index)); } /** * Searches JLabel in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JLabel instance or null if component was not found. */ public static JLabel findJLabel(Container cont, ComponentChooser chooser) { return(findJLabel(cont, chooser, 0)); } /** * Searches JLabel by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JLabel instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JLabel findJLabel(Container cont, String text, boolean ce, boolean ccs, int index) { return(findJLabel(cont, new JLabelByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches JLabel by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JLabel instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JLabel findJLabel(Container cont, String text, boolean ce, boolean ccs) { return(findJLabel(cont, text, ce, ccs, 0)); } /** * Waits JLabel in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JLabel instance. * */ public static JLabel waitJLabel(final Container cont, final ComponentChooser chooser, final int index) { return((JLabel)waitComponent(cont, new JLabelFinder(chooser), index)); } /** * Waits JLabel in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JLabel instance. * */ public static JLabel waitJLabel(Container cont, ComponentChooser chooser) { return(waitJLabel(cont, chooser, 0)); } /** * Waits JLabel by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JLabel instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public static JLabel waitJLabel(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitJLabel(cont, new JLabelByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits JLabel by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JLabel instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public static JLabel waitJLabel(Container cont, String text, boolean ce, boolean ccs) { return(waitJLabel(cont, text, ce, ccs, 0)); } /** * Waits for text. Uses getComparator() comparator. * @param text Text to wait for. */ public void waitText(String text) { getOutput().printLine("Wait \"" + text + "\" text in component \n : "+ toStringSource()); getOutput().printGolden("Wait \"" + text + "\" text"); waitState(new JLabelByLabelFinder(text, getComparator())); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); if(((JLabel)getSource()).getText() != null) { result.put(TEXT_DPROP, ((JLabel)getSource()).getText()); } else { result.put(TEXT_DPROP, "null"); } return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JLabel.getDisabledIcon() through queue*/ public Icon getDisabledIcon() { return((Icon)runMapping(new MapAction("getDisabledIcon") { public Object map() { return(((JLabel)getSource()).getDisabledIcon()); }}));} /**Maps JLabel.getDisplayedMnemonic() through queue*/ public int getDisplayedMnemonic() { return(runMapping(new MapIntegerAction("getDisplayedMnemonic") { public int map() { return(((JLabel)getSource()).getDisplayedMnemonic()); }}));} /**Maps JLabel.getHorizontalAlignment() through queue*/ public int getHorizontalAlignment() { return(runMapping(new MapIntegerAction("getHorizontalAlignment") { public int map() { return(((JLabel)getSource()).getHorizontalAlignment()); }}));} /**Maps JLabel.getHorizontalTextPosition() through queue*/ public int getHorizontalTextPosition() { return(runMapping(new MapIntegerAction("getHorizontalTextPosition") { public int map() { return(((JLabel)getSource()).getHorizontalTextPosition()); }}));} /**Maps JLabel.getIcon() through queue*/ public Icon getIcon() { return((Icon)runMapping(new MapAction("getIcon") { public Object map() { return(((JLabel)getSource()).getIcon()); }}));} /**Maps JLabel.getIconTextGap() through queue*/ public int getIconTextGap() { return(runMapping(new MapIntegerAction("getIconTextGap") { public int map() { return(((JLabel)getSource()).getIconTextGap()); }}));} /**Maps JLabel.getLabelFor() through queue*/ public Component getLabelFor() { return((Component)runMapping(new MapAction("getLabelFor") { public Object map() { return(((JLabel)getSource()).getLabelFor()); }}));} /**Maps JLabel.getText() through queue*/ public String getText() { return((String)runMapping(new MapAction("getText") { public Object map() { return(((JLabel)getSource()).getText()); }}));} /**Maps JLabel.getUI() through queue*/ public LabelUI getUI() { return((LabelUI)runMapping(new MapAction("getUI") { public Object map() { return(((JLabel)getSource()).getUI()); }}));} /**Maps JLabel.getVerticalAlignment() through queue*/ public int getVerticalAlignment() { return(runMapping(new MapIntegerAction("getVerticalAlignment") { public int map() { return(((JLabel)getSource()).getVerticalAlignment()); }}));} /**Maps JLabel.getVerticalTextPosition() through queue*/ public int getVerticalTextPosition() { return(runMapping(new MapIntegerAction("getVerticalTextPosition") { public int map() { return(((JLabel)getSource()).getVerticalTextPosition()); }}));} /**Maps JLabel.setDisabledIcon(Icon) through queue*/ public void setDisabledIcon(final Icon icon) { runMapping(new MapVoidAction("setDisabledIcon") { public void map() { ((JLabel)getSource()).setDisabledIcon(icon); }});} /**Maps JLabel.setDisplayedMnemonic(char) through queue*/ public void setDisplayedMnemonic(final char c) { runMapping(new MapVoidAction("setDisplayedMnemonic") { public void map() { ((JLabel)getSource()).setDisplayedMnemonic(c); }});} /**Maps JLabel.setDisplayedMnemonic(int) through queue*/ public void setDisplayedMnemonic(final int i) { runMapping(new MapVoidAction("setDisplayedMnemonic") { public void map() { ((JLabel)getSource()).setDisplayedMnemonic(i); }});} /**Maps JLabel.setHorizontalAlignment(int) through queue*/ public void setHorizontalAlignment(final int i) { runMapping(new MapVoidAction("setHorizontalAlignment") { public void map() { ((JLabel)getSource()).setHorizontalAlignment(i); }});} /**Maps JLabel.setHorizontalTextPosition(int) through queue*/ public void setHorizontalTextPosition(final int i) { runMapping(new MapVoidAction("setHorizontalTextPosition") { public void map() { ((JLabel)getSource()).setHorizontalTextPosition(i); }});} /**Maps JLabel.setIcon(Icon) through queue*/ public void setIcon(final Icon icon) { runMapping(new MapVoidAction("setIcon") { public void map() { ((JLabel)getSource()).setIcon(icon); }});} /**Maps JLabel.setIconTextGap(int) through queue*/ public void setIconTextGap(final int i) { runMapping(new MapVoidAction("setIconTextGap") { public void map() { ((JLabel)getSource()).setIconTextGap(i); }});} /**Maps JLabel.setLabelFor(Component) through queue*/ public void setLabelFor(final Component component) { runMapping(new MapVoidAction("setLabelFor") { public void map() { ((JLabel)getSource()).setLabelFor(component); }});} /**Maps JLabel.setText(String) through queue*/ public void setText(final String string) { runMapping(new MapVoidAction("setText") { public void map() { ((JLabel)getSource()).setText(string); }});} /**Maps JLabel.setUI(LabelUI) through queue*/ public void setUI(final LabelUI labelUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JLabel)getSource()).setUI(labelUI); }});} /**Maps JLabel.setVerticalAlignment(int) through queue*/ public void setVerticalAlignment(final int i) { runMapping(new MapVoidAction("setVerticalAlignment") { public void map() { ((JLabel)getSource()).setVerticalAlignment(i); }});} /**Maps JLabel.setVerticalTextPosition(int) through queue*/ public void setVerticalTextPosition(final int i) { runMapping(new MapVoidAction("setVerticalTextPosition") { public void map() { ((JLabel)getSource()).setVerticalTextPosition(i); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Allows to find component by text. */ public static class JLabelByLabelFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs JLabelByLabelFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public JLabelByLabelFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs JLabelByLabelFinder. * @param lb a text pattern */ public JLabelByLabelFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JLabel) { if(((JLabel)comp).getText() != null) { return(comparator.equals(((JLabel)comp).getText(), label)); } } return(false); } public String getDescription() { return("JLabel with text \"" + label + "\""); } } /** * Checks component type. */ public static class JLabelFinder extends Finder { /** * Constructs JLabelFinder. * @param sf other searching criteria. */ public JLabelFinder(ComponentChooser sf) { super(JLabel.class, sf); } /** * Constructs JLabelFinder. */ public JLabelFinder() { super(JLabel.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/ScrollPaneOperator.java0000644000175000017500000006376111245712237023743 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Adjustable; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Point; import java.awt.ScrollPane; import javax.swing.SwingUtilities; import org.netbeans.jemmy.Action; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.ScrollDriver; import org.netbeans.jemmy.drivers.scrolling.ScrollAdjuster; /** *

Timeouts used:
* ScrollbarOperator.WholeScrollTimeout - time for one scroll click
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class ScrollPaneOperator extends ContainerOperator implements Timeoutable, Outputable { private static int X_POINT_RECT_SIZE = 6; private static int Y_POINT_RECT_SIZE = 4; private Timeouts timeouts; private TestOut output; private ScrollDriver driver; /** * Constructor. * @param b The java.awt.ScrollPane managed by * this instance. */ public ScrollPaneOperator(ScrollPane b) { super(b); driver = DriverManager.getScrollDriver(getClass()); } /** * Constructs a ScrollPaneOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public ScrollPaneOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((ScrollPane)cont. waitSubComponent(new ScrollPaneFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a ScrollPaneOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public ScrollPaneOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @param index Ordinal component index. * @throws TimeoutExpiredException */ public ScrollPaneOperator(ContainerOperator cont, int index) { this((ScrollPane)waitComponent(cont, new ScrollPaneFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @throws TimeoutExpiredException */ public ScrollPaneOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches ScrollPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return ScrollPane instance or null if component was not found. */ public static ScrollPane findScrollPane(Container cont, ComponentChooser chooser, int index) { return((ScrollPane)findComponent(cont, new ScrollPaneFinder(chooser), index)); } /** * Searches 0'th ScrollPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return ScrollPane instance or null if component was not found. */ public static ScrollPane findScrollPane(Container cont, ComponentChooser chooser) { return(findScrollPane(cont, chooser, 0)); } /** * Searches ScrollPane in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return ScrollPane instance or null if component was not found. */ public static ScrollPane findScrollPane(Container cont, int index) { return(findScrollPane(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th ScrollPane instance"), index)); } /** * Searches 0'th ScrollPane in container. * @param cont Container to search component in. * @return ScrollPane instance or null if component was not found. */ public static ScrollPane findScrollPane(Container cont) { return(findScrollPane(cont, 0)); } /** * Searches ScrollPane object which component lies on. * @param comp Component to find ScrollPane under. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return ScrollPane instance or null if component was not found. */ public static ScrollPane findScrollPaneUnder(Component comp, ComponentChooser chooser) { return((ScrollPane)findContainerUnder(comp, new ScrollPaneFinder(chooser))); } /** * Searches ScrollPane object which component lies on. * @param comp Component to find ScrollPane under. * @return ScrollPane instance or null if component was not found. */ public static ScrollPane findScrollPaneUnder(Component comp) { return(findScrollPaneUnder(comp, new ScrollPaneFinder())); } /** * Waits ScrollPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return ScrollPane instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static ScrollPane waitScrollPane(Container cont, ComponentChooser chooser, int index) { return((ScrollPane)waitComponent(cont, new ScrollPaneFinder(chooser), index)); } /** * Waits 0'th ScrollPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return ScrollPane instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static ScrollPane waitScrollPane(Container cont, ComponentChooser chooser) { return(waitScrollPane(cont, chooser, 0)); } /** * Waits ScrollPane in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return ScrollPane instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static ScrollPane waitScrollPane(Container cont, int index) { return(waitScrollPane(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th ScrollPane instance"), index)); } /** * Waits 0'th ScrollPane in container. * @param cont Container to search component in. * @return ScrollPane instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static ScrollPane waitScrollPane(Container cont) { return(waitScrollPane(cont, 0)); } static { try { Class.forName("org.netbeans.jemmy.operators.ScrollbarOperator"); } catch(Exception e) { throw(new JemmyException("Exception", e)); } } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (ScrollDriver)DriverManager. getDriver(DriverManager.SCROLL_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Sets both values. * @param x a horizontal value. * @param y a vertical value. */ public void setValues(int x, int y) { getHAdjustable().setValue(x); getVAdjustable().setValue(y); } /** * Scrools to the position defined by a ScrollAdjuster instance. * @param adj specifies the position. */ public void scrollTo(final ScrollAdjuster adj) { produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scroll(ScrollPaneOperator.this, adj); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("ScrollbarOperator.WholeScrollTimeout")); } /** * Scrolls horizontal scroll bar. * @param value Value to scroll horizontal scroll bar to. * @throws TimeoutExpiredException */ public void scrollToHorizontalValue(final int value) { output.printTrace("Scroll ScrollPane to " + Integer.toString(value) + " horizontal value \n" + toStringSource()); output.printGolden("Scroll ScrollPane to " + Integer.toString(value) + " horizontal value"); scrollTo(new ValueScrollAdjuster(value, Adjustable.HORIZONTAL, getHAdjustable())); } /** * Scrolls horizontal scroll bar. * @param proportionalValue Proportional value to scroll horizontal scroll bar to. * @throws TimeoutExpiredException */ public void scrollToHorizontalValue(double proportionalValue) { output.printTrace("Scroll ScrollPane to " + Double.toString(proportionalValue) + " proportional horizontal value \n" + toStringSource()); output.printGolden("Scroll ScrollPane to " + Double.toString(proportionalValue) + " proportional horizontal value"); Adjustable adj = getHAdjustable(); scrollTo(new ValueScrollAdjuster((int)(adj.getMinimum() + (adj.getMaximum() - adj.getVisibleAmount() - adj.getMinimum()) * proportionalValue), Adjustable.VERTICAL, getVAdjustable())); } /** * Scrolls vertical scroll bar. * @param value Value to scroll vertical scroll bar to. * @throws TimeoutExpiredException */ public void scrollToVerticalValue(final int value) { output.printTrace("Scroll ScrollPane to " + Integer.toString(value) + " vertical value \n" + toStringSource()); output.printGolden("Scroll ScrollPane to " + Integer.toString(value) + " vertical value"); scrollTo(new ValueScrollAdjuster(value, Adjustable.VERTICAL, getVAdjustable())); } /** * Scrolls vertical scroll bar. * @param proportionalValue Value to scroll vertical scroll bar to. * @throws TimeoutExpiredException */ public void scrollToVerticalValue(double proportionalValue) { output.printTrace("Scroll ScrollPane to " + Double.toString(proportionalValue) + " proportional vertical value \n" + toStringSource()); output.printGolden("Scroll ScrollPane to " + Double.toString(proportionalValue) + " proportional vertical value"); Adjustable adj = getVAdjustable(); scrollTo(new ValueScrollAdjuster((int)(adj.getMinimum() + (adj.getMaximum() - adj.getVisibleAmount() - adj.getMinimum()) * proportionalValue), Adjustable.VERTICAL, getVAdjustable())); } /** * Scrolls both scroll bars. * @param valueX Value to scroll horizontal scroll bar to. * @param valueY Value to scroll vertical scroll bar to. * @throws TimeoutExpiredException */ public void scrollToValues(int valueX, int valueY) { scrollToVerticalValue(valueX); scrollToHorizontalValue(valueX); } /** * Scrolls both scroll bars. * @param proportionalValueX Value to scroll horizontal scroll bar to. * @param proportionalValueY Value to scroll vertical scroll bar to. * @throws TimeoutExpiredException */ public void scrollToValues(double proportionalValueX, double proportionalValueY) { scrollToVerticalValue(proportionalValueX); scrollToHorizontalValue(proportionalValueY); } /** * Scrolls pane to top. * @throws TimeoutExpiredException */ public void scrollToTop() { output.printTrace("Scroll ScrollPane to top\n" + toStringSource()); output.printGolden("Scroll ScrollPane to top"); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scrollToMinimum(ScrollPaneOperator.this, Adjustable.VERTICAL); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("ScrollbarOperator.WholeScrollTimeout")); } /** * Scrolls pane to bottom. * @throws TimeoutExpiredException */ public void scrollToBottom() { output.printTrace("Scroll ScrollPane to bottom\n" + toStringSource()); output.printGolden("Scroll ScrollPane to bottom"); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scrollToMaximum(ScrollPaneOperator.this, Adjustable.VERTICAL); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("ScrollbarOperator.WholeScrollTimeout")); } /** * Scrolls pane to left. * @throws TimeoutExpiredException */ public void scrollToLeft() { output.printTrace("Scroll ScrollPane to left\n" + toStringSource()); output.printGolden("Scroll ScrollPane to left"); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scrollToMinimum(ScrollPaneOperator.this, Adjustable.HORIZONTAL); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("ScrollbarOperator.WholeScrollTimeout")); } /** * Scrolls pane to right. * @throws TimeoutExpiredException */ public void scrollToRight() { output.printTrace("Scroll ScrollPane to right\n" + toStringSource()); output.printGolden("Scroll ScrollPane to right"); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scrollToMaximum(ScrollPaneOperator.this, Adjustable.HORIZONTAL); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("ScrollbarOperator.WholeScrollTimeout")); } /** * Scrolls pane to rectangle.. * @param comp a subcomponent defining coordinate system. * @param x coordinate * @param y coordinate * @param width rectangle width * @param height rectangle height * @throws TimeoutExpiredException */ public void scrollToComponentRectangle(Component comp, int x, int y, int width, int height) { scrollTo(new ComponentRectChecker(comp, x, y, width, height, Adjustable.HORIZONTAL)); scrollTo(new ComponentRectChecker(comp, x, y, width, height, Adjustable.VERTICAL)); } /** * Scrolls pane to point. * @param comp a subcomponent defining coordinate system. * @param x coordinate * @param y coordinate * @throws TimeoutExpiredException */ public void scrollToComponentPoint(Component comp, int x, int y) { scrollToComponentRectangle(comp, x - X_POINT_RECT_SIZE, y - Y_POINT_RECT_SIZE, 2 * X_POINT_RECT_SIZE, 2 * Y_POINT_RECT_SIZE); } /** * Scrolls pane to component on this pane. * Component should lay on the ScrollPane view. * @param comp Component to scroll to. * @throws TimeoutExpiredException */ public void scrollToComponent(final Component comp) { String componentToString = (String)runMapping( new Operator.MapAction("comp.toString()") { public Object map() { return comp.toString(); } } ); output.printTrace("Scroll ScrollPane " + toStringSource() + "\nto component " + componentToString); output.printGolden("Scroll ScrollPane to " + comp.getClass().getName() + " component."); scrollToComponentRectangle(comp, 0, 0, comp.getWidth(), comp.getHeight()); } /** * Checks if component's rectangle is inside view port (no scrolling necessary). * @param comp a subcomponent defining coordinate system. * @param x coordinate * @param y coordinate * @param width rectangle width * @param height rectangle height * @return true if pointed subcomponent rectangle is inside the scrolling area. */ public boolean checkInside(Component comp, int x, int y, int width, int height) { Point toPoint = SwingUtilities. convertPoint(comp, x, y, getSource()); if(toPoint.x < getHAdjustable().getValue()) { return(false); } if(comp.getWidth() > getSource().getWidth()) { if(toPoint.x > 0) { return(false); } } else { if(toPoint.x + comp.getWidth() > getHAdjustable().getValue() + getSource().getWidth()) { return(false); } } if(toPoint.y < getVAdjustable().getValue()) { return(false); } if(comp.getHeight() > getSource().getHeight()) { if(toPoint.y > 0) { return(false); } } else { if(toPoint.y + comp.getHeight() > getVAdjustable().getValue() + getSource().getHeight()) { return(false); } } return(true); } /** * Checks if component is inside view port (no scrolling necessary). * @param comp a subcomponent defining coordinate system. * @return true if pointed subcomponent is inside the scrolling area. */ public boolean checkInside(Component comp) { return(checkInside(comp, 0, 0, comp.getWidth(), comp.getHeight())); } /** * Tells if a scrollbar is visible. * @param orientation Adjustable.HORIZONTAL or Adjustable.VERTICAL * @return trus if the bar is visible. */ public boolean isScrollbarVisible(int orientation) { if (orientation == Adjustable.HORIZONTAL) { return(getViewportSize().getHeight() < getHeight() - getHScrollbarHeight()); } else if(orientation == Adjustable.VERTICAL) { return(getViewportSize().getWidth() < getWidth() - getVScrollbarWidth()); } else { return(false); } } //////////////////////////////////////////////////////// //Mapping // /**Maps ScrollPane.getHAdjustable() through queue*/ public Adjustable getHAdjustable() { return((Adjustable)runMapping(new MapAction("getHAdjustable") { public Object map() { return(((ScrollPane)getSource()).getHAdjustable()); }}));} /**Maps ScrollPane.getHScrollbarHeight() through queue*/ public int getHScrollbarHeight() { return(runMapping(new MapIntegerAction("getHScrollbarHeight") { public int map() { return(((ScrollPane)getSource()).getHScrollbarHeight()); }}));} /**Maps ScrollPane.getScrollPosition() through queue*/ public Point getScrollPosition() { return((Point)runMapping(new MapAction("getScrollPosition") { public Object map() { return(((ScrollPane)getSource()).getScrollPosition()); }}));} /**Maps ScrollPane.getScrollbarDisplayPolicy() through queue*/ public int getScrollbarDisplayPolicy() { return(runMapping(new MapIntegerAction("getScrollbarDisplayPolicy") { public int map() { return(((ScrollPane)getSource()).getScrollbarDisplayPolicy()); }}));} /**Maps ScrollPane.getVAdjustable() through queue*/ public Adjustable getVAdjustable() { return((Adjustable)runMapping(new MapAction("getVAdjustable") { public Object map() { return(((ScrollPane)getSource()).getVAdjustable()); }}));} /**Maps ScrollPane.getVScrollbarWidth() through queue*/ public int getVScrollbarWidth() { return(runMapping(new MapIntegerAction("getVScrollbarWidth") { public int map() { return(((ScrollPane)getSource()).getVScrollbarWidth()); }}));} /**Maps ScrollPane.getViewportSize() through queue*/ public Dimension getViewportSize() { return((Dimension)runMapping(new MapAction("getViewportSize") { public Object map() { return(((ScrollPane)getSource()).getViewportSize()); }}));} /**Maps ScrollPane.paramString() through queue*/ public String paramString() { return((String)runMapping(new MapAction("paramString") { public Object map() { return(((ScrollPane)getSource()).paramString()); }}));} /**Maps ScrollPane.setScrollPosition(int, int) through queue*/ public void setScrollPosition(final int i, final int i1) { runMapping(new MapVoidAction("setScrollPosition") { public void map() { ((ScrollPane)getSource()).setScrollPosition(i, i1); }});} /**Maps ScrollPane.setScrollPosition(Point) through queue*/ public void setScrollPosition(final Point point) { runMapping(new MapVoidAction("setScrollPosition") { public void map() { ((ScrollPane)getSource()).setScrollPosition(point); }});} //End of mapping // //////////////////////////////////////////////////////// private class ValueScrollAdjuster implements ScrollAdjuster { int value; int orientation; Adjustable adj; public ValueScrollAdjuster(int value, int orientation, Adjustable adj) { this.value = value; this.orientation = orientation; this.adj = adj; } public int getScrollDirection() { if(adj.getValue() == value) { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } else { return((adj.getValue() < value) ? ScrollAdjuster.INCREASE_SCROLL_DIRECTION : ScrollAdjuster.DECREASE_SCROLL_DIRECTION); } } public int getScrollOrientation() { return(orientation); } public String getDescription() { return("Scroll to " + Integer.toString(value) + " value"); } } private class ComponentRectChecker implements ScrollAdjuster { Component comp; int x; int y; int width; int height; int orientation; public ComponentRectChecker(Component comp, int x, int y, int width, int height, int orientation) { this.comp = comp; this.x = x; this.y = y; this.width = width; this.height = height; this.orientation = orientation; } public int getScrollDirection() { int sp = (orientation == Adjustable.HORIZONTAL) ? (int)getScrollPosition().getX(): (int)getScrollPosition().getY(); Point pnt = SwingUtilities.convertPoint(comp, x, y, ((Container)getSource()).getComponents()[0]); int cp = (orientation == Adjustable.HORIZONTAL) ? pnt.x : pnt.y; int sl = (orientation == Adjustable.HORIZONTAL) ? (int)getViewportSize().getWidth(): (int)getViewportSize().getHeight(); int cl = (orientation == Adjustable.HORIZONTAL) ? width : height; if(cp <= sp) { return(ScrollAdjuster.DECREASE_SCROLL_DIRECTION); } else if((cp + cl) > (sp + sl) && cp > sp) { return(ScrollAdjuster.INCREASE_SCROLL_DIRECTION); } else { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } } public int getScrollOrientation() { return(orientation); } public String getDescription() { return(""); } } /** * Checks component type. */ public static class ScrollPaneFinder extends Finder { /** * Constructs ScrollPaneFinder. * @param sf other searching criteria. */ public ScrollPaneFinder(ComponentChooser sf) { super(ScrollPane.class, sf); } /** * Constructs ScrollPaneFinder. */ public ScrollPaneFinder() { super(ScrollPane.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/package.html0000644000175000017500000000230311064436407021565 0ustar tonytony Operators package

Operators package

Contains so called "operators".

Operator is a test-side representation for a component. Each particular operator class provides all the functionality to work with one component type. For example JButtonOperator covers javax.swing.JButton.

Operators inheritance tree exactly matches component types inheritance: AbstractButton extending JComponent means that AbstractBittonOperator extends JComponentOperator.

Every operator provides, basicly, all the methods to reproduce user actions which can be performed on a component type covered by operator.

Every operator also provides mapping functionality: API to invoke component method during the event queue. For example, AbstractButtonOperator has getText() method which simply invokes AbstractButton.getText() through the queue.

@since 23 Feb 2002
Jemmy2/src/org/netbeans/jemmy/operators/ButtonOperator.java0000644000175000017500000004063411245712237023146 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Button; import java.awt.Component; import java.awt.Container; import java.awt.event.ActionListener; import java.util.Hashtable; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.ButtonDriver; import org.netbeans.jemmy.drivers.DriverManager; /** * *

Timeouts used:
* ButtonOperator.PushButtonTimeout - time between button pressing and releasing
* ComponentOperator.WaitComponentTimeout - time to wait button displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait button enabled
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class ButtonOperator extends ComponentOperator implements Timeoutable, Outputable { /** * Identifier for a label property. * @see #getDump */ public static final String TEXT_DPROP = "Label"; private final static long PUSH_BUTTON_TIMEOUT = 0; private Timeouts timeouts; private TestOut output; ButtonDriver driver; /** * Constructor. * @param b The java.awt.Button managed by * this instance. */ public ButtonOperator(Button b) { super(b); driver = DriverManager.getButtonDriver(getClass()); } /** * Constructs a ButtonOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public ButtonOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((Button)cont. waitSubComponent(new ButtonFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a ButtonOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. */ public ButtonOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits for a component in a container to show. The component is * identified as the index+1'th * java.awt.Button that shows, lies below * the container in the display containment hierarchy, * and that has the desired text. Uses cont's timeout and output * for waiting and to init this operator. * @param cont The operator for a container containing the sought for button. * @param text Button text. * @param index Ordinal component index. The first component has index 0. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public ButtonOperator(ContainerOperator cont, String text, int index) { this((Button)waitComponent(cont, new ButtonByLabelFinder(text, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits for a component in a container to show. The component is * identified as the first * java.awt.Button that shows, lies below * the container in the display containment hierarchy, * and that has the desired text. Uses cont's timeout and output * for waiting and to init this operator. * @param cont The operator for a container containing the sought for button. * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public ButtonOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont The operator for a container containing the sought for button. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public ButtonOperator(ContainerOperator cont, int index) { this((Button) waitComponent(cont, new ButtonFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont The operator for a container containing the sought for button. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public ButtonOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches Button in a container. * @param cont Container in which to search for the component. The container * lies above the component in the display containment hierarchy. The containment * need not be direct. * @param chooser org.netbeans.jemmy.ComponentChooser implementation, defining and * applying search criteria. * @param index Ordinal component index. The first index is 0. * @return Button instance or null if component was not found. */ public static Button findButton(Container cont, ComponentChooser chooser, int index) { return((Button)findComponent(cont, new ButtonFinder(chooser), index)); } /** * Searches for the first Button in a container. * @param cont Container in which to search for the component. The container * lies above the component in the display containment hierarchy. The containment * need not be direct. * @param chooser org.netbeans.jemmy.ComponentChooser implementation, defining and * applying search criteria. * @return Button instance or null if component was not found. */ public static Button findButton(Container cont, ComponentChooser chooser) { return(findButton(cont, chooser, 0)); } /** * Searches Button by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return Button instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static Button findButton(Container cont, String text, boolean ce, boolean ccs, int index) { return(findButton(cont, new ButtonByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches Button by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return Button instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static Button findButton(Container cont, String text, boolean ce, boolean ccs) { return(findButton(cont, text, ce, ccs, 0)); } /** * Waits Button in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return Button instance. * @throws TimeoutExpiredException */ public static Button waitButton(Container cont, ComponentChooser chooser, int index) { return((Button)waitComponent(cont, new ButtonFinder(chooser), index)); } /** * Waits 0'th Button in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return Button instance. * @throws TimeoutExpiredException */ public static Button waitButton(Container cont, ComponentChooser chooser){ return(waitButton(cont, chooser, 0)); } /** * Waits Button by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return Button instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static Button waitButton(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitButton(cont, new ButtonByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits Button by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return Button instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static Button waitButton(Container cont, String text, boolean ce, boolean ccs) { return(waitButton(cont, text, ce, ccs, 0)); } static { Timeouts.initDefault("ButtonOperator.PushButtonTimeout", PUSH_BUTTON_TIMEOUT); } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (ButtonDriver)DriverManager. getDriver(DriverManager.BUTTON_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Pushes the button by mouse click. * @throws TimeoutExpiredException */ public void push() { output.printLine("Push button\n :" + toStringSource()); output.printGolden("Push button"); driver.push(this); } /** * Runs push() method in a separate thread. */ public void pushNoBlock() { produceNoBlocking(new NoBlockingAction("Button pushing") { public Object doAction(Object param) { push(); return(null); } }); } /** * Press the button by mouse. * @throws TimeoutExpiredException */ public void press() { output.printLine("Press button\n :" + toStringSource()); output.printGolden("Press button"); driver.press(this); } /** * Releases the button by mouse. * @throws TimeoutExpiredException */ public void release() { output.printLine("Release button\n :" + toStringSource()); output.printGolden("Release button"); driver.press(this); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); if(((Button)getSource()).getLabel() != null) { result.put(TEXT_DPROP, ((Button)getSource()).getLabel()); } return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps Button.addActionListener(ActionListener) through queue*/ public void addActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("addActionListener") { public void map() { ((Button)getSource()).addActionListener(actionListener); }});} /**Maps Button.getActionCommand() through queue*/ public String getActionCommand() { return((String)runMapping(new MapAction("getActionCommand") { public Object map() { return(((Button)getSource()).getActionCommand()); }}));} /**Maps Button.getLabel() through queue*/ public String getLabel() { return((String)runMapping(new MapAction("getLabel") { public Object map() { return(((Button)getSource()).getLabel()); }}));} /**Maps Button.removeActionListener(ActionListener) through queue*/ public void removeActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("removeActionListener") { public void map() { ((Button)getSource()).removeActionListener(actionListener); }});} /**Maps Button.setActionCommand(String) through queue*/ public void setActionCommand(final String string) { runMapping(new MapVoidAction("setActionCommand") { public void map() { ((Button)getSource()).setActionCommand(string); }});} /**Maps Button.setLabel(String) through queue*/ public void setLabel(final String string) { runMapping(new MapVoidAction("setLabel") { public void map() { ((Button)getSource()).setLabel(string); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Allows to find component by label. */ public static class ButtonByLabelFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs ButtonByLabelFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public ButtonByLabelFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs ButtonByLabelFinder. * @param lb a text pattern */ public ButtonByLabelFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof Button) { if(((Button)comp).getLabel() != null) { return(comparator.equals(((Button)comp).getLabel(), label)); } } return(false); } public String getDescription() { return("Button with label \"" + label + "\""); } } /** * Checks component type. */ public static class ButtonFinder extends Finder { /** * Constructs AbstractButtonFinder. * @param sf other searching criteria. */ public ButtonFinder(ComponentChooser sf) { super(Button.class, sf); } /** * Constructs AbstractButtonFinder. */ public ButtonFinder() { super(Button.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/TextComponentOperator.java0000644000175000017500000005422311245712237024501 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.TextComponent; import java.awt.event.TextListener; import java.util.Hashtable; import org.netbeans.jemmy.Action; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.TextDriver; /** * This operator type covers java.awt.TextArea component. * * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class TextComponentOperator extends ComponentOperator implements Timeoutable, Outputable { /** * Identifier for a "text" property. * @see #getDump */ public static final String TEXT_DPROP = "Text"; private final static long PUSH_KEY_TIMEOUT = 0; private final static long BETWEEN_KEYS_TIMEOUT = 0; private final static long CHANGE_CARET_POSITION_TIMEOUT = 60000; private final static long TYPE_TEXT_TIMEOUT = 60000; private Timeouts timeouts; private TestOut output; private TextDriver driver; /** * Constructor. * @param b The java.awt.TextComponent managed by * this instance. */ public TextComponentOperator(TextComponent b) { super(b); driver = DriverManager.getTextDriver(getClass()); } /** * Constructs a TextComponentOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public TextComponentOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((TextComponent)cont. waitSubComponent(new TextComponentFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a TextComponentOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public TextComponentOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits for a component in a container to show. The component is * identified as the index+1'th * java.awt.TextComponent that shows, lies below * the container in the display containment hierarchy, * and that has the desired text. Uses cont's timeout and output * for waiting and to init this operator. * @param cont The operator for a container containing the sought for textComponent. * @param text TextComponent text. * @param index Ordinal component index. The first component has index 0. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public TextComponentOperator(ContainerOperator cont, String text, int index) { this((TextComponent)waitComponent(cont, new TextComponentByTextFinder(text, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits for a component in a container to show. The component is * identified as the first * java.awt.TextComponent that shows, lies below * the container in the display containment hierarchy, * and that has the desired text. Uses cont's timeout and output * for waiting and to init this operator. * @param cont The operator for a container containing the sought for textComponent. * @param text TextComponent text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public TextComponentOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont The operator for a container containing the sought for textComponent. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public TextComponentOperator(ContainerOperator cont, int index) { this((TextComponent) waitComponent(cont, new TextComponentFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont The operator for a container containing the sought for textComponent. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public TextComponentOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches TextComponent in a container. * @param cont Container in which to search for the component. The container * lies above the component in the display containment hierarchy. The containment * need not be direct. * @param chooser org.netbeans.jemmy.ComponentChooser implementation, defining and * applying search criteria. * @param index Ordinal component index. The first index is 0. * @return TextComponent instance or null if component was not found. */ public static TextComponent findTextComponent(Container cont, ComponentChooser chooser, int index) { return((TextComponent)findComponent(cont, new TextComponentFinder(chooser), index)); } /** * Searches for the first TextComponent in a container. * @param cont Container in which to search for the component. The container * lies above the component in the display containment hierarchy. The containment * need not be direct. * @param chooser org.netbeans.jemmy.ComponentChooser implementation, defining and * applying search criteria. * @return TextComponent instance or null if component was not found. */ public static TextComponent findTextComponent(Container cont, ComponentChooser chooser) { return(findTextComponent(cont, chooser, 0)); } /** * Searches TextComponent by text. * @param cont Container to search component in. * @param text TextComponent text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return TextComponent instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static TextComponent findTextComponent(Container cont, String text, boolean ce, boolean ccs, int index) { return(findTextComponent(cont, new TextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches TextComponent by text. * @param cont Container to search component in. * @param text TextComponent text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return TextComponent instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static TextComponent findTextComponent(Container cont, String text, boolean ce, boolean ccs) { return(findTextComponent(cont, text, ce, ccs, 0)); } /** * Waits TextComponent in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return TextComponent instance. */ public static TextComponent waitTextComponent(Container cont, ComponentChooser chooser, int index) { return((TextComponent)waitComponent(cont, new TextComponentFinder(chooser), index)); } /** * Waits 0'th TextComponent in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return TextComponent instance. */ public static TextComponent waitTextComponent(Container cont, ComponentChooser chooser){ return(waitTextComponent(cont, chooser, 0)); } /** * Waits TextComponent by text. * @param cont Container to search component in. * @param text TextComponent text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return TextComponent instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static TextComponent waitTextComponent(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitTextComponent(cont, new TextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits TextComponent by text. * @param cont Container to search component in. * @param text TextComponent text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return TextComponent instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static TextComponent waitTextComponent(Container cont, String text, boolean ce, boolean ccs) { return(waitTextComponent(cont, text, ce, ccs, 0)); } static { Timeouts.initDefault("TextComponentOperator.PushKeyTimeout", PUSH_KEY_TIMEOUT); Timeouts.initDefault("TextComponentOperator.BetweenKeysTimeout", BETWEEN_KEYS_TIMEOUT); Timeouts.initDefault("TextComponentOperator.ChangeCaretPositionTimeout", CHANGE_CARET_POSITION_TIMEOUT); Timeouts.initDefault("TextComponentOperator.TypeTextTimeout", TYPE_TEXT_TIMEOUT); } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (TextDriver)DriverManager. getDriver(DriverManager.TEXT_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Changes caret position. * @param position Position to move caret to. * */ public void changeCaretPosition(final int position) { makeComponentVisible(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.changeCaretPosition(TextComponentOperator.this, position); return(null); } public String getDescription() { return("Caret moving"); } }, getTimeouts().getTimeout("TextComponentOperator.ChangeCaretPositionTimeout")); } /** * Selects a part of text. * @param startPosition Start caret position * @param finalPosition Final caret position * */ public void selectText(final int startPosition, final int finalPosition) { makeComponentVisible(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.selectText(TextComponentOperator.this, startPosition, finalPosition); return(null); } public String getDescription() { return("Text selecting"); } }, getTimeouts().getTimeout("TextComponentOperator.TypeTextTimeout")); } /** * Finds start text position. * @param text Text to be searched. * @param index Index of text instance (first instance has index 0) * @return Caret position correspondent to text start. */ public int getPositionByText(String text, int index) { String allText = getText(); int position = 0; int ind = 0; while((position = allText.indexOf(text, position)) >= 0) { if(ind == index) { return(position); } else { ind++; } position = position + text.length(); } return(-1); } /** * Finds start text position. * @param text Text to be searched. * @return Caret position correspondent to text start. */ public int getPositionByText(String text) { return(getPositionByText(text, 0)); } /** * Clears text. * */ public void clearText() { output.printLine("Clearing text in text component\n : " + toStringSource()); output.printGolden("Clearing text in text component"); makeComponentVisible(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.clearText(TextComponentOperator.this); return(null); } public String getDescription() { return("Text clearing"); } }, getTimeouts().getTimeout("TextComponentOperator.TypeTextTimeout")); } /** * Types text starting from known position. * @param text Text to be typed. * @param caretPosition Position to start type text */ public void typeText(final String text, final int caretPosition) { output.printLine("Typing text \"" + text + "\" from " + Integer.toString(caretPosition) + " position " + "in text component\n : " + toStringSource()); output.printGolden("Typing text \"" + text + "\" in text component"); makeComponentVisible(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.typeText(TextComponentOperator.this, text, caretPosition); return(null); } public String getDescription() { return("Text typing"); } }, getTimeouts().getTimeout("TextComponentOperator.TypeTextTimeout")); } /** * Types text starting from known position. * @param text Text to be typed. */ public void typeText(String text) { typeText(text, getCaretPosition()); } /** * Requests a focus, clears text, types new one and pushes Enter. * @param text New text value. Shouln't include final '\n'. * */ public void enterText(final String text) { makeComponentVisible(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.enterText(TextComponentOperator.this, text); return(null); } public String getDescription() { return("Text entering"); } }, getTimeouts().getTimeout("TextComponentOperator.TypeTextTimeout")); } public Hashtable getDump() { Hashtable result = super.getDump(); result.put(TEXT_DPROP, ((TextComponent)getSource()).getText()); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps TextComponent.addTextListener(TextListener) through queue*/ public void addTextListener(final TextListener textListener) { runMapping(new MapVoidAction("addTextListener") { public void map() { ((TextComponent)getSource()).addTextListener(textListener); }});} /**Maps TextComponent.getCaretPosition() through queue*/ public int getCaretPosition() { return(runMapping(new MapIntegerAction("getCaretPosition") { public int map() { return(((TextComponent)getSource()).getCaretPosition()); }}));} /**Maps TextComponent.getSelectedText() through queue*/ public String getSelectedText() { return((String)runMapping(new MapAction("getSelectedText") { public Object map() { return(((TextComponent)getSource()).getSelectedText()); }}));} /**Maps TextComponent.getSelectionEnd() through queue*/ public int getSelectionEnd() { return(runMapping(new MapIntegerAction("getSelectionEnd") { public int map() { return(((TextComponent)getSource()).getSelectionEnd()); }}));} /**Maps TextComponent.getSelectionStart() through queue*/ public int getSelectionStart() { return(runMapping(new MapIntegerAction("getSelectionStart") { public int map() { return(((TextComponent)getSource()).getSelectionStart()); }}));} /**Maps TextComponent.getText() through queue*/ public String getText() { return((String)runMapping(new MapAction("getText") { public Object map() { return(((TextComponent)getSource()).getText()); }}));} /**Maps TextComponent.isEditable() through queue*/ public boolean isEditable() { return(runMapping(new MapBooleanAction("isEditable") { public boolean map() { return(((TextComponent)getSource()).isEditable()); }}));} /**Maps TextComponent.removeTextListener(TextListener) through queue*/ public void removeTextListener(final TextListener textListener) { runMapping(new MapVoidAction("removeTextListener") { public void map() { ((TextComponent)getSource()).removeTextListener(textListener); }});} /**Maps TextComponent.select(int, int) through queue*/ public void select(final int i, final int i1) { runMapping(new MapVoidAction("select") { public void map() { ((TextComponent)getSource()).select(i, i1); }});} /**Maps TextComponent.selectAll() through queue*/ public void selectAll() { runMapping(new MapVoidAction("selectAll") { public void map() { ((TextComponent)getSource()).selectAll(); }});} /**Maps TextComponent.setCaretPosition(int) through queue*/ public void setCaretPosition(final int i) { runMapping(new MapVoidAction("setCaretPosition") { public void map() { ((TextComponent)getSource()).setCaretPosition(i); }});} /**Maps TextComponent.setEditable(boolean) through queue*/ public void setEditable(final boolean b) { runMapping(new MapVoidAction("setEditable") { public void map() { ((TextComponent)getSource()).setEditable(b); }});} /**Maps TextComponent.setSelectionEnd(int) through queue*/ public void setSelectionEnd(final int i) { runMapping(new MapVoidAction("setSelectionEnd") { public void map() { ((TextComponent)getSource()).setSelectionEnd(i); }});} /**Maps TextComponent.setSelectionStart(int) through queue*/ public void setSelectionStart(final int i) { runMapping(new MapVoidAction("setSelectionStart") { public void map() { ((TextComponent)getSource()).setSelectionStart(i); }});} /**Maps TextComponent.setText(String) through queue*/ public void setText(final String string) { runMapping(new MapVoidAction("setText") { public void map() { ((TextComponent)getSource()).setText(string); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Return a TextDriver used by this component. * @return a driver got by the operator during creation. */ protected TextDriver getTextDriver() { return(driver); } /** * Allows to find component by text. */ public static class TextComponentByTextFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs TextComponentByTextFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public TextComponentByTextFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs TextComponentByTextFinder. * @param lb a text pattern */ public TextComponentByTextFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof TextComponent) { if(((TextComponent)comp).getText() != null) { return(comparator.equals(((TextComponent)comp).getText(), label)); } } return(false); } public String getDescription() { return("TextComponent with text \"" + label + "\""); } } /** * Checks component type. */ public static class TextComponentFinder extends Finder { /** * Constructs TextComponentFinder. * @param sf other searching criteria. */ public TextComponentFinder(ComponentChooser sf) { super(TextComponent.class, sf); } /** * Constructs TextComponentFinder. */ public TextComponentFinder() { super(TextComponent.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/WindowOperator.java0000644000175000017500000005304611247147442023145 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Window; import java.awt.event.WindowListener; import java.lang.reflect.InvocationTargetException; import java.util.ResourceBundle; import org.netbeans.jemmy.ClassReference; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.WindowWaiter; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.WindowDriver; /** *

Timeouts used:
* WindowWaiter.WaitWindowTimeout - time to wait window displayed
* WindowWaiter.AfterWindowTimeout - time to sleep after window has been dispayed
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class WindowOperator extends ContainerOperator implements Outputable{ TestOut output; WindowDriver driver; /** * Constructor. * @param w a component */ public WindowOperator(Window w) { super(w); driver = DriverManager.getWindowDriver(getClass()); } /** * Constructs a DialogOperator object. * @param owner window - owner * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public WindowOperator(WindowOperator owner, ComponentChooser chooser, int index) { this((Window)owner. waitSubWindow(chooser, index)); copyEnvironment(owner); } /** * Constructs a DialogOperator object. * @param owner window - owner * @param chooser a component chooser specifying searching criteria. */ public WindowOperator(WindowOperator owner, ComponentChooser chooser) { this(owner, chooser, 0); } /** * Constructor. * Waits for the index'th displayed owner's child. * Uses owner's timeout and output for waiting and to init operator. * @param owner Operator pointing on a window owner. * @param index an index between appropriate ones. * @throws TimeoutExpiredException */ public WindowOperator(WindowOperator owner, int index) { this(waitWindow(owner, ComponentSearcher.getTrueChooser("Any Window"), index)); copyEnvironment(owner); } /** * Constructor. * Waits for the first displayed owner's child. * Uses owner's timeout and output for waiting and to init operator. * @param owner Operator pointing on a window owner. * @throws TimeoutExpiredException */ public WindowOperator(WindowOperator owner) { this(owner, 0); } /** * Constructor. * Waits for the index'th displayed window. * Constructor can be used in complicated cases when * output or timeouts should differ from default. * @param index an index between appropriate ones. * @param env an operator to copy environment from. * @throws TimeoutExpiredException */ public WindowOperator(int index, Operator env) { this(waitWindow(ComponentSearcher.getTrueChooser("Any Window"), index, env.getTimeouts(), env.getOutput())); copyEnvironment(env); } /** * Constructor. * Waits for the index'th displayed window. * Uses current timeouts and output values. * @see JemmyProperties#getCurrentTimeouts() * @see JemmyProperties#getCurrentOutput() * @param index an index between appropriate ones. * @throws TimeoutExpiredException */ public WindowOperator(int index) { this(index, getEnvironmentOperator()); } /** * Constructor. * Waits for the first displayed window. * Uses current timeouts and output values. * @see JemmyProperties#getCurrentTimeouts() * @see JemmyProperties#getCurrentOutput() * @throws TimeoutExpiredException */ public WindowOperator() { this(0); } /** * Searches an index'th window. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @return a window */ public static Window findWindow(ComponentChooser chooser, int index) { return(WindowWaiter.getWindow(chooser, index)); } /** * Searches a window. * @param chooser a component chooser specifying searching criteria. * @return a window */ public static Window findWindow(ComponentChooser chooser) { return(findWindow(chooser, 0)); } /** * Searches an index'th window. * @param owner Window - owner. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @return a window */ public static Window findWindow(Window owner, ComponentChooser chooser, int index) { return(WindowWaiter.getWindow(owner, chooser, index)); } /** * Searches a window. * @param owner Window - owner. * @param chooser a component chooser specifying searching criteria. * @return a window */ public static Window findWindow(Window owner, ComponentChooser chooser) { return(findWindow(owner, chooser, 0)); } /** * Waits an index'th window. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @throws TimeoutExpiredException * @return a window */ public static Window waitWindow(ComponentChooser chooser, int index) { return(waitWindow(chooser, index, JemmyProperties.getCurrentTimeouts(), JemmyProperties.getCurrentOutput())); } /** * Waits a window. * @param chooser a component chooser specifying searching criteria. * @throws TimeoutExpiredException * @return a window */ public static Window waitWindow(ComponentChooser chooser) { return(waitWindow(chooser, 0)); } /** * Waits an index'th window. * @param owner Window - owner. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @throws TimeoutExpiredException * @return a window */ public static Window waitWindow(Window owner, ComponentChooser chooser, int index) { return(waitWindow(owner, chooser, index, JemmyProperties.getCurrentTimeouts(), JemmyProperties.getCurrentOutput())); } /** * Waits a window. * @param owner Window - owner. * @param chooser a component chooser specifying searching criteria. * @throws TimeoutExpiredException * @return a window */ public static Window waitWindow(Window owner, ComponentChooser chooser) { return(waitWindow(owner, chooser, 0)); } public void setOutput(TestOut out) { super.setOutput(out); output = out; } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (WindowDriver)DriverManager. getDriver(DriverManager.WINDOW_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Activates the window. * Uses WindowDriver registered for the operator type. */ public void activate() { output.printLine("Activate window\n " + getSource().toString()); output.printGolden("Activate window"); driver.activate(this); } /** * Requests the window to close. * Uses WindowDriver registered for the operator type. */ public void requestClose() { output.printLine("Requesting close of window\n " + getSource().toString()); output.printGolden("Requesting close of window"); driver.requestClose(this); } /** * Closes a window by requesting it to close and then hiding it. * Not implemented for internal frames at the moment. * Uses WindowDriver registered for the operator type. * * @see #requestClose() */ public void requestCloseAndThenHide() { output.printLine("Closing window\n " + getSource().toString()); output.printGolden("Closing window"); driver.requestCloseAndThenHide(this); if(getVerification()) { waitClosed(); } } /** * Closes a window by requesting it to close and then, if it's a top-level * frame, hiding it. Uses WindowDriver registered for the operator type. * * @deprecated Use requestClose(). It is the target window's responsibility * to hide itself if needed. Or, if you really have to, use * requestCloseAndThenHide(). * @see #requestClose() * @see #requestCloseAndThenHide() */ public void close() { output.printLine("Closing window\n " + getSource().toString()); output.printGolden("Closing window"); driver.close(this); if(getVerification()) { waitClosed(); } } /** * Moves the window to another location. * Uses WindowDriver registered for the operator type. * @param x coordinate in screen coordinate system * @param y coordinate in screen coordinate system */ public void move(int x, int y) { output.printLine("Moving frame\n " + getSource().toString()); output.printGolden("Moving frame"); driver.move(this, x, y); } /** * Resizes the window. * Uses WindowDriver registered for the operator type. * @param width new width * @param height new height */ public void resize(int width, int height) { output.printLine("Resizing frame\n " + getSource().toString()); output.printGolden("Resizing frame"); driver.resize(this, width, height); } /** * Searches an index'th window between windows owned by this window. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @return a subwindow */ public Window findSubWindow(ComponentChooser chooser, int index) { getOutput().printLine("Looking for \"" + chooser.getDescription() + "\" subwindow"); return(findWindow((Window)getSource(), chooser, index)); } /** * Searches a window between windows owned by this window. * @param chooser a component chooser specifying searching criteria. * @return a subwindow */ public Window findSubWindow(ComponentChooser chooser) { return(findSubWindow(chooser, 0)); } /** * Waits an index'th window between windows owned by this window. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @return a subwindow */ public Window waitSubWindow(ComponentChooser chooser, int index) { getOutput().printLine("Waiting for \"" + chooser.getDescription() + "\" subwindow"); WindowWaiter ww = new WindowWaiter(); ww.setOutput(getOutput()); ww.setTimeouts(getTimeouts()); try { return(ww.waitWindow((Window)getSource(), chooser, index)); } catch (InterruptedException e) { throw(new JemmyException("Waiting for \"" + chooser.getDescription() + "\" window has been interrupted", e)); } } /** * Waits a window between windows owned by this window. * @param chooser a component chooser specifying searching criteria. * @return a subwindow */ public Window waitSubWindow(ComponentChooser chooser) { return(waitSubWindow(chooser, 0)); } /** * Waits the window to be closed. */ public void waitClosed() { getOutput().printLine("Wait window to be closed \n : "+ getSource().toString()); getOutput().printGolden("Wait window to be closed"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(!comp.isVisible()); } public String getDescription() { return("Closed window"); } }); } //////////////////////////////////////////////////////// //Mapping // /**Maps Window.addWindowListener(WindowListener) through queue*/ public void addWindowListener(final WindowListener windowListener) { runMapping(new MapVoidAction("addWindowListener") { public void map() { ((Window)getSource()).addWindowListener(windowListener); }});} /**Maps Window.applyResourceBundle(String) through queue*/ public void applyResourceBundle(final String string) { runMapping(new MapVoidAction("applyResourceBundle") { public void map() { ((Window)getSource()).applyResourceBundle(string); }});} /**Maps Window.applyResourceBundle(ResourceBundle) through queue*/ public void applyResourceBundle(final ResourceBundle resourceBundle) { runMapping(new MapVoidAction("applyResourceBundle") { public void map() { ((Window)getSource()).applyResourceBundle(resourceBundle); }});} /**Maps Window.dispose() through queue*/ public void dispose() { runMapping(new MapVoidAction("dispose") { public void map() { ((Window)getSource()).dispose(); }});} /**Maps Window.getFocusOwner() through queue*/ public Component getFocusOwner() { return((Component)runMapping(new MapAction("getFocusOwner") { public Object map() { return(((Window)getSource()).getFocusOwner()); }}));} /**Maps Window.getOwnedWindows() through queue*/ public Window[] getOwnedWindows() { return((Window[])runMapping(new MapAction("getOwnedWindows") { public Object map() { return(((Window)getSource()).getOwnedWindows()); }}));} /**Maps Window.getOwner() through queue*/ public Window getOwner() { return((Window)runMapping(new MapAction("getOwner") { public Object map() { return(((Window)getSource()).getOwner()); }}));} /**Maps Window.getWarningString() through queue*/ public String getWarningString() { return((String)runMapping(new MapAction("getWarningString") { public Object map() { return(((Window)getSource()).getWarningString()); }}));} /**Maps Window.pack() through queue*/ public void pack() { runMapping(new MapVoidAction("pack") { public void map() { ((Window)getSource()).pack(); }});} /**Maps Window.removeWindowListener(WindowListener) through queue*/ public void removeWindowListener(final WindowListener windowListener) { runMapping(new MapVoidAction("removeWindowListener") { public void map() { ((Window)getSource()).removeWindowListener(windowListener); }});} /**Maps Window.toBack() through queue*/ public void toBack() { runMapping(new MapVoidAction("toBack") { public void map() { ((Window)getSource()).toBack(); }});} /**Maps Window.toFront() through queue*/ public void toFront() { runMapping(new MapVoidAction("toFront") { public void map() { ((Window)getSource()).toFront(); }});} //End of mapping // //////////////////////////////////////////////////////// //////////////////////////////////////////////////////// //Mapping 1.4 // /**Maps Window.isFocused() through queue. @return result of the mapped method */ public boolean isFocused() { if(System.getProperty("java.specification.version").compareTo("1.3") > 0) { return(runMapping(new MapBooleanAction("isFocused") { public boolean map() { try { return(((Boolean)new ClassReference(getSource()). invokeMethod("isFocused", null, null)).booleanValue()); } catch(InvocationTargetException e) { return(false); } catch(NoSuchMethodException e) { return(false); } catch(IllegalAccessException e) { return(false); } }})); } else { return(getFocusOwner() != null); } } /**Maps Window.isActive() through queue. @return result of the mapped method */ public boolean isActive() { if(System.getProperty("java.specification.version").compareTo("1.3") > 0) { return(runMapping(new MapBooleanAction("isActive") { public boolean map() { try { return(((Boolean)new ClassReference(getSource()). invokeMethod("isActive", null, null)).booleanValue()); } catch(InvocationTargetException e) { return(false); } catch(NoSuchMethodException e) { return(false); } catch(IllegalAccessException e) { return(false); } }})); } else { return(isShowing()); } } //End of mapping 1.4 // //////////////////////////////////////////////////////// /** * A method to be used from subclasses. * Uses timeouts and output passed as parameters during the waiting. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @param timeouts timeouts to be used during the waiting. * @param output an output to be used during the waiting. * @return Component instance or null if component was not found. */ protected static Window waitWindow(ComponentChooser chooser, int index, Timeouts timeouts, TestOut output) { try { WindowWaiter waiter = new WindowWaiter(); waiter.setTimeouts(timeouts); waiter.setOutput(output); return(waiter.waitWindow(chooser, index)); } catch(InterruptedException e) { output.printStackTrace(e); return(null); } } /** * A method to be used from subclasses. * Uses owner's timeouts and output during the waiting. * @param owner a window - dialog owner. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return Component instance or null if component was not found. */ protected static Window waitWindow(WindowOperator owner, ComponentChooser chooser, int index) { return(waitWindow((Window)owner.getSource(), chooser, index, owner.getTimeouts(), owner.getOutput())); } /** * A method to be used from subclasses. * Uses timeouts and output passed as parameters during the waiting. * @param owner a window - dialog owner. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @param timeouts timeouts to be used during the waiting. * @param output an output to be used during the waiting. * @return Component instance or null if component was not found. */ protected static Window waitWindow(Window owner, ComponentChooser chooser, int index, Timeouts timeouts, TestOut output) { try { WindowWaiter waiter = new WindowWaiter(); waiter.setTimeouts(timeouts); waiter.setOutput(output); return(waiter.waitWindow(owner, chooser, index)); } catch(InterruptedException e) { JemmyProperties.getCurrentOutput().printStackTrace(e); return(null); } } } Jemmy2/src/org/netbeans/jemmy/operators/Operator.java0000644000175000017500000013205011245712447021747 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.event.InputEvent; import java.lang.reflect.InvocationTargetException; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; import org.netbeans.jemmy.Action; import org.netbeans.jemmy.ActionProducer; import org.netbeans.jemmy.CharBindingMap; import org.netbeans.jemmy.ClassReference; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.Waitable; import org.netbeans.jemmy.Waiter; import org.netbeans.jemmy.util.DefaultVisualizer; import org.netbeans.jemmy.util.MouseVisualizer; /** * Keeps all environment and low-level methods. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public abstract class Operator extends Object implements Timeoutable, Outputable { /** * Identifier for a "class" property. * @see #getDump */ public static final String CLASS_DPROP = "Class"; /** * Identifier for a "toString" property. * @see #getDump */ public static final String TO_STRING_DPROP = "toString"; private static Vector operatorPkgs; private Timeouts timeouts; private TestOut output; private CharBindingMap map; private ComponentVisualizer visualizer; private StringComparator comparator; private PathParser parser; private QueueTool queueTool; private boolean verification = false; private JemmyProperties properties; /** * Inits environment. */ public Operator() { super(); initEnvironment(); } /** * Specifies an object to be used by default to prepare component. * Each new operator created after the method using will have * defined visualizer. * Default implementation is org.netbeans.jemmy.util.DefaultVisualizer class. * @param visualizer ComponentVisualizer implementation * @return previous value * @see #setVisualizer(Operator.ComponentVisualizer) * @see #getDefaultComponentVisualizer() * @see org.netbeans.jemmy.util.DefaultVisualizer */ public static ComponentVisualizer setDefaultComponentVisualizer(ComponentVisualizer visualizer) { return((ComponentVisualizer)JemmyProperties. setCurrentProperty("ComponentOperator.ComponentVisualizer", visualizer)); } /** * Returns an object to be used by default to prepare component. * @return Object is used by default to prepare component * @see #getVisualizer() * @see #setDefaultComponentVisualizer(Operator.ComponentVisualizer) */ public static ComponentVisualizer getDefaultComponentVisualizer() { return((ComponentVisualizer)JemmyProperties. getCurrentProperty("ComponentOperator.ComponentVisualizer")); } /** * Defines string comparator to be assigned in constructor. * @param comparator the comparator to be used by default. * @return previous value. * @see #getDefaultStringComparator() * @see Operator.StringComparator */ public static StringComparator setDefaultStringComparator(StringComparator comparator) { return((StringComparator)JemmyProperties. setCurrentProperty("ComponentOperator.StringComparator", comparator)); } /** * Returns string comparator used to init operators. * @return the comparator used by default. * @see #setDefaultStringComparator(Operator.StringComparator) * @see Operator.StringComparator */ public static StringComparator getDefaultStringComparator() { return((StringComparator)JemmyProperties. getCurrentProperty("ComponentOperator.StringComparator")); } /** * Specifies an object used for parsing of path-like strings. * @param parser the parser. * @return a previous value. * @see Operator.PathParser * @see #getDefaultPathParser */ public static PathParser setDefaultPathParser(PathParser parser) { return((PathParser)JemmyProperties. setCurrentProperty("ComponentOperator.PathParser", parser)); } /** * Returns an object used for parsing of path-like strings. * @return a parser used by default. * @see Operator.PathParser * @see #setDefaultPathParser */ public static PathParser getDefaultPathParser() { return((PathParser)JemmyProperties. getCurrentProperty("ComponentOperator.PathParser")); } /** * Defines weither newly created operators should perform operation verifications by default. * @param verification a verification mode to be used by default. * @return a prevoius value. * @see #getDefaultVerification() * @see #setVerification(boolean) */ public static boolean setDefaultVerification(boolean verification) { Boolean oldValue = (Boolean)(JemmyProperties. setCurrentProperty("Operator.Verification", verification ? Boolean.TRUE : Boolean.FALSE)); return((oldValue != null) ? oldValue.booleanValue() : false); } /** * Says weither newly created operators perform operations verifications by default. * @return a verification mode used by default. * @see #setDefaultVerification(boolean) * @see #getVerification() */ public static boolean getDefaultVerification() { return(((Boolean)(JemmyProperties. getCurrentProperty("Operator.Verification"))).booleanValue()); } /** * Compares caption (button text, window title, ...) with a sample text. * @param caption String to be compared with match. Method returns false, if parameter is null. * @param match Sample to compare with. Method returns true, if parameter is null. * @param ce Compare exactly. If true, text can be a substring of caption. * @param ccs Compare case sensitively. If true, both text and caption are * converted to upper case before comparison. * @return true is the captions matched the match. * @see #isCaptionEqual * @deprecated use another methods with the same name. */ public static boolean isCaptionEqual(String caption, String match, boolean ce, boolean ccs) { return(new DefaultStringComparator(ce, ccs).equals(caption, match)); } /** * Compares caption (button text, window title, ...) with a sample text. * @param caption String to be compared with match * @param match Sample to compare with * @param comparator StringComparator instance. * @return true is the captions matched the match. * @see #isCaptionEqual */ public static boolean isCaptionEqual(String caption, String match, StringComparator comparator) { return(comparator.equals(caption, match)); } /** * Returns default mouse button mask. * @return InputEvent.BUTTON*_MASK field value */ public static int getDefaultMouseButton() { return(InputEvent.BUTTON1_MASK); } /** * Returns mask of mouse button which used to popup expanding. (InputEvent.BUTTON3_MASK) * @return InputEvent.BUTTON*_MASK field value */ public static int getPopupMouseButton() { return(InputEvent.BUTTON3_MASK); } /** * Creates operator for component. * Tries to find class with "operator package"."class name"Operator name, * where "operator package" is a package from operator packages list, * and "class name" is the name of class or one of its superclasses. * @param comp Component to create operator for. * @return a new operator with default environment. * @see #addOperatorPackage(String) */ public static ComponentOperator createOperator(Component comp) { //hack! try { Class cclass = Class.forName("java.awt.Component"); Class compClass = comp.getClass(); ComponentOperator result; do { if((result = createOperator(comp, compClass)) != null) { return(result); } } while(cclass.isAssignableFrom(compClass = compClass.getSuperclass())); } catch(ClassNotFoundException e) { } return(null); } /** * Adds package to the list of packages containing operators.
* "org.netbeans.jemmy.operators" is in the list by default. * @param pkgName Package name. * @see #createOperator(Component) */ public static void addOperatorPackage(String pkgName) { operatorPkgs.add(pkgName); } /** * Returns an operator containing default environment. * @return an empty operator (not having any component source) * having default environment. */ public static Operator getEnvironmentOperator() { return(new NullOperator()); } static { //init visualizer depending on OS: //Linux - new MouseVisualizer(MouseVisualizer.TOP, 0.5, 10, false) //solaris - new MouseVisualizer() //others - new DefaultVisualizer() String os = System.getProperty("os.name").toUpperCase(); if (os.startsWith("LINUX")) { setDefaultComponentVisualizer(new MouseVisualizer(MouseVisualizer.TOP, 0.5, 10, false)); } else if(os.startsWith("SUNOS")) { setDefaultComponentVisualizer(new MouseVisualizer()); } else { setDefaultComponentVisualizer(new DefaultVisualizer()); } operatorPkgs = new Vector (); setDefaultStringComparator(new DefaultStringComparator(false, false)); setDefaultPathParser(new DefaultPathParser("|")); addOperatorPackage("org.netbeans.jemmy.operators"); setDefaultVerification(true); } /** * Returns object operator is used for. * @return an instance of java.awt.Component subclass * which this operator was created for. */ public abstract Component getSource(); //////////////////////////////////////////////////////// //Environment // //////////////////////////////////////////////////////// /** * Returns QueueTool is used to work with queue. * @return a QueueTool. */ public QueueTool getQueueTool() { return(queueTool); } /** * Copies all environment (output, timeouts, * visualizer) from another operator. * @param anotherOperator an operator to copy the environment to. */ public void copyEnvironment(Operator anotherOperator) { setTimeouts(anotherOperator.getTimeouts()); setOutput(anotherOperator.getOutput()); setVisualizer(anotherOperator.getVisualizer()); setComparator(anotherOperator.getComparator()); setVerification(anotherOperator.getVerification()); setCharBindingMap(anotherOperator.getCharBindingMap()); setProperties(anotherOperator.getProperties()); } public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; queueTool.setTimeouts(timeouts); } public Timeouts getTimeouts() { return(timeouts); } /** * Returns component visualizer. * Visualizer is used from from makeComponentVisible() method. * @return a visualizer assigned to this operator. * @see #getDefaultComponentVisualizer() * @see #setVisualizer(Operator.ComponentVisualizer) */ public ComponentVisualizer getVisualizer() { return(visualizer); } /** * Changes component visualizer. * Visualizer is used from from makeComponentVisible() method. * @param vo a visualizer to assign to this operator. * @see #setDefaultComponentVisualizer(Operator.ComponentVisualizer) * @see #getVisualizer() */ public void setVisualizer(ComponentVisualizer vo) { visualizer = vo; } /** * Returns a JemmyProperty object assigned to this operator. * @return a JemmyProperty object got from the top of property stack * or from another operator by copyuing environment. * @see #setProperties */ public JemmyProperties getProperties() { return(properties); } /** * Assigns a JemmyProperty object to this operator. * @param properties a properties to assign to this operator. * @return previously assigned properties. * @see #getProperties */ public JemmyProperties setProperties(JemmyProperties properties) { JemmyProperties oldProperties = getProperties(); this.properties = properties; return(oldProperties); } /** * Defines CharBindingMap. * @param map a CharBindingMap to use for keyboard operations. * @see org.netbeans.jemmy.CharBindingMap * @see org.netbeans.jemmy.JemmyProperties#setCurrentCharBindingMap(CharBindingMap) * @see #getCharBindingMap */ public void setCharBindingMap(CharBindingMap map) { this.map = map; } /** * Returns CharBindingMap used for keyboard operations. * @return a map assigned to this object. * @see #setCharBindingMap */ public CharBindingMap getCharBindingMap() { return(map); } public void setOutput(TestOut out) { output = out; queueTool.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } /** * Returns object which is used for string comparison. * @return a comparator assigned to this operator. * @see org.netbeans.jemmy.operators.Operator.StringComparator * @see org.netbeans.jemmy.operators.Operator.DefaultStringComparator * @see #setComparator */ public StringComparator getComparator() { return(comparator); } /** * Defines object which is used for string comparison. * @param comparator a comparator to use for string comparision. * @see org.netbeans.jemmy.operators.Operator.StringComparator * @see org.netbeans.jemmy.operators.Operator.DefaultStringComparator * @see #getComparator */ public void setComparator(StringComparator comparator) { this.comparator = comparator; } /** * Returns object which is used for parsing of path-like strings. * @return a comparator assigned to this operator. * @see #setPathParser */ public PathParser getPathParser() { return(parser); } /** * Specifies object which is used for parsing of path-like strings. * @param parser a parser to use for path parsing. * @see #getPathParser */ public void setPathParser(PathParser parser) { this.parser = parser; } /** * Defines weither operator should perform operation verifications. * @param verification new value. * @return old value * @see #setDefaultVerification(boolean) * @see #getDefaultVerification() * @see #getVerification() */ public boolean setVerification(boolean verification) { boolean oldValue = this.verification; this.verification = verification; return(oldValue); } /** * Says weither operator performs operation verifications. * @return old value * @see #setDefaultVerification(boolean) * @see #getDefaultVerification() * @see #setVerification(boolean) */ public boolean getVerification() { return(verification); } //////////////////////////////////////////////////////// //Util // //////////////////////////////////////////////////////// /** * Creates new array which has all elements from * first array, except last element. * @param path an original array * @return new array */ public String[] getParentPath(String path[]) { if(path.length > 1) { String[] ppath = new String[path.length - 1]; for(int i = 0; i < ppath.length; i++) { ppath[i] = path[i]; } return(ppath); } else { return(new String[0]); } } public ComponentChooser[] getParentPath(ComponentChooser path[]) { if(path.length > 1) { ComponentChooser[] ppath = new ComponentChooser[path.length - 1]; for(int i = 0; i < ppath.length; i++) { ppath[i] = path[i]; } return(ppath); } else { return(new ComponentChooser[0]); } } /** * Parses a string to a string array * using a PathParser assigned to this operator. * @param path an original string * @return created String array. */ public String[] parseString(String path) { return(getPathParser().parse(path)); } /** * Parses strings like "1|2|3" into arrays {"1", "2", "3"}. * @param path an original string * @param delim a delimiter string * @return created String array. */ public String[] parseString(String path, String delim) { return(new DefaultPathParser(delim).parse(path)); } /** * Returns key code to be pressed for character typing. * @param c Character to be typed. * @return a value of one of the KeyEvent.VK_* fields. * @see org.netbeans.jemmy.CharBindingMap */ public int getCharKey(char c) { return(map.getCharKey(c)); } /** * Returns modifiers mask for character typing. * @param c Character to be typed. * @return a combination of InputEvent.*_MASK fields. * @see org.netbeans.jemmy.CharBindingMap */ public int getCharModifiers(char c) { return(map.getCharModifiers(c)); } /** * Returns key codes to by pressed for characters typing. * @param c Characters to be typed. * @return an array of KeyEvent.VK_* values. * @see org.netbeans.jemmy.CharBindingMap */ public int[] getCharsKeys(char[] c) { int[] result = new int[c.length]; for(int i = 0; i < c.length; i++) { result[i] = getCharKey(c[i]); } return(result); } /** * Returns modifiers masks for characters typing. * @param c Characters to be typed. * @return an array of a combination of InputEvent.*_MASK fields. * @see org.netbeans.jemmy.CharBindingMap */ public int[] getCharsModifiers(char[] c) { int[] result = new int[c.length]; for(int i = 0; i < c.length; i++) { result[i] = getCharModifiers(c[i]); } return(result); } /** * Returns key codes to by pressed for the string typing. * @param s String to be typed. * @return an array of KeyEvent.VK_* values. * @see org.netbeans.jemmy.CharBindingMap */ public int[] getCharsKeys(String s) { return(getCharsKeys(s.toCharArray())); } /** * Returns modifiers masks for the string typing. * @param s String to be typed. * @return an array of a combination of InputEvent.*_MASK fields. * @see org.netbeans.jemmy.CharBindingMap */ public int[] getCharsModifiers(String s) { return(getCharsModifiers(s.toCharArray())); } /** * Compares string using getComparator StringComparator. * @param caption a caption * @param match a pattern * @return true if caption and match match * @see #isCaptionEqual */ public boolean isCaptionEqual(String caption, String match) { return(comparator.equals(caption, match)); } /** * Prints component information into operator output. */ public void printDump() { Hashtable result = getDump(); Object[] keys = result.keySet().toArray(); for(int i = 0; i < result.size(); i++) { output.printLine((String)keys[i] + " = " + (String)result.get(keys[i])); } } /** * Returns information about component. * All records marked by simbolic constants defined in * public static final *_DPROP fields for * each operator type. * @return a Hashtable containing name-value pairs. */ public Hashtable getDump() { Hashtable result = new Hashtable(); result.put(CLASS_DPROP, getSource().getClass().getName()); result.put(TO_STRING_DPROP, getSource().toString()); return(result); } /** * Waits a state specified by a ComponentChooser instance. * @param state a ComponentChooser defining the state criteria. * @throws TimeoutExpiredException if the state has not * achieved in a value defined by "ComponentOperator.WaitStateTimeout" */ public void waitState(final ComponentChooser state) { Waiter stateWaiter = new Waiter(new Waitable() { public Object actionProduced(Object obj) { return(state.checkComponent(getSource()) ? "" : null); } public String getDescription() { return("Wait \"" + state.getDescription() + "\" state to be reached"); } }); stateWaiter.setTimeoutsToCloneOf(getTimeouts(), "ComponentOperator.WaitStateTimeout"); stateWaiter.setOutput(getOutput().createErrorOutput()); try { stateWaiter.waitAction(null); } catch(InterruptedException e) { throw(new JemmyException("Waiting of \"" + state.getDescription() + "\" state has been interrupted!")); } } //////////////////////////////////////////////////////// //Mapping // //////////////////////////////////////////////////////// /** * Performs an operation with time control. * @param action an action to execute. * @param param an action parameters. * @param wholeTime a time for the action to be finished. * @return an action result. */ protected Object produceTimeRestricted(Action action, final Object param, long wholeTime) { ActionProducer producer = new ActionProducer(action); producer.setOutput(getOutput().createErrorOutput()); producer.setTimeouts(getTimeouts().cloneThis()); producer.getTimeouts().setTimeout("ActionProducer.MaxActionTime", wholeTime); try { Object result = producer.produceAction(param); Throwable exception = producer.getException(); if(exception != null) { if(exception instanceof JemmyException) { throw((JemmyException)exception); } else { throw(new JemmyException("Exception during " + action.getDescription(), exception)); } } return(result); } catch(InterruptedException e) { throw(new JemmyException("Interrupted!", e)); } } /** * Performs an operation with time control. * @param action an action to execute. * @param wholeTime a time for the action to be finished. * @return an action result. */ protected Object produceTimeRestricted(Action action, long wholeTime) { return(produceTimeRestricted(action, null, wholeTime)); } /** * Performs an operation without time control. * @param action an action to execute. * @param param an action parameters. */ protected void produceNoBlocking(NoBlockingAction action, Object param) { try { ActionProducer noBlockingProducer = new ActionProducer(action, false); noBlockingProducer.setOutput(output.createErrorOutput()); noBlockingProducer.setTimeouts(timeouts); noBlockingProducer.produceAction(param); } catch(InterruptedException e) { throw(new JemmyException("Exception during \"" + action.getDescription() + "\" execution", e)); } if(action.exception != null) { throw(new JemmyException("Exception during nonblocking \"" + action.getDescription() + "\"", action.exception)); } } /** * Performs an operation without time control. * @param action an action to execute. */ protected void produceNoBlocking(NoBlockingAction action) { produceNoBlocking(action, null); } /** * Equivalent to getQueue().lock();. */ protected void lockQueue() { queueTool.lock(); } /** * Equivalent to getQueue().unlock();. */ protected void unlockQueue() { queueTool.unlock(); } /** * Unlocks Queue and then throw exception. * @param e an exception to be thrown. */ protected void unlockAndThrow(Exception e) { unlockQueue(); throw(new JemmyException("Exception during queue locking", e)); } /** * To map nonprimitive type component's method. * @param action a mapping action. * @return an action result. * @see Operator.MapAction */ protected Object runMapping(MapAction action) { return(runMappingPrimitive(action)); } /** * To map char component's method. * @param action a mapping action. * @return an action result. * @see #runMapping(Operator.MapAction) * @see Operator.MapCharacterAction */ protected char runMapping(MapCharacterAction action) { return(((Character)runMappingPrimitive(action)).charValue()); } /** * To map byte component's method. * @param action a mapping action. * @return an action result. * @see #runMapping(Operator.MapAction) * @see Operator.MapByteAction */ protected byte runMapping(MapByteAction action) { return(((Byte)runMappingPrimitive(action)).byteValue()); } /** * To map int component's method. * @param action a mapping action. * @return an action result. * @see #runMapping(Operator.MapAction) * @see Operator.MapIntegerAction */ protected int runMapping(MapIntegerAction action) { return(((Integer)runMappingPrimitive(action)).intValue()); } /** * To map long component's method. * @param action a mapping action. * @return an action result. * @see #runMapping(Operator.MapAction) * @see Operator.MapLongAction */ protected long runMapping(MapLongAction action) { return(((Long)runMappingPrimitive(action)).longValue()); } /** * To map float component's method. * @param action a mapping action. * @return an action result. * @see #runMapping(Operator.MapAction) * @see Operator.MapFloatAction */ protected float runMapping(MapFloatAction action) { return(((Float)runMappingPrimitive(action)).floatValue()); } /** * To map double component's method. * @param action a mapping action. * @return an action result. * @see #runMapping(Operator.MapAction) * @see Operator.MapDoubleAction */ protected double runMapping(MapDoubleAction action) { return(((Double)runMappingPrimitive(action)).doubleValue()); } /** * To map boolean component's method. * @param action a mapping action. * @return an action result. * @see #runMapping(Operator.MapAction) * @see Operator.MapBooleanAction */ protected boolean runMapping(MapBooleanAction action) { return(((Boolean)runMappingPrimitive(action)).booleanValue()); } /** * To map void component's method. * @param action a mapping action. * @see #runMapping(Operator.MapAction) * @see Operator.MapVoidAction */ protected void runMapping(MapVoidAction action) { runMappingPrimitive(action); } /** * Adds array of objects to dump hashtable. * Is used for multiple properties such as list items and tree nodes. * @param table a table to add properties to. * @param title property names prefix. Property names are constructed by * adding a number to the prefix: * title + "_" + Iteger.toString("ordinal index") * @param items an array of property values. * @return an array of property names (with added numbers). */ protected String[] addToDump(Hashtable table, String title, Object[] items) { String[] names = createNames(title + "_", items.length); for(int i = 0; i < items.length; i++) { table.put(names[i], items[i].toString()); } return(names); } /** * Adds two dimentional array of objects to dump hashtable. * Is used for multiple properties such as table cells. * @param table a table to add properties to. * @param title property names prefix. Property names are constructed by * adding two numbers to the prefix: * title + "_" + Iteger.toString("row index") + "_" + Iteger.toString("column index") * @param items an array of property values. * @return an array of property names (with added numbers). */ protected String[] addToDump(Hashtable table, String title, Object[][] items) { String[] names = createNames(title + "_", items.length); for(int i = 0; i < items.length; i++) { addToDump(table, names[i], items[i]); } return(names); } //////////////////////////////////////////////////////// //Private // //////////////////////////////////////////////////////// private Object runMappingPrimitive(QueueTool.QueueAction action) { return(queueTool.invokeSmoothly(action)); } private String[] createNames(String title, int count) { String[] result = new String[count]; int indexLength = Integer.toString(count).length(); String zeroString = ""; for(int i = 0; i < indexLength; i++) { zeroString = zeroString + "0"; } String indexString; for(int i = 0; i < count; i++) { indexString = Integer.toString(i); result[i] = title + zeroString.substring(0, indexLength - indexString.length()) + indexString; } return(result); } private static ComponentOperator createOperator(Component comp, Class compClass) { StringTokenizer token = new StringTokenizer(compClass.getName(), "."); String className = ""; while(token.hasMoreTokens()) { className = token.nextToken(); } Object[] params = {comp}; Class[] param_classes = {compClass}; String operatorPackage; for(int i = 0; i < operatorPkgs.size(); i++) { operatorPackage = (String)operatorPkgs.get(i); try { return((ComponentOperator) new ClassReference(operatorPackage + "." + className + "Operator"). newInstance(params, param_classes)); } catch(ClassNotFoundException e) { } catch(InvocationTargetException e) { } catch(NoSuchMethodException e) { } catch(IllegalAccessException e) { } catch(InstantiationException e) { } } return(null); } private void initEnvironment() { queueTool = new QueueTool(); setTimeouts(JemmyProperties.getProperties().getTimeouts()); setOutput(JemmyProperties.getProperties().getOutput()); setCharBindingMap(JemmyProperties.getProperties().getCharBindingMap()); setVisualizer(getDefaultComponentVisualizer()); setComparator(getDefaultStringComparator()); setVerification(getDefaultVerification()); setProperties(JemmyProperties.getProperties()); setPathParser(getDefaultPathParser()); } /** * Returns toString() result from component of this operator. It calls * {@link #getSource}.toString() in dispatch thread. * @return toString() result from component of this operator. */ public String toStringSource() { return (String)runMapping(new MapAction("getSource().toString()") { public Object map() { return getSource().toString(); } }); } /** * Interface used to make component visible & ready to to make operations with. */ public interface ComponentVisualizer { /** * Prepares component for a user input. * @param compOper Operator asking for necessary actions. */ public void makeVisible(ComponentOperator compOper); } /** * Interface to compare string resources like labels, button text, ... * with match.
*/ public interface StringComparator { /** * Imlementation must return true if strings are equal. * @param caption a text to compare with pattern. * @param match a pattern * @return true if text and pattern matches. */ public boolean equals(String caption, String match); } /** * Default StringComparator implementation. */ public static class DefaultStringComparator implements StringComparator { boolean ce; boolean ccs; /** * Constructs a DefaultStringComparator object. * @param ce Compare exactly. If false, text can be a substring of caption. * @param ccs Compare case sensitively. */ public DefaultStringComparator(boolean ce, boolean ccs) { this.ce = ce; this.ccs = ccs; } /** * Compares a caption with a match using switched passed into constructor. * @param caption String to be compared with match. Method returns false, if parameter is null. * @param match Sample to compare with. Method returns true, if parameter is null. * @return true if text and pattern matches. */ public boolean equals(String caption, String match) { if(match == null) { return(true); } if(caption == null) { return(false); } String c, t; if(!ccs) { c = caption.toUpperCase(); t = match.toUpperCase(); } else { c = caption; t = match; } if(ce) { return(c.equals(t)); } else { return(c.indexOf(t) != -1); } } } /** * Used for parsing of path-like strings. */ public interface PathParser { /** * Parses a string to a String array. * @param path a String to parse. * @return a parsed array. */ public String[] parse(String path); } /** * Used for parsing of path-like strings where path components are * separated by a string-separator: "drive|directory|subdirectory|file". */ public static class DefaultPathParser implements PathParser { String separator; /** * Constructs a DefaultPathParser object. * @param separator a string used as separator. */ public DefaultPathParser(String separator) { this.separator = separator; } public String[] parse(String path) { if(path.length() > 0) { Vector parsed = new Vector(); int position = 0; int sepIndex = 0; while((sepIndex = path.indexOf(separator, position)) != -1) { parsed.add(path.substring(position, sepIndex)); position = sepIndex + separator.length(); } parsed.add(path.substring(position)); String[] result = new String[parsed.size()]; for(int i = 0; i < parsed.size(); i++) { result[i] = (String)parsed.get(i); } return(result); } else { return(new String[0]); } } } /** * Allows to bind a compponent by a component type. */ public static class Finder implements ComponentChooser { Class clz; ComponentChooser subchooser; /** * Constructs Finder. * @param clz a component class. * @param subchooser other searching criteria. */ public Finder(Class clz, ComponentChooser subchooser) { this.clz = clz; this.subchooser = subchooser; } /** * Constructs Finder. * @param clz a component class. */ public Finder(Class clz) { this(clz, ComponentSearcher.getTrueChooser("Any " + clz.getName())); } public boolean checkComponent(Component comp) { if(clz.isInstance(comp)) { return(subchooser.checkComponent(comp)); } return(false); } public String getDescription() { return(subchooser.getDescription()); } } /** * Can be used to make nonblocking operation implementation. * Typical scenario is:
* produceNoBlocking(new NoBlockingAction("Button pushing") {
* public Object doAction(Object param) {
* push();
* return(null);
* }
* });
*/ protected abstract class NoBlockingAction implements Action { String description; Exception exception; boolean finished; /** * Constructs a NoBlockingAction object. * @param description an action description. */ public NoBlockingAction(String description) { this.description = description; exception = null; finished = false; } public final Object launch(Object param) { Object result = null; try { result = doAction(param); } catch(Exception e) { exception = e; } finished = true; return(result); } /** * Performs a mapping action. * @param param an action parameter. * @return an action result. */ public abstract Object doAction(Object param); public String getDescription() { return(description); } /** * Specifies the exception. * @param e an exception. * @see #getException */ protected void setException(Exception e) { exception = e; } /** * Returns an exception occured diring the action execution. * @return an exception. * @see #setException */ public Exception getException() { return(exception); } } /** * Can be used to simplify nonprimitive type component's methods mapping. * Like this:
* public Color getBackground() {
* return((Color)runMapping(new MapAction("getBackground") {
* public Object map() {
* return(((Component)getSource()).getBackground());
* }
* }));
* }
* @see #runMapping(Operator.MapAction) */ protected abstract class MapAction extends QueueTool.QueueAction { /** * Constructs a MapAction object. * @param description an action description. */ public MapAction(String description) { super(description); } public final Object launch() throws Exception { return(map()); } /** * Executes a map action. * @return an action result. * @throws Exception */ public abstract Object map() throws Exception; } /** * Can be used to simplify char component's methods mapping. * @see #runMapping(Operator.MapCharacterAction) */ protected abstract class MapCharacterAction extends QueueTool.QueueAction { /** * Constructs a MapCharacterAction object. * @param description an action description. */ public MapCharacterAction(String description) { super(description); } public final Object launch() throws Exception { return(new Character(map())); } /** * Executes a map action. * @return an action result. * @throws Exception */ public abstract char map() throws Exception; } /** * Can be used to simplify byte component's methods mapping. * @see #runMapping(Operator.MapByteAction) */ protected abstract class MapByteAction extends QueueTool.QueueAction { /** * Constructs a MapByteAction object. * @param description an action description. */ public MapByteAction(String description) { super(description); } public final Object launch() throws Exception { return(new Byte(map())); } /** * Executes a map action. * @return an action result. * @throws Exception */ public abstract byte map() throws Exception; } /** * Can be used to simplify int component's methods mapping. * @see #runMapping(Operator.MapIntegerAction) */ protected abstract class MapIntegerAction extends QueueTool.QueueAction { /** * Constructs a MapIntegerAction object. * @param description an action description. */ public MapIntegerAction(String description) { super(description); } public final Object launch() throws Exception { return(new Integer(map())); } /** * Executes a map action. * @return an action result. * @throws Exception */ public abstract int map() throws Exception; } /** * Can be used to simplify long component's methods mapping. * @see #runMapping(Operator.MapLongAction) */ protected abstract class MapLongAction extends QueueTool.QueueAction { /** * Constructs a MapLongAction object. * @param description an action description. */ public MapLongAction(String description) { super(description); } public final Object launch() throws Exception { return(new Long(map())); } /** * Executes a map action. * @return an action result. * @throws Exception */ public abstract long map() throws Exception; } /** * Can be used to simplify float component's methods mapping. * @see #runMapping(Operator.MapFloatAction) */ protected abstract class MapFloatAction extends QueueTool.QueueAction { /** * Constructs a MapFloatAction object. * @param description an action description. */ public MapFloatAction(String description) { super(description); } public final Object launch() throws Exception { return(new Float(map())); } /** * Executes a map action. * @return an action result. * @throws Exception */ public abstract float map() throws Exception; } /** * Can be used to simplify double component's methods mapping. * @see #runMapping(Operator.MapDoubleAction) */ protected abstract class MapDoubleAction extends QueueTool.QueueAction { /** * Constructs a MapDoubleAction object. * @param description an action description. */ public MapDoubleAction(String description) { super(description); } public final Object launch() throws Exception { return(new Double(map())); } /** * Executes a map action. * @return an action result. * @throws Exception */ public abstract double map() throws Exception; } /** * Can be used to simplify boolean component's methods mapping. * @see #runMapping(Operator.MapBooleanAction) */ protected abstract class MapBooleanAction extends QueueTool.QueueAction { /** * Constructs a MapBooleanAction object. * @param description an action description. */ public MapBooleanAction(String description) { super(description); } public final Object launch() throws Exception { return(map() ? Boolean.TRUE : Boolean.FALSE); } /** * Executes a map action. * @return an action result. * @throws Exception */ public abstract boolean map() throws Exception; } /** * Can be used to simplify void component's methods mapping. * @see #runMapping(Operator.MapVoidAction) */ protected abstract class MapVoidAction extends QueueTool.QueueAction { /** * Constructs a MapVoidAction object. * @param description an action description. */ public MapVoidAction(String description) { super(description); } public final Object launch() throws Exception { map(); return(null); } /** * Executes a map action. * @throws Exception */ public abstract void map() throws Exception; } private static class NullOperator extends Operator { public NullOperator() { super(); } public Component getSource() { return(null); } } } Jemmy2/src/org/netbeans/jemmy/operators/FrameOperator.java0000644000175000017500000003645511245712237022733 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Frame; import java.awt.Image; import java.awt.MenuBar; import java.util.Hashtable; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.FrameWaiter; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.FrameDriver; /** *

Timeouts used:
* FrameWaiter.WaitFrameTimeout - time to wait frame displayed
* FrameWaiter.AfterFrameTimeout - time to sleep after frame has been dispayed
* ComponentOperator.WaitStateTimeout - time to wait for text
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class FrameOperator extends WindowOperator implements Outputable { /** * Identifier for a title property. * @see #getDump */ public static final String TITLE_DPROP = "Title"; /** * Identifier for a state property. * @see #getDump */ public static final String STATE_DPROP = "State"; /** * Identifier for a "normal state" state property value. * @see #getDump */ public static final String STATE_NORMAL_DPROP_VALUE = "NORMAL"; /** * Identifier for a "iconified state" state property value. * @see #getDump */ public static final String STATE_ICONIFIED_DPROP_VALUE = "ICONIFIED"; /** * Identifier for a resizable property. * @see #getDump */ public static final String IS_RESIZABLE_DPROP = "Resizable"; TestOut output; FrameDriver driver; /** * Constructs a FrameOperator object. * @param w window */ public FrameOperator(Frame w) { super(w); driver = DriverManager.getFrameDriver(getClass()); } /** * Constructs a FrameOperator object. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @param env an operator to copy environment from. */ public FrameOperator(ComponentChooser chooser, int index, Operator env) { this(waitFrame(new FrameFinder(chooser), index, env.getTimeouts(), env.getOutput())); copyEnvironment(env); } /** * Constructs a FrameOperator object. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public FrameOperator(ComponentChooser chooser, int index) { this(chooser, index, Operator.getEnvironmentOperator()); } /** * Constructs a FrameOperator object. * @param chooser a component chooser specifying searching criteria. */ public FrameOperator(ComponentChooser chooser) { this(chooser, 0); } /** * Constructor. * Waits for the frame with "title" subtitle. * Constructor can be used in complicated cases when * output or timeouts should differ from default. * @param title a window title * @param index Ordinal component index. * @param env an operator to copy environment from. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public FrameOperator(String title, int index, Operator env) { this(waitFrame(new FrameByTitleFinder(title, env.getComparator()), index, env.getTimeouts(), env.getOutput())); copyEnvironment(env); } /** * Constructor. * Waits for the frame with "title" subtitle. * Uses current timeouts and output values. * @param title a window title * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see JemmyProperties#getCurrentTimeouts() * @see JemmyProperties#getCurrentOutput() * @throws TimeoutExpiredException */ public FrameOperator(String title, int index) { this(title, index, ComponentOperator.getEnvironmentOperator()); } /** * Constructor. * Waits for the frame with "title" subtitle. * Uses current timeouts and output values. * @param title a window title * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see JemmyProperties#getCurrentTimeouts() * @see JemmyProperties#getCurrentOutput() * @throws TimeoutExpiredException */ public FrameOperator(String title) { this(title, 0); } /** * Constructor. * Waits for the index'th frame. * Uses current timeout and output for waiting and to init operator. * @param index Ordinal component index. * @throws TimeoutExpiredException */ public FrameOperator(int index) { this((Frame) waitFrame(new FrameFinder(), index, ComponentOperator.getEnvironmentOperator().getTimeouts(), ComponentOperator.getEnvironmentOperator().getOutput())); copyEnvironment(ComponentOperator.getEnvironmentOperator()); } /** * Constructor. * Waits for the first frame. * Uses current timeout and output for waiting and to init operator. * @throws TimeoutExpiredException */ public FrameOperator() { this(0); } public void setOutput(TestOut out) { super.setOutput(out); output = out; } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (FrameDriver)DriverManager. getDriver(DriverManager.FRAME_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Waits for title. Uses getComparator() comparator. * @param title Title to wait for. */ public void waitTitle(final String title) { getOutput().printLine("Wait \"" + title + "\" title of frame \n : "+ toStringSource()); getOutput().printGolden("Wait \"" + title + "\" title"); waitState(new FrameByTitleFinder(title, getComparator())); } /** * Iconifies the frame. */ public void iconify() { output.printLine("Iconifying frame\n " + toStringSource()); output.printGolden("Iconifying frame"); driver.iconify(this); if(getVerification()) { waitState(Frame.ICONIFIED); } } /** * Deiconifies the frame. */ public void deiconify() { output.printLine("Deiconifying frame\n " + toStringSource()); output.printGolden("Deiconifying frame"); driver.deiconify(this); if(getVerification()) { waitState(Frame.NORMAL); } } /** * Maximizes the frame. */ public void maximize() { output.printLine("Maximizing frame\n " + toStringSource()); output.printGolden("Maximizing frame"); driver.maximize(this); if(getVerification()) { waitState(Frame.NORMAL); } } /** * Demaximizes the frame. */ public void demaximize() { output.printLine("Demaximizing frame\n " + toStringSource()); output.printGolden("Demaximizing frame"); driver.demaximize(this); if(getVerification()) { waitState(Frame.NORMAL); } } /** * Waits for the frame to have a specified state. * @param state a state for the frame to have. */ public void waitState(final int state) { getOutput().printLine("Wait frame to have " + Integer.toString(state) + " state \n : "+ toStringSource()); getOutput().printGolden("Wait frame to have " + Integer.toString(state) + " state"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(((Frame)comp).getState() == state); } public String getDescription() { return(Integer.toString(state) + " state"); } }); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); if(((Frame)getSource()).getTitle() != null) { result.put(TITLE_DPROP, ((Frame)getSource()).getTitle()); } result.put(STATE_DPROP, (((Frame)getSource()).getState() == Frame.ICONIFIED) ? STATE_ICONIFIED_DPROP_VALUE : STATE_NORMAL_DPROP_VALUE); result.put(IS_RESIZABLE_DPROP, ((Frame)getSource()).isResizable() ? "true" : "false"); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps Frame.getIconImage() through queue*/ public Image getIconImage() { return((Image)runMapping(new MapAction("getIconImage") { public Object map() { return(((Frame)getSource()).getIconImage()); }}));} /**Maps Frame.getMenuBar() through queue*/ public MenuBar getMenuBar() { return((MenuBar)runMapping(new MapAction("getMenuBar") { public Object map() { return(((Frame)getSource()).getMenuBar()); }}));} /**Maps Frame.getState() through queue*/ public int getState() { return(runMapping(new MapIntegerAction("getState") { public int map() { return(((Frame)getSource()).getState()); }}));} /**Maps Frame.getTitle() through queue*/ public String getTitle() { return((String)runMapping(new MapAction("getTitle") { public Object map() { return(((Frame)getSource()).getTitle()); }}));} /**Maps Frame.isResizable() through queue*/ public boolean isResizable() { return(runMapping(new MapBooleanAction("isResizable") { public boolean map() { return(((Frame)getSource()).isResizable()); }}));} /**Maps Frame.setIconImage(Image) through queue*/ public void setIconImage(final Image image) { runMapping(new MapVoidAction("setIconImage") { public void map() { ((Frame)getSource()).setIconImage(image); }});} /**Maps Frame.setMenuBar(MenuBar) through queue*/ public void setMenuBar(final MenuBar menuBar) { runMapping(new MapVoidAction("setMenuBar") { public void map() { ((Frame)getSource()).setMenuBar(menuBar); }});} /**Maps Frame.setResizable(boolean) through queue*/ public void setResizable(final boolean b) { runMapping(new MapVoidAction("setResizable") { public void map() { ((Frame)getSource()).setResizable(b); }});} /**Maps Frame.setState(int) through queue*/ public void setState(final int i) { runMapping(new MapVoidAction("setState") { public void map() { ((Frame)getSource()).setState(i); }});} /**Maps Frame.setTitle(String) through queue*/ public void setTitle(final String string) { runMapping(new MapVoidAction("setTitle") { public void map() { ((Frame)getSource()).setTitle(string); }});} //End of mapping // //////////////////////////////////////////////////////// /** * A method to be used from subclasses. * Uses timeouts and output passed as parameters during the waiting. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @param timeouts timeouts to be used during the waiting. * @param output an output to be used during the waiting. * @return Component instance or null if component was not found. * @throws TimeoutExpiredException */ protected static Frame waitFrame(ComponentChooser chooser, int index, Timeouts timeouts, TestOut output) { try { FrameWaiter waiter = new FrameWaiter(); waiter.setTimeouts(timeouts); waiter.setOutput(output); return((Frame)waiter.waitFrame(new FrameFinder(chooser), index)); } catch(InterruptedException e) { output.printStackTrace(e); return(null); } } /** * Checks component type. */ public static class FrameFinder extends Finder { /** * Constructs FrameFinder. * @param sf other searching criteria. */ public FrameFinder(ComponentChooser sf) { super(Frame.class, sf); } /** * Constructs FrameFinder. */ public FrameFinder() { super(Frame.class); } } /** * Allows to find component by title. */ public static class FrameByTitleFinder implements ComponentChooser { String title; StringComparator comparator; /** * Constructs FrameByTitleFinder. * @param t a text pattern * @param comparator specifies string comparision algorithm. */ public FrameByTitleFinder(String t, StringComparator comparator) { title = t; this.comparator = comparator; } /** * Constructs FrameByTitleFinder. * @param t a text pattern */ public FrameByTitleFinder(String t) { this(t, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof Frame) { if(((Frame)comp).isShowing() && ((Frame)comp).getTitle() != null) { return(comparator.equals(((Frame)comp).getTitle(), title)); } } return(false); } public String getDescription() { return("Frame with title \"" + title + "\""); } } } Jemmy2/src/org/netbeans/jemmy/operators/JInternalFrameOperator.java0000644000175000017500000012074311245712347024536 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Rectangle; import java.beans.PropertyVetoException; import java.util.Hashtable; import javax.swing.Icon; import javax.swing.JDesktopPane; import javax.swing.JInternalFrame; import javax.swing.JLayeredPane; import javax.swing.JMenuBar; import javax.swing.JScrollPane; import javax.swing.JInternalFrame.JDesktopIcon; import javax.swing.event.InternalFrameListener; import javax.swing.plaf.InternalFrameUI; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyInputException; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.FrameDriver; import org.netbeans.jemmy.drivers.InternalFrameDriver; import org.netbeans.jemmy.drivers.WindowDriver; import org.netbeans.jemmy.util.EmptyVisualizer; /** * Class provides necessary functionality to operate with javax.swing.JInternalFrame component. * * Some methods can throw WrongInternalFrameStateException exception. * *

Timeouts used:
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.MouseClickTimeout - time between mouse pressing and releasing
* AbstractButtonOperator.PushButtonTimeout - time between button pressing and releasing
* JScrollBarOperator.WholeScrollTimeout - time for the whole scrolling
. * * @see org.netbeans.jemmy.Timeouts * @see WrongInternalFrameStateException * @author Alexandre Iline (alexandre.iline@sun.com) */ public class JInternalFrameOperator extends JComponentOperator implements Outputable, Timeoutable { /** * Identifier for a "title" property. * @see #getDump */ public static final String TITLE_DPROP = "Title"; /** * Identifier for a "state" property. * @see #getDump */ public static final String STATE_DPROP = "State"; /** * Identifier for a "normal" value of "state" property. * @see #getDump */ public static final String STATE_NORMAL_DPROP_VALUE = "NORMAL"; /** * Identifier for a "closed" value of "state" property. * @see #getDump */ public static final String STATE_CLOSED_DPROP_VALUE = "CLOSED"; /** * Identifier for a "iconified" value of "state" property. * @see #getDump */ public static final String STATE_ICONIFIED_DPROP_VALUE = "ICONIFIED"; /** * Identifier for a "maximized" value of "state" property. * @see #getDump */ public static final String STATE_MAXIMAZED_DPROP_VALUE = "MAXIMIZED"; /** * Identifier for a "resizable" property. * @see #getDump */ public static final String IS_RESIZABLE_DPROP = "Resizable"; /** * Identifier for a "selected" property. * @see #getDump */ public static final String IS_SELECTED_DPROP = "Selected"; /** * A minimizing button. */ protected JButtonOperator minOper = null; /** * A maximizing button. */ protected JButtonOperator maxOper = null; /** * A close button. */ protected JButtonOperator closeOper = null; /** * A title operator. */ protected ContainerOperator titleOperator = null; private TestOut output; private Timeouts timeouts; private JDesktopIconOperator iconOperator; WindowDriver wDriver; FrameDriver fDriver; InternalFrameDriver iDriver; /** * Constructor. * @param b a component */ public JInternalFrameOperator(JInternalFrame b) { super(b); wDriver = DriverManager.getWindowDriver(getClass()); fDriver = DriverManager.getFrameDriver(getClass()); iDriver = DriverManager.getInternalFrameDriver(getClass()); } /** * Constructs a JInternalFrameOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JInternalFrameOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JInternalFrame)cont. waitSubComponent(new JInternalFrameFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JInternalFrameOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JInternalFrameOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public JInternalFrameOperator(ContainerOperator cont, String text, int index) { this(findOne(cont, text, index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public JInternalFrameOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * */ public JInternalFrameOperator(ContainerOperator cont, int index) { this((JInternalFrame) waitComponent(cont, new JInternalFrameFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * */ public JInternalFrameOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JInternalframe in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JInternalframe instance or null if component was not found. */ public static JInternalFrame findJInternalFrame(Container cont, ComponentChooser chooser, int index) { Component res = findComponent(cont, new JInternalFrameFinder(chooser), index); if(res instanceof JInternalFrame) { return((JInternalFrame)res); } else if(res instanceof JInternalFrame.JDesktopIcon) { return(((JInternalFrame.JDesktopIcon)res).getInternalFrame()); } else { return(null); } } /** * Searches JInternalframe in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JInternalframe instance or null if component was not found. */ public static JInternalFrame findJInternalFrame(Container cont, ComponentChooser chooser) { return(findJInternalFrame(cont, chooser, 0)); } /** * Searches JInternalframe by title. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JInternalframe instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JInternalFrame findJInternalFrame(Container cont, String text, boolean ce, boolean ccs, int index) { return(findJInternalFrame(cont, new JInternalFrameByTitleFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches JInternalframe by title. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JInternalframe instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JInternalFrame findJInternalFrame(Container cont, String text, boolean ce, boolean ccs) { return(findJInternalFrame(cont, text, ce, ccs, 0)); } /** * Searches JInternalFrame object which component lies on. * @param comp Component to find JInternalFrame under. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JInternalFrame instance or null if component was not found. */ public static JInternalFrame findJInternalFrameUnder(Component comp, ComponentChooser chooser) { return((JInternalFrame)findContainerUnder(comp, new JInternalFrameFinder(chooser))); } /** * Searches JInternalFrame object which component lies on. * @param comp Component to find JInternalFrame under. * @return JInternalFrame instance or null if component was not found. */ public static JInternalFrame findJInternalFrameUnder(Component comp) { return(findJInternalFrameUnder(comp, new JInternalFrameFinder())); } /** * Waits JInternalframe in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JInternalframe instance. * */ public static JInternalFrame waitJInternalFrame(final Container cont, final ComponentChooser chooser, final int index) { Component res = waitComponent(cont, new JInternalFrameFinder(chooser), index); if(res instanceof JInternalFrame) { return((JInternalFrame)res); } else if(res instanceof JInternalFrame.JDesktopIcon) { return(((JInternalFrame.JDesktopIcon)res).getInternalFrame()); } else { throw(new TimeoutExpiredException(chooser.getDescription())); } } /** * Waits JInternalframe in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JInternalframe instance. * */ public static JInternalFrame waitJInternalFrame(Container cont, ComponentChooser chooser) { return(waitJInternalFrame(cont, chooser, 0)); } /** * Waits JInternalframe by title. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JInternalframe instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public static JInternalFrame waitJInternalFrame(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitJInternalFrame(cont, new JInternalFrameByTitleFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits JInternalframe by title. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JInternalframe instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public static JInternalFrame waitJInternalFrame(Container cont, String text, boolean ce, boolean ccs) { return(waitJInternalFrame(cont, text, ce, ccs, 0)); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void setTimeouts(Timeouts times) { timeouts = times; super.setTimeouts(timeouts); } public Timeouts getTimeouts() { return(timeouts); } /** * Iconifies frame. * Note: frame should not be iconified and should be iconifiable. * @throws WrongInternalFrameStateException * */ public void iconify() { output.printLine("Iconify JInternalFrame\n : " + toStringSource()); output.printGolden("Iconify JInternalFrame \"" + getTitle() + "\""); checkIconified(false); makeComponentVisible(); fDriver.iconify(this); if(getVerification()) { waitIcon(true); } } /** * Deiconifies frame. * Note: frame should be iconified. * @throws WrongInternalFrameStateException * */ public void deiconify() { output.printLine("Deiconify JInternalFrame\n : " + toStringSource()); output.printGolden("Deiconify JInternalFrame \"" + getTitle() + "\""); checkIconified(true); fDriver.deiconify(this); if(getVerification()) { waitIcon(false); } } /** * Maximizes frame. * Note: frame should not be iconified. * * @throws WrongInternalFrameStateException */ public void maximize() { output.printLine("Maximize JInternalFrame\n : " + toStringSource()); output.printGolden("Maximize JInternalFrame \"" + getTitle() + "\""); checkIconified(false); makeComponentVisible(); fDriver.maximize(this); if(getVerification()) { waitMaximum(true); } } /** * Demaximizes frame. * Note: frame should not be iconified. * * @throws WrongInternalFrameStateException */ public void demaximize() { output.printLine("Demaximize JInternalFrame\n : " + toStringSource()); output.printGolden("Demaximize JInternalFrame \"" + getTitle() + "\""); checkIconified(false); makeComponentVisible(); fDriver.demaximize(this); if(getVerification()) { waitMaximum(false); } } /** * Moves frame to new location. * Note: frame should not be iconified. * @param x X coordinate of a new frame location. * @param y Y coordinate of a new frame location. * @throws WrongInternalFrameStateException */ public void move(int x, int y) { checkIconified(false); output.printLine("Move JInternalFrame to (" + Integer.toString(x) + "," + Integer.toString(y) + ")" + " position\n : " + toStringSource()); output.printGolden("Move " + getTitle() + " JInternalFrame to (" + Integer.toString(x) + "," + Integer.toString(y) + ")" + " position"); checkIconified(false); wDriver.move(this, x, y); } /** * Resizes frame. * Note: frame should not be iconified. * @param width New frame width. * @param height New frame height. * @throws WrongInternalFrameStateException */ public void resize(int width, int height) { output.printLine("Resize JInternalFrame to (" + Integer.toString(width) + "," + Integer.toString(height) + ")" + " size\n : " + toStringSource()); output.printGolden("Resize " + getTitle() + " JInternalFrame to (" + Integer.toString(width) + "," + Integer.toString(height) + ")" + " size"); checkIconified(false); wDriver.resize(this, width, height); } /** * Activates frame. * Note: frame should not be iconified. * @throws WrongInternalFrameStateException */ public void activate() { checkIconified(false); wDriver.activate(this); } /** * Closes the frame. */ public void close() { checkIconified(false); wDriver.close(this); } /** * Scrolls to internal frame's rectangle. * @param x Horizontal rectangle coordinate * @param y Vertical rectangle coordinate * @param width rectangle width * @param height rectangle height * */ public void scrollToRectangle(int x, int y, int width, int height) { output.printTrace("Scroll desktop pane to make \"" + getTitle() + "\" internal frame visible"); output.printGolden("Scroll desktop pane to make \"" + getTitle() + "\" internal frame visible"); makeComponentVisible(); //try to find JScrollPane under. JScrollPane scroll; if(isIcon()) { scroll = (JScrollPane)iconOperator.getContainer(new JScrollPaneOperator. JScrollPaneFinder(ComponentSearcher. getTrueChooser("JScrollPane"))); } else { scroll = (JScrollPane)getContainer(new JScrollPaneOperator. JScrollPaneFinder(ComponentSearcher. getTrueChooser("JScrollPane"))); } if(scroll == null) { return; } JScrollPaneOperator scroller = new JScrollPaneOperator(scroll); scroller.copyEnvironment(this); scroller.setVisualizer(new EmptyVisualizer()); scroller.scrollToComponentRectangle(isIcon() ? iconOperator.getSource() : getSource(), x, y, width, height); } /** * Scrolls to internal frame's rectangle. * @param rect a rectangle to scroll to. */ public void scrollToRectangle(Rectangle rect) { scrollToRectangle(rect.x, rect.y, rect.width, rect.height); } /** * Scrolls to internal frame. * */ public void scrollToFrame() { if(isIcon()) { scrollToRectangle(0, 0, iconOperator.getWidth(), iconOperator.getHeight()); } else { scrollToRectangle(0, 0, getWidth(), getHeight()); } } /** * Waits for a minimize button inside the title pane. * @return a button operator */ public JButtonOperator getMinimizeButton() { initOperators(); return(minOper); } /** * Waits for a maximize button inside the title pane. * @return a button operator */ public JButtonOperator getMaximizeButton() { initOperators(); return(maxOper); } /** * Waits for a close button inside the title pane. * @return a button operator */ public JButtonOperator getCloseButton() { initOperators(); return(closeOper); } /** * Waits for the title pane. * @return a button operator */ public ContainerOperator getTitleOperator() { initOperators(); return(titleOperator); } /** * Creates an operator for an desktop icon. * @return an icon operator. */ public JDesktopIconOperator getIconOperator() { initOperators(); return(iconOperator); } /** * Waits for the frame to be iconified or deiconified. * @param icon whether the frame needs to be iconified. */ public void waitIcon(final boolean icon) { waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(((JInternalFrame)comp).isIcon() == icon); } public String getDescription() { return("Iconified JInternalFrame"); } }); } /** * Waits for the frame to be maximized or demaximized. * @param maximum whether the frame needs to be maximized. */ public void waitMaximum(final boolean maximum) { waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(((JInternalFrame)comp).isMaximum() == maximum); } public String getDescription() { return("Maximizied JInternalFrame"); } }); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); result.put(TITLE_DPROP, ((JInternalFrame)getSource()).getTitle()); String state = STATE_NORMAL_DPROP_VALUE; if (((JInternalFrame)getSource()).isClosed()) { state = STATE_CLOSED_DPROP_VALUE; } else if(((JInternalFrame)getSource()).isIcon()) { state = STATE_ICONIFIED_DPROP_VALUE; } else if(((JInternalFrame)getSource()).isMaximum()) { state = STATE_MAXIMAZED_DPROP_VALUE; } result.put(STATE_DPROP, state); result.put(IS_RESIZABLE_DPROP, ((JInternalFrame)getSource()).isResizable() ? "true" : "false"); result.put(IS_SELECTED_DPROP, ((JInternalFrame)getSource()).isSelected() ? "true" : "false"); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JInternalFrame.addInternalFrameListener(InternalFrameListener) through queue*/ public void addInternalFrameListener(final InternalFrameListener internalFrameListener) { runMapping(new MapVoidAction("addInternalFrameListener") { public void map() { ((JInternalFrame)getSource()).addInternalFrameListener(internalFrameListener); }});} /**Maps JInternalFrame.dispose() through queue*/ public void dispose() { runMapping(new MapVoidAction("dispose") { public void map() { ((JInternalFrame)getSource()).dispose(); }});} /**Maps JInternalFrame.getContentPane() through queue*/ public Container getContentPane() { return((Container)runMapping(new MapAction("getContentPane") { public Object map() { return(((JInternalFrame)getSource()).getContentPane()); }}));} /**Maps JInternalFrame.getDefaultCloseOperation() through queue*/ public int getDefaultCloseOperation() { return(runMapping(new MapIntegerAction("getDefaultCloseOperation") { public int map() { return(((JInternalFrame)getSource()).getDefaultCloseOperation()); }}));} /**Maps JInternalFrame.getDesktopIcon() through queue*/ public JDesktopIcon getDesktopIcon() { return((JDesktopIcon)runMapping(new MapAction("getDesktopIcon") { public Object map() { return(((JInternalFrame)getSource()).getDesktopIcon()); }}));} /**Maps JInternalFrame.getDesktopPane() through queue*/ public JDesktopPane getDesktopPane() { return((JDesktopPane)runMapping(new MapAction("getDesktopPane") { public Object map() { return(((JInternalFrame)getSource()).getDesktopPane()); }}));} /**Maps JInternalFrame.getFrameIcon() through queue*/ public Icon getFrameIcon() { return((Icon)runMapping(new MapAction("getFrameIcon") { public Object map() { return(((JInternalFrame)getSource()).getFrameIcon()); }}));} /**Maps JInternalFrame.getGlassPane() through queue*/ public Component getGlassPane() { return((Component)runMapping(new MapAction("getGlassPane") { public Object map() { return(((JInternalFrame)getSource()).getGlassPane()); }}));} /**Maps JInternalFrame.getJMenuBar() through queue*/ public JMenuBar getJMenuBar() { return((JMenuBar)runMapping(new MapAction("getJMenuBar") { public Object map() { return(((JInternalFrame)getSource()).getJMenuBar()); }}));} /**Maps JInternalFrame.getLayer() through queue*/ public int getLayer() { return(runMapping(new MapIntegerAction("getLayer") { public int map() { return(((JInternalFrame)getSource()).getLayer()); }}));} /**Maps JInternalFrame.getLayeredPane() through queue*/ public JLayeredPane getLayeredPane() { return((JLayeredPane)runMapping(new MapAction("getLayeredPane") { public Object map() { return(((JInternalFrame)getSource()).getLayeredPane()); }}));} /**Maps JInternalFrame.getTitle() through queue*/ public String getTitle() { return((String)runMapping(new MapAction("getTitle") { public Object map() { return(((JInternalFrame)getSource()).getTitle()); }}));} /**Maps JInternalFrame.getUI() through queue*/ public InternalFrameUI getUI() { return((InternalFrameUI)runMapping(new MapAction("getUI") { public Object map() { return(((JInternalFrame)getSource()).getUI()); }}));} /**Maps JInternalFrame.getWarningString() through queue*/ public String getWarningString() { return((String)runMapping(new MapAction("getWarningString") { public Object map() { return(((JInternalFrame)getSource()).getWarningString()); }}));} /**Maps JInternalFrame.isClosable() through queue*/ public boolean isClosable() { return(runMapping(new MapBooleanAction("isClosable") { public boolean map() { return(((JInternalFrame)getSource()).isClosable()); }}));} /**Maps JInternalFrame.isClosed() through queue*/ public boolean isClosed() { return(runMapping(new MapBooleanAction("isClosed") { public boolean map() { return(((JInternalFrame)getSource()).isClosed()); }}));} /**Maps JInternalFrame.isIcon() through queue*/ public boolean isIcon() { return(runMapping(new MapBooleanAction("isIcon") { public boolean map() { return(((JInternalFrame)getSource()).isIcon()); }}));} /**Maps JInternalFrame.isIconifiable() through queue*/ public boolean isIconifiable() { return(runMapping(new MapBooleanAction("isIconifiable") { public boolean map() { return(((JInternalFrame)getSource()).isIconifiable()); }}));} /**Maps JInternalFrame.isMaximizable() through queue*/ public boolean isMaximizable() { return(runMapping(new MapBooleanAction("isMaximizable") { public boolean map() { return(((JInternalFrame)getSource()).isMaximizable()); }}));} /**Maps JInternalFrame.isMaximum() through queue*/ public boolean isMaximum() { return(runMapping(new MapBooleanAction("isMaximum") { public boolean map() { return(((JInternalFrame)getSource()).isMaximum()); }}));} /**Maps JInternalFrame.isResizable() through queue*/ public boolean isResizable() { return(runMapping(new MapBooleanAction("isResizable") { public boolean map() { return(((JInternalFrame)getSource()).isResizable()); }}));} /**Maps JInternalFrame.isSelected() through queue*/ public boolean isSelected() { return(runMapping(new MapBooleanAction("isSelected") { public boolean map() { return(((JInternalFrame)getSource()).isSelected()); }}));} /**Maps JInternalFrame.moveToBack() through queue*/ public void moveToBack() { runMapping(new MapVoidAction("moveToBack") { public void map() { ((JInternalFrame)getSource()).moveToBack(); }});} /**Maps JInternalFrame.moveToFront() through queue*/ public void moveToFront() { runMapping(new MapVoidAction("moveToFront") { public void map() { ((JInternalFrame)getSource()).moveToFront(); }});} /**Maps JInternalFrame.pack() through queue*/ public void pack() { runMapping(new MapVoidAction("pack") { public void map() { ((JInternalFrame)getSource()).pack(); }});} /**Maps JInternalFrame.removeInternalFrameListener(InternalFrameListener) through queue*/ public void removeInternalFrameListener(final InternalFrameListener internalFrameListener) { runMapping(new MapVoidAction("removeInternalFrameListener") { public void map() { ((JInternalFrame)getSource()).removeInternalFrameListener(internalFrameListener); }});} /**Maps JInternalFrame.setClosable(boolean) through queue*/ public void setClosable(final boolean b) { runMapping(new MapVoidAction("setClosable") { public void map() { ((JInternalFrame)getSource()).setClosable(b); }});} /**Maps JInternalFrame.setClosed(boolean) through queue*/ public void setClosed(final boolean b) { runMapping(new MapVoidAction("setClosed") { public void map() throws PropertyVetoException { ((JInternalFrame)getSource()).setClosed(b); }});} /**Maps JInternalFrame.setContentPane(Container) through queue*/ public void setContentPane(final Container container) { runMapping(new MapVoidAction("setContentPane") { public void map() { ((JInternalFrame)getSource()).setContentPane(container); }});} /**Maps JInternalFrame.setDefaultCloseOperation(int) through queue*/ public void setDefaultCloseOperation(final int i) { runMapping(new MapVoidAction("setDefaultCloseOperation") { public void map() { ((JInternalFrame)getSource()).setDefaultCloseOperation(i); }});} /**Maps JInternalFrame.setDesktopIcon(JDesktopIcon) through queue*/ public void setDesktopIcon(final JDesktopIcon jDesktopIcon) { runMapping(new MapVoidAction("setDesktopIcon") { public void map() { ((JInternalFrame)getSource()).setDesktopIcon(jDesktopIcon); }});} /**Maps JInternalFrame.setFrameIcon(Icon) through queue*/ public void setFrameIcon(final Icon icon) { runMapping(new MapVoidAction("setFrameIcon") { public void map() { ((JInternalFrame)getSource()).setFrameIcon(icon); }});} /**Maps JInternalFrame.setGlassPane(Component) through queue*/ public void setGlassPane(final Component component) { runMapping(new MapVoidAction("setGlassPane") { public void map() { ((JInternalFrame)getSource()).setGlassPane(component); }});} /**Maps JInternalFrame.setIcon(boolean) through queue*/ public void setIcon(final boolean b) { runMapping(new MapVoidAction("setIcon") { public void map() throws PropertyVetoException { ((JInternalFrame)getSource()).setIcon(b); }});} /**Maps JInternalFrame.setIconifiable(boolean) through queue*/ public void setIconifiable(final boolean b) { runMapping(new MapVoidAction("setIconifiable") { public void map() { ((JInternalFrame)getSource()).setIconifiable(b); }});} /**Maps JInternalFrame.setJMenuBar(JMenuBar) through queue*/ public void setJMenuBar(final JMenuBar jMenuBar) { runMapping(new MapVoidAction("setJMenuBar") { public void map() { ((JInternalFrame)getSource()).setJMenuBar(jMenuBar); }});} /**Maps JInternalFrame.setLayer(Integer) through queue*/ public void setLayer(final Integer integer) { runMapping(new MapVoidAction("setLayer") { public void map() { ((JInternalFrame)getSource()).setLayer(integer); }});} /**Maps JInternalFrame.setLayeredPane(JLayeredPane) through queue*/ public void setLayeredPane(final JLayeredPane jLayeredPane) { runMapping(new MapVoidAction("setLayeredPane") { public void map() { ((JInternalFrame)getSource()).setLayeredPane(jLayeredPane); }});} /**Maps JInternalFrame.setMaximizable(boolean) through queue*/ public void setMaximizable(final boolean b) { runMapping(new MapVoidAction("setMaximizable") { public void map() { ((JInternalFrame)getSource()).setMaximizable(b); }});} /**Maps JInternalFrame.setMaximum(boolean) through queue*/ public void setMaximum(final boolean b) { runMapping(new MapVoidAction("setMaximum") { public void map() throws PropertyVetoException { ((JInternalFrame)getSource()).setMaximum(b); }});} /**Maps JInternalFrame.setResizable(boolean) through queue*/ public void setResizable(final boolean b) { runMapping(new MapVoidAction("setResizable") { public void map() { ((JInternalFrame)getSource()).setResizable(b); }});} /**Maps JInternalFrame.setSelected(boolean) through queue*/ public void setSelected(final boolean b) { runMapping(new MapVoidAction("setSelected") { public void map() throws PropertyVetoException { ((JInternalFrame)getSource()).setSelected(b); }});} /**Maps JInternalFrame.setTitle(String) through queue*/ public void setTitle(final String string) { runMapping(new MapVoidAction("setTitle") { public void map() { ((JInternalFrame)getSource()).setTitle(string); }});} /**Maps JInternalFrame.setUI(InternalFrameUI) through queue*/ public void setUI(final InternalFrameUI internalFrameUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JInternalFrame)getSource()).setUI(internalFrameUI); }});} /**Maps JInternalFrame.toBack() through queue*/ public void toBack() { runMapping(new MapVoidAction("toBack") { public void map() { ((JInternalFrame)getSource()).toBack(); }});} /**Maps JInternalFrame.toFront() through queue*/ public void toFront() { runMapping(new MapVoidAction("toFront") { public void map() { ((JInternalFrame)getSource()).toFront(); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Uses InternalframeDriver to get a title pane. * @return a title pane. */ protected Container findTitlePane() { return((Container)iDriver.getTitlePane(this)); } /** * Initiaites suboperators. */ protected void initOperators() { iconOperator = new JDesktopIconOperator(((JInternalFrame)getSource()).getDesktopIcon()); iconOperator.copyEnvironment(this); Container titlePane = findTitlePane(); if(!isIcon() && titlePane != null) { if(titleOperator == null) { titleOperator = new ContainerOperator(titlePane); int bttCount = 0; if(getContainer(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp instanceof JDesktopPane); } public String getDescription() { return("Desctop pane"); } }) != null) { minOper = new JButtonOperator(titleOperator, bttCount); bttCount++; if(((JInternalFrame)getSource()).isMaximizable()) { maxOper = new JButtonOperator(titleOperator, bttCount); bttCount++; } else { maxOper = null; } } else { minOper = null; maxOper = null; } if(isClosable()) { closeOper = new JButtonOperator(titleOperator, bttCount); } else { closeOper = null; } } } else { titleOperator = null; minOper = null; maxOper = null; closeOper = null; } } //throw exception if state is wrong private void checkIconified(boolean shouldBeIconified) { if( shouldBeIconified && !isIcon() || !shouldBeIconified && isIcon()) { throw(new WrongInternalFrameStateException("JInternal frame should " + (shouldBeIconified ? "" : "not") + " be iconified to produce this operation", getSource())); } } private static JInternalFrame findOne(ContainerOperator cont, String text, int index) { Component source = waitComponent(cont, new JInternalFrameByTitleFinder(text, cont.getComparator()), index); if(source instanceof JInternalFrame) { return((JInternalFrame)source); } else if(source instanceof JInternalFrame.JDesktopIcon) { return(((JInternalFrame.JDesktopIcon)source).getInternalFrame()); } else { throw(new TimeoutExpiredException("No internal frame was found")); } } /** * Exception can be throwht if as a result of an attempt to produce * operation for the frame in incorrect state. * Like activate iconified frame, for example. */ public class WrongInternalFrameStateException extends JemmyInputException { /** * Constructs a JInternalFrameOperator$WrongInternalFrameStateException object. * @param message an exception message. * @param comp an internal frame. */ public WrongInternalFrameStateException(String message, Component comp) { super(message, comp); } } /** * Allows to find component by title. */ public static class JInternalFrameByTitleFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs JInternalFrameByTitleFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public JInternalFrameByTitleFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs JInternalFrameByTitleFinder. * @param lb a text pattern */ public JInternalFrameByTitleFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JInternalFrame || comp instanceof JInternalFrame.JDesktopIcon) { JInternalFrame frame = null; if(comp instanceof JInternalFrame) { frame = (JInternalFrame)comp; } else { JDesktopIconOperator io = new JDesktopIconOperator((JInternalFrame.JDesktopIcon)comp); frame = io.getInternalFrame(); } if(frame.getTitle() != null) { return(comparator.equals(frame.getTitle(), label)); } } return(false); } public String getDescription() { return("JInternalFrame with title \"" + label + "\""); } } /** * Class to operate with javax.swing.JInternalFrame.JDesktopIconOperator component. */ public static class JDesktopIconOperator extends JComponentOperator implements Outputable, Timeoutable { private TestOut output; private Timeouts timeouts; /** * Constructs JDesktopIconOperator. * @param b a component */ public JDesktopIconOperator(JInternalFrame.JDesktopIcon b) { super(b); setOutput(JemmyProperties.getCurrentOutput()); setTimeouts(JemmyProperties.getCurrentTimeouts()); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void setTimeouts(Timeouts times) { timeouts = times; super.setTimeouts(timeouts); } public Timeouts getTimeouts() { return(timeouts); } /** * Creates an operator for the correspondent intenal frame. * @return an operator. */ public JInternalFrame getInternalFrame() { return((JInternalFrame)getEventDispatcher(). invokeExistingMethod("getInternalFrame", null, null, output)); } /** * Pushs the deiconifying button. */ public void pushButton() { new JButtonOperator(this).push(); } } /** * Checks component type. */ public static class JInternalFrameFinder implements ComponentChooser { ComponentChooser sf = null; /** * Constructs JInternalFrameFinder. * @param sf other searching criteria. */ public JInternalFrameFinder(ComponentChooser sf) { this.sf = sf; } /** * Constructs JInternalFrameFinder. */ public JInternalFrameFinder() { this(ComponentSearcher.getTrueChooser("JInternalFrame or JInternalFrame.JDesktopIcon")); } public boolean checkComponent(Component comp) { return((comp instanceof JInternalFrame || comp instanceof JInternalFrame.JDesktopIcon) && sf.checkComponent(comp)); } public String getDescription() { return(sf.getDescription()); } } } Jemmy2/src/org/netbeans/jemmy/operators/DialogOperator.java0000644000175000017500000004014011245712237023062 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Dialog; import java.awt.Window; import java.util.Hashtable; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.DialogWaiter; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeouts; /** *

Timeouts used:
* DialogWaiter.WaitDialogTimeout - time to wait dialog displayed
* DialogWaiter.AfterDialogTimeout - time to sleep after dialog has been dispayed
* ComponentOperator.WaitStateTimeout - time to wait for title
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class DialogOperator extends WindowOperator { /** * Identifier for a title property. * @see #getDump */ public static final String TITLE_DPROP = "Title"; /** * Identifier for a modal property. * @see #getDump */ public static final String IS_MODAL_DPROP = "Modal"; /** * Identifier for a resizable property. * @see #getDump */ public static final String IS_RESIZABLE_DPROP = "Resizable"; /** * Constructs a DialogOperator object. * @param w window */ public DialogOperator(Dialog w) { super(w); } /** * Constructs a DialogOperator object. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @param env an operator to copy environment from. */ public DialogOperator(ComponentChooser chooser, int index, Operator env) { this(waitDialog(new DialogFinder(chooser), index, env.getTimeouts(), env.getOutput())); copyEnvironment(env); } /** * Constructs a DialogOperator object. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public DialogOperator(ComponentChooser chooser, int index) { this(chooser, index, Operator.getEnvironmentOperator()); } /** * Constructs a DialogOperator object. * @param chooser a component chooser specifying searching criteria. */ public DialogOperator(ComponentChooser chooser) { this(chooser, 0); } /** * Constructs a DialogOperator object. * @param owner window - owner * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public DialogOperator(WindowOperator owner, ComponentChooser chooser, int index) { this((Dialog)owner. waitSubWindow(new DialogFinder(chooser), index)); copyEnvironment(owner); } /** * Constructs a DialogOperator object. * @param owner window - owner * @param chooser a component chooser specifying searching criteria. */ public DialogOperator(WindowOperator owner, ComponentChooser chooser) { this(owner, chooser, 0); } /** * Constructor. * Waits for a dialog to show. The dialog is identified as the * index+1'th java.awt.Dialog that shows, is * owned by the window managed by the WindowOperator * owner, and that has the desired title. Uses owner's * timeout and output for waiting and to init this operator. * @param owner Operator pointing to a window owner. * @param title The desired title. * @param index Ordinal index. The first dialog has index 0. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public DialogOperator(WindowOperator owner, String title, int index) { this(waitDialog(owner, new DialogByTitleFinder(title, owner.getComparator()), index)); copyEnvironment(owner); } /** * Uses owner's timeout and output for waiting and to init operator. * Waits for a dialog to show. The dialog is identified as the * first java.awt.Dialog that shows, is * owned by the window managed by the WindowOperator * owner, and that has the desired title. Uses owner's * timeout and output for waiting and to init this operator. * @param owner Operator pointing to a window owner. * @param title The desired title. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public DialogOperator(WindowOperator owner, String title) { this(owner, title, 0); } /** * Constructor. * Waits for the index'th dialog between owner's children. * Uses owner'th timeout and output for waiting and to init operator. * @param owner Operator pointing to a window owner. * @param index Ordinal component index. * @throws TimeoutExpiredException */ public DialogOperator(WindowOperator owner, int index) { this((Dialog) waitDialog(owner, new DialogFinder(), index)); copyEnvironment(owner); } /** * Constructor. * Waits for the first dialog between owner's children. * Uses owner'th timeout and output for waiting and to init operator. * @param owner Operator pointing to a window owner. * @throws TimeoutExpiredException */ public DialogOperator(WindowOperator owner) { this(owner, 0); } /** * Constructor. * Waits for the dialog with "title" subtitle. * Constructor can be used in complicated cases when * output or timeouts should differ from default. * @param title a window title * @param index Ordinal component index. * @param env an operator to copy environment from. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public DialogOperator(String title, int index, Operator env) { this(new DialogByTitleFinder(title, env.getComparator()), index, env); } /** * Constructor. * Waits for the dialog with "title" subtitle. * Uses current timeouts and output values. * @param title a window title * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see JemmyProperties#getCurrentTimeouts() * @see JemmyProperties#getCurrentOutput() * @throws TimeoutExpiredException */ public DialogOperator(String title, int index){ this(title, index, ComponentOperator.getEnvironmentOperator()); } /** * Constructor. * Waits for the dialog with "title" subtitle. * Uses current timeouts and output values. * @param title a window title * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see JemmyProperties#getCurrentTimeouts() * @see JemmyProperties#getCurrentOutput() * @throws TimeoutExpiredException */ public DialogOperator(String title) { this(title, 0); } /** * Constructor. * Waits for the index'th dialog. * Uses current timeout and output for waiting and to init operator. * @param index Ordinal component index. * @throws TimeoutExpiredException */ public DialogOperator(int index) { this((Dialog) waitDialog(new DialogFinder(), index, ComponentOperator.getEnvironmentOperator().getTimeouts(), ComponentOperator.getEnvironmentOperator().getOutput())); copyEnvironment(ComponentOperator.getEnvironmentOperator()); } /** * Constructor. * Waits for the first dialog. * Uses current timeout and output for waiting and to init operator. * @throws TimeoutExpiredException */ public DialogOperator() { this(0); } /** * Waits for title. Uses getComparator() comparator. * @param title Title to wait for. */ public void waitTitle(final String title) { getOutput().printLine("Wait \"" + title + "\" title of dialog \n : "+ toStringSource()); getOutput().printGolden("Wait \"" + title + "\" title"); waitState(new DialogByTitleFinder(title, getComparator())); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); if(((Dialog)getSource()).getTitle() != null) { result.put(TITLE_DPROP, ((Dialog)getSource()).getTitle()); } result.put(IS_MODAL_DPROP, ((Dialog)getSource()).isModal() ? "true" : "false"); result.put(IS_RESIZABLE_DPROP, ((Dialog)getSource()).isResizable() ? "true" : "false"); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps Dialog.getTitle() through queue*/ public String getTitle() { return((String)runMapping(new MapAction("getTitle") { public Object map() { return(((Dialog)getSource()).getTitle()); }}));} /**Maps Dialog.isModal() through queue*/ public boolean isModal() { return(runMapping(new MapBooleanAction("isModal") { public boolean map() { return(((Dialog)getSource()).isModal()); }}));} /**Maps Dialog.isResizable() through queue*/ public boolean isResizable() { return(runMapping(new MapBooleanAction("isResizable") { public boolean map() { return(((Dialog)getSource()).isResizable()); }}));} /**Maps Dialog.setModal(boolean) through queue*/ public void setModal(final boolean b) { runMapping(new MapVoidAction("setModal") { public void map() { ((Dialog)getSource()).setModal(b); }});} /**Maps Dialog.setResizable(boolean) through queue*/ public void setResizable(final boolean b) { runMapping(new MapVoidAction("setResizable") { public void map() { ((Dialog)getSource()).setResizable(b); }});} /**Maps Dialog.setTitle(String) through queue*/ public void setTitle(final String string) { runMapping(new MapVoidAction("setTitle") { public void map() { ((Dialog)getSource()).setTitle(string); }});} //End of mapping // //////////////////////////////////////////////////////// /** * A method to be used from subclasses. * Uses timeouts and output passed as parameters during the waiting. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @param timeouts timeouts to be used during the waiting. * @param output an output to be used during the waiting. * @return Component instance or null if component was not found. */ protected static Dialog waitDialog(ComponentChooser chooser, int index, Timeouts timeouts, TestOut output) { try { DialogWaiter waiter = new DialogWaiter(); waiter.setTimeouts(timeouts); waiter.setOutput(output); return((Dialog)waiter. waitDialog(new DialogFinder(chooser), index)); } catch(InterruptedException e) { output.printStackTrace(e); return(null); } } /** * A method to be used from subclasses. * Uses owner's timeouts and output during the waiting. * @param owner a window - dialog owner. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return Component instance or null if component was not found. */ protected static Dialog waitDialog(WindowOperator owner, ComponentChooser chooser, int index) { return(waitDialog((Window)owner.getSource(), chooser, index, owner.getTimeouts(), owner.getOutput())); } /** * A method to be used from subclasses. * Uses timeouts and output passed as parameters during the waiting. * @param owner a window - dialog owner. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @param timeouts timeouts to be used during the waiting. * @param output an output to be used during the waiting. * @return Component instance or null if component was not found. */ protected static Dialog waitDialog(Window owner, ComponentChooser chooser, int index, Timeouts timeouts, TestOut output) { try { DialogWaiter waiter = new DialogWaiter(); waiter.setTimeouts(timeouts); waiter.setOutput(output); return((Dialog)waiter. waitDialog(owner, new DialogFinder(chooser), index)); } catch(InterruptedException e) { JemmyProperties.getCurrentOutput().printStackTrace(e); return(null); } } /** * Checks component type. */ public static class DialogFinder extends Finder { /** * Constructs DialogFinder. * @param sf other searching criteria. */ public DialogFinder(ComponentChooser sf) { super(Dialog.class, sf); } /** * Constructs DialogFinder. */ public DialogFinder() { super(Dialog.class); } } /** * Allows to find component by title. */ public static class DialogByTitleFinder implements ComponentChooser { String title; StringComparator comparator; /** * Constructs DialogByTitleFinder. * @param t a text pattern * @param comparator specifies string comparision algorithm. */ public DialogByTitleFinder(String t, StringComparator comparator) { title = t; this.comparator = comparator; } /** * Constructs DialogByTitleFinder. * @param t a text pattern */ public DialogByTitleFinder(String t) { this(t, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof Dialog) { if(((Dialog)comp).isShowing() && ((Dialog)comp).getTitle() != null) { return(comparator.equals(((Dialog)comp).getTitle(), title)); } } return(false); } public String getDescription() { return("Dialog with title \"" + title + "\""); } } } Jemmy2/src/org/netbeans/jemmy/operators/JMenuOperator.java0000644000175000017500000011030411245712237022701 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.util.Hashtable; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.event.MenuListener; import org.netbeans.jemmy.Action; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.DescriptablePathChooser; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.MenuDriver; /** *

Timeouts used:
* JMenuOperator.WaitBeforePopupTimeout - time to sleep before popup expanding
* JMenuOperator.WaitPopupTimeout - time to wait popup displayed
* JMenuOperator.PushMenuTimeout - time for the whole menu operation
* JMenuItemOperator.PushMenuTimeout - time between button pressing and releasing
* ComponentOperator.WaitComponentTimeout - time to wait button displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait button enabled
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JMenuOperator extends JMenuItemOperator implements Outputable, Timeoutable{ /** * Identifier for a "submenu" properties. * @see #getDump */ public static final String SUBMENU_PREFIX_DPROP = "Submenu"; private final static long WAIT_POPUP_TIMEOUT = 60000; private final static long WAIT_BEFORE_POPUP_TIMEOUT = 0; private final static long PUSH_MENU_TIMEOUT = 60000; private Timeouts timeouts; private TestOut output; private MenuDriver driver; /** * Constructor. * @param menu a component */ public JMenuOperator(JMenu menu) { super(menu); driver = DriverManager.getMenuDriver(this); } /** * Constructs a JMenuOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JMenuOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JMenu)cont. waitSubComponent(new JMenuFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JMenuOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JMenuOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JMenuOperator(ContainerOperator cont, String text, int index) { this((JMenu)waitComponent(cont, new JMenuByLabelFinder(text, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JMenuOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JMenuOperator(ContainerOperator cont, int index) { this((JMenu) waitComponent(cont, new JMenuFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JMenuOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JMenu in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JMenu instance or null if component was not found. */ public static JMenu findJMenu(Container cont, ComponentChooser chooser, int index) { return((JMenu)findComponent(cont, new JMenuFinder(chooser), index)); } /** * Searches 0'th JMenu in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JMenu instance or null if component was not found. */ public static JMenu findJMenu(Container cont, ComponentChooser chooser) { return(findJMenu(cont, chooser, 0)); } /** * Searches JMenu by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JMenu instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JMenu findJMenu(Container cont, String text, boolean ce, boolean ccs, int index) { return(findJMenu(cont, new JMenuByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches JMenu by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JMenu instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JMenu findJMenu(Container cont, String text, boolean ce, boolean ccs) { return(findJMenu(cont, text, ce, ccs, 0)); } /** * Waits JMenu in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JMenu instance. * @throws TimeoutExpiredException */ public static JMenu waitJMenu(final Container cont, final ComponentChooser chooser, final int index) { return((JMenu)waitComponent(cont, new JMenuFinder(chooser), index)); } /** * Waits 0'th JMenu in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JMenu instance. * @throws TimeoutExpiredException */ public static JMenu waitJMenu(Container cont, ComponentChooser chooser) { return(waitJMenu(cont, chooser, 0)); } /** * Waits JMenu by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JMenu instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JMenu waitJMenu(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitJMenu(cont, new JMenuByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits JMenu by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JMenu instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JMenu waitJMenu(Container cont, String text, boolean ce, boolean ccs) { return(waitJMenu(cont, text, ce, ccs, 0)); } public static void performInit() { Timeouts.initDefault("JMenuOperator.WaitBeforePopupTimeout", WAIT_BEFORE_POPUP_TIMEOUT); Timeouts.initDefault("JMenuOperator.WaitPopupTimeout", WAIT_POPUP_TIMEOUT); Timeouts.initDefault("JMenuOperator.PushMenuTimeout", PUSH_MENU_TIMEOUT); } static { performInit(); } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { super.setOutput(out); output = out; } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = DriverManager.getMenuDriver(this); } /** * Pushes menu. * @param choosers Array of choosers to find menuItems to push. * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(final ComponentChooser[] choosers) { return((JMenuItem)produceTimeRestricted(new Action() { public Object launch(Object obj) { //TDB 1.5 menu workaround getQueueTool().waitEmpty(); Object result = driver.pushMenu(JMenuOperator.this, converChoosers(choosers)); getQueueTool().waitEmpty(); return(result); } public String getDescription() { return(createDescription(choosers)); } }, getTimeouts().getTimeout("JMenuOperator.PushMenuTimeout"))); } /** * Executes pushMenu(choosers) in a separate thread. * @param choosers Array of choosers to find menuItems to push. * @see #pushMenu(ComponentChooser[]) */ public void pushMenuNoBlock(final ComponentChooser[] choosers) { produceNoBlocking(new NoBlockingAction("Menu pushing") { public Object doAction(Object param) { //TDB 1.5 menu workaround getQueueTool().waitEmpty(); Object result = driver.pushMenu(JMenuOperator.this, converChoosers(choosers)); getQueueTool().waitEmpty(); return(result); } }); } /** * Pushes menu. * @param names an array of menu texts. * @param comparator a string comparision algorithm * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String[] names, StringComparator comparator) { return(pushMenu(JMenuItemOperator.createChoosers(names, comparator))); } /** * Pushes menu. * @param names Menu items texts. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException * @return Last pushed JMenuItem. * @deprecated Use pushMenu(String[]) or pushMenu(String[], StringComparator) */ public JMenuItem pushMenu(String[] names, boolean ce, boolean ccs) { return(pushMenu(names, new DefaultStringComparator(ce, ccs))); } /** * Executes pushMenu(names, ce, ccs) in a separate thread. * @param names an array of menu texts. * @param comparator a string comparision algorithm */ public void pushMenuNoBlock(String[] names, StringComparator comparator) { pushMenuNoBlock(JMenuItemOperator.createChoosers(names, comparator)); } /** * Executes pushMenu(names, ce, ccs) in a separate thread. * @param names Menu items texts. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @see #pushMenu(String[], boolean,boolean) * @deprecated Use pushMenuNoBlock(String[]) or pushMenuNoBlock(String[], StringComparator) */ public void pushMenuNoBlock(String[] names, boolean ce, boolean ccs) { pushMenuNoBlock(names, new DefaultStringComparator(ce, ccs)); } /** * Pushes menu. * Uses StringComparator assigned to this object, * @param names Menu items texts. * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String[] names) { return(pushMenu(names, getComparator())); } /** * Executes pushMenu(names) in a separate thread. * @param names Menu items texts. * @see #pushMenu(String[]) */ public void pushMenuNoBlock(String[] names) { pushMenuNoBlock(names, getComparator()); } /** * Pushes menu. * @param path a menu path. * @param delim a path delimiter. * @param comparator a string comparision algorithm * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String path, String delim, StringComparator comparator) { output.printLine("Pushing " + path + " menu in \n " + toStringSource()); output.printGolden("Pushing " + path + " menu in \n " + toStringSource()); return(pushMenu(parseString(path, delim), comparator)); } /** * Pushes menu. Uses PathParser assigned to this operator. * @param path a menu path. * @param comparator a string comparision algorithm * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String path, StringComparator comparator) { output.printLine("Pushing " + path + " menu in \n " + toStringSource()); output.printGolden("Pushing " + path + " menu in \n " + toStringSource()); return(pushMenu(parseString(path), comparator)); } /** * Pushes menu. * @param path String menupath representation ("File/New", for example). * @param delim String menupath divider ("/"). * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @return Last pushed JMenuItem. * @throws TimeoutExpiredException * @deprecated Use pushMenuNoBlock(String) or pushMenuNoBlock(String, StringComparator) */ public JMenuItem pushMenu(String path, String delim, boolean ce, boolean ccs) { return(pushMenu(path, delim, new DefaultStringComparator(ce, ccs))); } /** * Executes pushMenu(names, delim, comparator) in a separate thread. * @param path a menu path. * @param delim a path delimiter. * @param comparator a string comparision algorithm */ public void pushMenuNoBlock(String path, String delim, StringComparator comparator) { output.printLine("Pushing " + path + " menu in \n " + toStringSource()); output.printGolden("Pushing " + path + " menu in \n " + toStringSource()); pushMenuNoBlock(parseString(path, delim), comparator); } /** * Executes pushMenu(names, comparator) in a separate thread. * Uses PathParser assigned to this operator. * @param path a menu path. * @param comparator a string comparision algorithm */ public void pushMenuNoBlock(String path, StringComparator comparator) { output.printLine("Pushing " + path + " menu in \n " + toStringSource()); output.printGolden("Pushing " + path + " menu in \n " + toStringSource()); pushMenuNoBlock(parseString(path), comparator); } /** * Executes pushMenu(path, delim, ce, ccs) in a separate thread. * @param path String menupath representation ("File/New", for example). * @param delim String menupath divider ("/"). * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @see #pushMenu * @deprecated Use pushMenuNoBlock(String, String) or pushMenuNoBlock(String, String, StringComparator) */ public void pushMenuNoBlock(String path, String delim, boolean ce, boolean ccs) { pushMenuNoBlock(parseString(path, delim), new DefaultStringComparator(ce, ccs)); } /** * Pushes menu. * Uses StringComparator assigned to this object, * @param path String menupath representation ("File/New", for example). * @param delim String menupath divider ("/"). * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String path, String delim) { output.printLine("Pushing " + path + " menu in \n " + toStringSource()); output.printGolden("Pushing " + path + " menu in \n " + toStringSource()); return(pushMenu(parseString(path, delim))); } /** * Pushes menu. Uses PathParser assigned to this operator. * @param path String menupath representation ("File/New", for example). * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String path) { output.printLine("Pushing " + path + " menu in \n " + toStringSource()); output.printGolden("Pushing " + path + " menu in \n " + toStringSource()); return(pushMenu(parseString(path))); } /** * Executes pushMenu(path, delim) in a separate thread. * @param path String menupath representation ("File/New", for example). * @param delim String menupath divider ("/"). */ public void pushMenuNoBlock(String path, String delim) { output.printLine("Pushing " + path + " menu in \n " + toStringSource()); output.printGolden("Pushing " + path + " menu in \n " + toStringSource()); pushMenuNoBlock(parseString(path, delim)); } /** * Executes pushMenu(path) in a separate thread. * @param path String menupath representation ("File/New", for example). */ public void pushMenuNoBlock(String path) { output.printLine("Pushing " + path + " menu in \n " + toStringSource()); output.printGolden("Pushing " + path + " menu in \n " + toStringSource()); pushMenuNoBlock(parseString(path)); } public JMenuItemOperator[] showMenuItems(ComponentChooser[] choosers) { return(JMenuItemOperator.getMenuItems((JMenu)pushMenu(choosers), this)); } /** * Shows submenu of menu specified by a path parameter. * @param path an array of menu texts. * @param comparator a string comparision algorithm * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String[] path, StringComparator comparator) { return(showMenuItems(JMenuItemOperator.createChoosers(path, comparator))); } /** * Shows submenu of menu specified by a path parameter. * Uses StringComparator assigned to the operator. * @param path an array of menu texts. * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String[] path) { return(showMenuItems(path, getComparator())); } /** * Shows submenu of menu specified by a path parameter. * @param path a string identifying the menu path. * @param delim a path delimiter. * @param comparator a string comparision algorithm * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String path, String delim, StringComparator comparator ) { return(showMenuItems(parseString(path, delim), comparator)); } /** * Shows submenu of menu specified by a path parameter. * Uses StringComparator assigned to the operator. * @param path a string identifying the menu path. * @param delim a path delimiter. * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String path, String delim) { return(showMenuItems(path, delim, getComparator())); } /** * Shows submenu of menu specified by a path parameter. * Uses PathParser assigned to this operator. * @param path a string identifying the menu path. * @param comparator a string comparision algorithm * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String path, StringComparator comparator ) { return(showMenuItems(parseString(path), comparator)); } /** * Shows submenu of menu specified by a path parameter. * Uses PathParser assigned to this operator. * Uses StringComparator assigned to the operator. * @param path a string identifying the menu path. * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String path) { return(showMenuItems(path, getComparator())); } public JMenuItemOperator showMenuItem(ComponentChooser[] choosers) { ComponentChooser[] parentPath = getParentPath(choosers); JMenu menu; if(parentPath.length > 0) { menu = (JMenu)pushMenu(parentPath); } else { push(); menu = (JMenu)getSource(); } JPopupMenuOperator popup = new JPopupMenuOperator(menu.getPopupMenu()); popup.copyEnvironment(this); JMenuItemOperator result = new JMenuItemOperator(popup, choosers[choosers.length - 1]); result.copyEnvironment(this); return(result); } /** * Expends all menus to show menu item specified by a path parameter. * @param path an array of menu texts. * @param comparator a string comparision algorithm * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String[] path, StringComparator comparator) { String[] parentPath = getParentPath(path); JMenu menu; if(parentPath.length > 0) { menu = (JMenu)pushMenu(parentPath, comparator); } else { push(); menu = (JMenu)getSource(); } JPopupMenuOperator popup = new JPopupMenuOperator(menu.getPopupMenu()); popup.copyEnvironment(this); JMenuItemOperator result = new JMenuItemOperator(popup, path[path.length - 1]); result.copyEnvironment(this); return(result); } /** * Expands all menus to show menu item specified by a path parameter. * @param path an array of menu texts. * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String[] path) { return(showMenuItem(path, getComparator())); } /** * Expands all menus to show menu item specified by a path parameter. * @param path a string identifying the menu path. * @param delim a path delimiter. * @param comparator a string comparision algorithm * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String path, String delim, StringComparator comparator ) { return(showMenuItem(parseString(path, delim), comparator)); } /** * Expands all menus to show menu item specified by a path parameter. * Uses StringComparator assigned to the operator. * @param path a string identifying the menu path. * @param delim a path delimiter. * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String path, String delim) { return(showMenuItem(path, delim, getComparator())); } /** * Expands all menus to show menu item specified by a path parameter. * Uses PathParser assigned to this operator. * @param path a string identifying the menu path. * @param comparator a string comparision algorithm * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String path, StringComparator comparator ) { return(showMenuItem(parseString(path), comparator)); } /** * Expands all menus to show menu item specified by a path parameter. * Uses PathParser assigned to this operator. * Uses StringComparator assigned to the operator. * @param path a string identifying the menu path. * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String path) { return(showMenuItem(path, getComparator())); } public Hashtable getDump() { Hashtable result = super.getDump(); String[] items = new String[((JMenu)getSource()).getItemCount()]; for(int i = 0; i < ((JMenu)getSource()).getItemCount(); i++) { if(((JMenu)getSource()).getItem(i) != null && ((JMenu)getSource()).getItem(i).getText() != null) { items[i] = ((JMenu)getSource()).getItem(i).getText(); } else { items[i] = "null"; } } addToDump(result, SUBMENU_PREFIX_DPROP, items); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JMenu.add(String) through queue*/ public JMenuItem add(final String string) { return((JMenuItem)runMapping(new MapAction("add") { public Object map() { return(((JMenu)getSource()).add(string)); }}));} /**Maps JMenu.add(Action) through queue*/ public JMenuItem add(final javax.swing.Action action) { return((JMenuItem)runMapping(new MapAction("add") { public Object map() { return(((JMenu)getSource()).add(action)); }}));} /**Maps JMenu.add(JMenuItem) through queue*/ public JMenuItem add(final JMenuItem jMenuItem) { return((JMenuItem)runMapping(new MapAction("add") { public Object map() { return(((JMenu)getSource()).add(jMenuItem)); }}));} /**Maps JMenu.addMenuListener(MenuListener) through queue*/ public void addMenuListener(final MenuListener menuListener) { runMapping(new MapVoidAction("addMenuListener") { public void map() { ((JMenu)getSource()).addMenuListener(menuListener); }});} /**Maps JMenu.addSeparator() through queue*/ public void addSeparator() { runMapping(new MapVoidAction("addSeparator") { public void map() { ((JMenu)getSource()).addSeparator(); }});} /**Maps JMenu.getDelay() through queue*/ public int getDelay() { return(runMapping(new MapIntegerAction("getDelay") { public int map() { return(((JMenu)getSource()).getDelay()); }}));} /**Maps JMenu.getItem(int) through queue*/ public JMenuItem getItem(final int i) { return((JMenuItem)runMapping(new MapAction("getItem") { public Object map() { return(((JMenu)getSource()).getItem(i)); }}));} /**Maps JMenu.getItemCount() through queue*/ public int getItemCount() { return(runMapping(new MapIntegerAction("getItemCount") { public int map() { return(((JMenu)getSource()).getItemCount()); }}));} /**Maps JMenu.getMenuComponent(int) through queue*/ public Component getMenuComponent(final int i) { return((Component)runMapping(new MapAction("getMenuComponent") { public Object map() { return(((JMenu)getSource()).getMenuComponent(i)); }}));} /**Maps JMenu.getMenuComponentCount() through queue*/ public int getMenuComponentCount() { return(runMapping(new MapIntegerAction("getMenuComponentCount") { public int map() { return(((JMenu)getSource()).getMenuComponentCount()); }}));} /**Maps JMenu.getMenuComponents() through queue*/ public Component[] getMenuComponents() { return((Component[])runMapping(new MapAction("getMenuComponents") { public Object map() { return(((JMenu)getSource()).getMenuComponents()); }}));} /**Maps JMenu.getPopupMenu() through queue*/ public JPopupMenu getPopupMenu() { return((JPopupMenu)runMapping(new MapAction("getPopupMenu") { public Object map() { return(((JMenu)getSource()).getPopupMenu()); }}));} /**Maps JMenu.insert(String, int) through queue*/ public void insert(final String string, final int i) { runMapping(new MapVoidAction("insert") { public void map() { ((JMenu)getSource()).insert(string, i); }});} /**Maps JMenu.insert(Action, int) through queue*/ public JMenuItem insert(final javax.swing.Action action, final int i) { return((JMenuItem)runMapping(new MapAction("insert") { public Object map() { return(((JMenu)getSource()).insert(action, i)); }}));} /**Maps JMenu.insert(JMenuItem, int) through queue*/ public JMenuItem insert(final JMenuItem jMenuItem, final int i) { return((JMenuItem)runMapping(new MapAction("insert") { public Object map() { return(((JMenu)getSource()).insert(jMenuItem, i)); }}));} /**Maps JMenu.insertSeparator(int) through queue*/ public void insertSeparator(final int i) { runMapping(new MapVoidAction("insertSeparator") { public void map() { ((JMenu)getSource()).insertSeparator(i); }});} /**Maps JMenu.isMenuComponent(Component) through queue*/ public boolean isMenuComponent(final Component component) { return(runMapping(new MapBooleanAction("isMenuComponent") { public boolean map() { return(((JMenu)getSource()).isMenuComponent(component)); }}));} /**Maps JMenu.isPopupMenuVisible() through queue*/ public boolean isPopupMenuVisible() { return(runMapping(new MapBooleanAction("isPopupMenuVisible") { public boolean map() { return(((JMenu)getSource()).isPopupMenuVisible()); }}));} /**Maps JMenu.isTearOff() through queue*/ public boolean isTearOff() { return(runMapping(new MapBooleanAction("isTearOff") { public boolean map() { return(((JMenu)getSource()).isTearOff()); }}));} /**Maps JMenu.isTopLevelMenu() through queue*/ public boolean isTopLevelMenu() { return(runMapping(new MapBooleanAction("isTopLevelMenu") { public boolean map() { return(((JMenu)getSource()).isTopLevelMenu()); }}));} /**Maps JMenu.remove(JMenuItem) through queue*/ public void remove(final JMenuItem jMenuItem) { runMapping(new MapVoidAction("remove") { public void map() { ((JMenu)getSource()).remove(jMenuItem); }});} /**Maps JMenu.removeMenuListener(MenuListener) through queue*/ public void removeMenuListener(final MenuListener menuListener) { runMapping(new MapVoidAction("removeMenuListener") { public void map() { ((JMenu)getSource()).removeMenuListener(menuListener); }});} /**Maps JMenu.setDelay(int) through queue*/ public void setDelay(final int i) { runMapping(new MapVoidAction("setDelay") { public void map() { ((JMenu)getSource()).setDelay(i); }});} /**Maps JMenu.setMenuLocation(int, int) through queue*/ public void setMenuLocation(final int i, final int i1) { runMapping(new MapVoidAction("setMenuLocation") { public void map() { ((JMenu)getSource()).setMenuLocation(i, i1); }});} /**Maps JMenu.setPopupMenuVisible(boolean) through queue*/ public void setPopupMenuVisible(final boolean b) { runMapping(new MapVoidAction("setPopupMenuVisible") { public void map() { ((JMenu)getSource()).setPopupMenuVisible(b); }});} //End of mapping // //////////////////////////////////////////////////////// static String createDescription(ComponentChooser[] choosers) { String description="("; for(int i = 0; i < choosers.length; i++) { if(i > 0) description = description + ", "; description = description + choosers[i].getDescription(); } description = description + ")"; return("Menu pushing: " + description); } static DescriptablePathChooser converChoosers(final ComponentChooser[] choosers) { return(new DescriptablePathChooser() { public boolean checkPathComponent(int depth, Object component) { return(choosers[depth].checkComponent((Component)component)); } public int getDepth() { return(choosers.length); } public String getDescription() { return(createDescription(choosers)); } }); } /** * Allows to find component by text. */ public static class JMenuByLabelFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs JMenuByLabelFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public JMenuByLabelFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs JMenuByLabelFinder. * @param lb a text pattern */ public JMenuByLabelFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JMenu) { if(((JMenu)comp).getText() != null) { return(comparator.equals(((JMenu)comp).getText(), label)); } } return(false); } public String getDescription() { return("JMenu with text \"" + label + "\""); } } /** * Checks component type. */ public static class JMenuFinder extends Finder { /** * Constructs JMenuFinder. * @param sf other searching criteria. */ public JMenuFinder(ComponentChooser sf) { super(JMenu.class, sf); } /** * Constructs JMenuFinder. */ public JMenuFinder() { super(JMenu.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JFileChooserOperator.java0000644000175000017500000013335711245712447024217 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Window; import java.awt.event.ActionListener; import java.io.File; import javax.swing.ComboBoxModel; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JList; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.ListModel; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileSystemView; import javax.swing.filechooser.FileView; import javax.swing.plaf.FileChooserUI; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.Waitable; import org.netbeans.jemmy.Waiter; /** * * Class provides methods to cover main JFileChooser component functionality. * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JFileChooserOperator extends JComponentOperator implements Timeoutable, Outputable { private final static long WAIT_LIST_PAINTED_TIMEOUT = 60000; private Timeouts timeouts; private TestOut output; private ComponentSearcher innerSearcher; /** * Constructor. * @param comp a component */ public JFileChooserOperator(JFileChooser comp) { super(comp); innerSearcher = new ComponentSearcher(comp); setTimeouts(JemmyProperties.getProperties().getTimeouts()); setOutput(JemmyProperties.getProperties().getOutput()); } /** * Constructor. * Waits component first. * Constructor can be used in complicated cases when * output or timeouts should differ from default. * @param env an operator to get environment from. */ public JFileChooserOperator(Operator env) { this((JFileChooser) waitComponent(JDialogOperator. waitJDialog(new JFileChooserJDialogFinder(env.getOutput()), 0, env.getTimeouts(), env.getOutput()), new JFileChooserFinder(), 0, env.getTimeouts(), env.getOutput())); copyEnvironment(env); } /** * Constructor. * Waits component first. */ public JFileChooserOperator() { this(getEnvironmentOperator()); } /** * Searches currently opened JDilog with JFileChooser inside. * @return a component instance */ public static JDialog findJFileChooserDialog() { return(JDialogOperator. findJDialog(new JFileChooserJDialogFinder(JemmyProperties. getCurrentOutput()))); } /** * Waits currently opened JDilog with JFileChooser inside. * @return a component instance */ public static JDialog waitJFileChooserDialog() { return(JDialogOperator. waitJDialog(new JFileChooserJDialogFinder(JemmyProperties. getCurrentOutput()))); } /** * Searches JFileChooser in container. * @param cont a container * @return a component instance */ public static JFileChooser findJFileChooser(Container cont) { return((JFileChooser)findComponent(cont, new JFileChooserFinder())); } /** * Searches JFileChooser in container. * @param cont a container * @return a component instance */ public static JFileChooser waitJFileChooser(Container cont) { return((JFileChooser)waitComponent(cont, new JFileChooserFinder())); } /** * Searches currently opened JFileChooser. * @return a component instance */ public static JFileChooser findJFileChooser() { return(findJFileChooser(findJFileChooserDialog())); } /** * Waits currently opened JFileChooser. * @return a component instance */ public static JFileChooser waitJFileChooser() { return(waitJFileChooser(waitJFileChooserDialog())); } static { Timeouts.initDefault("JFileChooserOperator.WaitListPaintedTimeout", WAIT_LIST_PAINTED_TIMEOUT); } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); if(innerSearcher != null) { innerSearcher.setOutput(output.createErrorOutput()); } } public TestOut getOutput() { return(output); } /** * Returns combo box containing path (upper). * @return JComboBox being used to show directories. */ public JComboBox getPathCombo() { return(getCombo(0)); } /** * Returns combo box containing file types (lower). * @return JComboBox being used to show file types. */ public JComboBox getFileTypesCombo() { return(getCombo(1)); } /** * Returns approve button. * @return an approve button. */ public JButton getApproveButton() { String aText = getApproveButtonText(); if(aText == null) aText = getUI().getApproveButtonText((JFileChooser)getSource()); if(aText != null) { return((JButton)innerSearcher. findComponent(new ButtonFinder(aText))); } else { throw(new JemmyException("JFileChooser.getApproveButtonText() " + "and getUI().getApproveButtonText " + "return null")); } } /** * Returns cancel button. * @return a cancel button. */ public JButton getCancelButton() { return((JButton)innerSearcher. findComponent(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp != null && comp instanceof JButton && comp.getParent() != null && !(comp.getParent() instanceof JComboBox) && ((JButton)comp).getText() != null && ((JButton)comp).getText().length() != 0); } public String getDescription() { return("JButton"); } }, 1)); } /** * Returns "Home" button. * @return a "home" button. */ public JButton getHomeButton() { return(getNoTextButton(1)); } /** * Returns "Up One Level" button. * @return a "Up One Level" button. */ public JButton getUpLevelButton() { return(getNoTextButton(0)); } /** * Returns a toggle button being used to switch to list view. * @return a "list mode" button. */ public JToggleButton getListToggleButton() { return(getToggleButton(0)); } /** * Returns a toggle button being used to switch to detals view. * @return a "list mode" button. */ public JToggleButton getDetailsToggleButton() { return(getToggleButton(1)); } /** * Returns field which can be used to type path. * @return a text field being used for path typing. */ public JTextField getPathField() { return((JTextField)innerSearcher. findComponent(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp != null && comp instanceof JTextField); } public String getDescription() { return("JTextField"); } })); } /** * Returns file list. * @return a list being used to display directory content. */ public JList getFileList() { return((JList)innerSearcher. findComponent(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp != null && comp instanceof JList); } public String getDescription() { return("JList"); } })); } /** * Pushes approve button. */ public void approve() { getQueueTool().waitEmpty(); output.printTrace("Push approve button in JFileChooser\n : " + toStringSource()); JButtonOperator approveOper = new JButtonOperator(getApproveButton()); approveOper.copyEnvironment(this); approveOper.setOutput(output.createErrorOutput()); approveOper.push(); } /** * Pushes cancel button. */ public void cancel() { output.printTrace("Push cancel button in JFileChooser\n : " + toStringSource()); JButtonOperator cancelOper = new JButtonOperator(getCancelButton()); cancelOper.copyEnvironment(this); cancelOper.setOutput(output.createErrorOutput()); cancelOper.push(); } /** * Types file name into text field and pushes approve button. * @param fileName a file to choose. */ public void chooseFile(String fileName) { getQueueTool().waitEmpty(); output.printTrace("Choose file by JFileChooser\n : " + fileName + "\n : " + toStringSource()); JTextFieldOperator fieldOper = new JTextFieldOperator(getPathField()); fieldOper.copyEnvironment(this); fieldOper.setOutput(output.createErrorOutput()); //workaround fieldOper.setText(fileName); //fieldOper.clearText(); //fieldOper.typeText(fileName); //approveSelection(); approve(); } /** * Pushes "Up One Level" button. * @return new current directory */ public File goUpLevel() { getQueueTool().waitEmpty(); output.printTrace("Go up level in JFileChooser\n : " + toStringSource()); //workaround setCurrentDirectory(getCurrentDirectory().getParentFile()); //JButtonOperator upOper = new JButtonOperator(getUpLevelButton()); //upOper.copyEnvironment(this); //upOper.setOutput(output.createErrorOutput()); //upOper.push(); waitPainted(-1); return(getCurrentDirectory()); } /** * Pushes "Home" button. * @return new current directory */ public File goHome() { getQueueTool().waitEmpty(); output.printTrace("Go home in JFileChooser\n : " + toStringSource()); JButtonOperator homeOper = new JButtonOperator(getHomeButton()); homeOper.copyEnvironment(this); homeOper.setOutput(output.createErrorOutput()); homeOper.push(); waitPainted(-1); return(getCurrentDirectory()); } /** * Clicks on file in the list. * @param index Ordinal file index. * @param clickCount click count */ public void clickOnFile(int index, int clickCount) { getQueueTool().waitEmpty(); output.printTrace("Click " + Integer.toString(clickCount) + "times on " + Integer.toString(index) + "`th file in JFileChooser\n : " + toStringSource()); JListOperator listOper = new JListOperator(getFileList()); waitPainted(index); listOper.copyEnvironment(this); listOper.setOutput(output.createErrorOutput()); listOper.clickOnItem(index, clickCount); } /** * Clicks on file in the list. * @param file File name (foo.c). Do not use full path (/tmp/foo.c) here. * @param comparator a comparator defining string comparision criteria * @param clickCount click count */ public void clickOnFile(String file, StringComparator comparator, int clickCount) { output.printTrace("Click " + Integer.toString(clickCount) + "times on \"" + file + "\" file in JFileChooser\n : " + toStringSource()); clickOnFile(findFileIndex(file, comparator), clickCount); } /** * Clicks on file in the list. * @param file File name (foo.c). Do not use full path (/tmp/foo.c) here. * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @param clickCount click count * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @deprecated Use clickOnFile(String, int) or clickOnFile(String, StringComparator, int) */ public void clickOnFile(String file, boolean ce, boolean cc, int clickCount) { clickOnFile(file, new DefaultStringComparator(ce, cc), clickCount); } /** * Clicks on file in the list. * @param file File name (foo.c). Do not use full path (/tmp/foo.c) here. * @param clickCount click count * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public void clickOnFile(String file, int clickCount) { clickOnFile(file, getComparator(), clickCount); } /** * Clicks on file in the list. * @param file File name (foo.c). Do not use full path (/tmp/foo.c) here. * @param comparator a comparator defining string comparision criteria * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public void clickOnFile(String file, StringComparator comparator) { clickOnFile(file, comparator, 1); } /** * Clicks 1 time on file in the list. * @param file File name (foo.c). Do not use full path (/tmp/foo.c) here. * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @see #clickOnFile * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @deprecated Use clickOnFile(String) or clickOnFile(String, StringComparator) */ public void clickOnFile(String file, boolean ce, boolean cc) { clickOnFile(file, ce, cc, 1); } /** * Clicks 1 time on file in the list. * @param file File name (foo.c). Do not use full path (/tmp/foo.c) here. * @see #clickOnFile * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public void clickOnFile(String file) { clickOnFile(file, 1); } /** * Enters into subdirectory. * @param dir A directory to enter into. * @param comparator a comparator defining string comparision criteria * @return new current directory */ public File enterSubDir(String dir, StringComparator comparator) { getQueueTool().waitEmpty(); selectFile(dir, comparator); int index = findFileIndex(dir, comparator); waitPainted(index); setCurrentDirectory(getSelectedFile()); return(getCurrentDirectory()); } /** * Enters into subdir curently displayed in the list. * @param dir Directory name (tmp1). Do not use full path (/tmp/tmp1) here. * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @return new current directory * @see #clickOnFile * @deprecated Use enterSubDir(String) or enterSubDir(String, StringComparator) */ public File enterSubDir(String dir, boolean ce, boolean cc) { return(enterSubDir(dir, new DefaultStringComparator(ce, cc))); } /** * Enters into subdir curently displayed in the list. * @param dir Directory name (tmp1). Do not use full path (/tmp/tmp1) here. * @return new current directory * @see #clickOnFile */ public File enterSubDir(String dir) { return(enterSubDir(dir, getComparator())); } /** * Selects a file curently in the list. * @param file File name (foo.c). Do not use full path (/tmp/foo.c) here. * @param comparator a comparator defining string comparision criteria * @see #clickOnFile */ public void selectFile(String file, StringComparator comparator) { getQueueTool().waitEmpty(); int index = findFileIndex(file, comparator); JListOperator listOper = new JListOperator(getFileList()); waitPainted(index); listOper.copyEnvironment(this); listOper.setOutput(output.createErrorOutput()); listOper.setSelectedIndex(index); } /** * Selects a file curently in the list. * @param file File name (foo.c). Do not use full path (/tmp/foo.c) here. * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @see #clickOnFile * @deprecated Use selectFile(String) or selectFile(String, StringComparator) */ public void selectFile(String file, boolean ce, boolean cc) { clickOnFile(file, ce, cc); } /** * Selects a file curently in the list. * @param file File name (foo.c). Do not use full path (/tmp/foo.c) here. * @see #clickOnFile */ public void selectFile(String file) { clickOnFile(file); } /** * Selects directory from the combo box above. * @param dir Directory name (tmp1). Do not use full path (/tmp/tmp1) here. * @param comparator a comparator defining string comparision criteria */ public void selectPathDirectory(String dir, StringComparator comparator) { getQueueTool().waitEmpty(); output.printTrace("Select \"" + dir + "\" directory in JFileChooser\n : " + toStringSource()); JComboBoxOperator comboOper = new JComboBoxOperator(getPathCombo()); comboOper.copyEnvironment(this); comboOper.setOutput(output.createErrorOutput()); //workaround comboOper.setSelectedIndex(findDirIndex(dir, comparator)); //comboOper.selectItem(findDirIndex(dir, comparator)); waitPainted(-1); } /** * Selects directory from the combo box above. * @param dir Directory name (tmp1). Do not use full path (/tmp/tmp1) here. * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @deprecated Use selectPathDirectory(String) or selectPathDirectory(String, StringComparator) */ public void selectPathDirectory(String dir, boolean ce, boolean cc) { selectPathDirectory(dir, new DefaultStringComparator(ce, cc)); } /** * Selects directory from the combo box above. * @param dir Directory name (tmp1). Do not use full path (/tmp/tmp1) here. */ public void selectPathDirectory(String dir) { selectPathDirectory(dir, getComparator()); } /** * Selects file type from the combo box below. * @param filter a pattern for choosing a file type. * @param comparator a comparator defining string comparision criteria */ public void selectFileType(String filter, StringComparator comparator) { getQueueTool().waitEmpty(); output.printTrace("Select \"" + filter + "\" file type in JFileChooser\n : " + toStringSource()); JComboBoxOperator comboOper = new JComboBoxOperator(getFileTypesCombo()); comboOper.copyEnvironment(this); comboOper.setOutput(output.createErrorOutput()); //workaround comboOper.setSelectedIndex(findFileTypeIndex(filter, comparator)); // comboOper.selectItem(findFileTypeIndex(filter, comparator)); waitPainted(-1); } /** * Selects file type from the combo box below. * @param filter a pattern for choosing a file type. * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @deprecated Use selectFileType(String) or selectFileType(String, StringComparator) */ public void selectFileType(String filter, boolean ce, boolean cc) { selectFileType(filter, new DefaultStringComparator(ce, cc)); } /** * Selects file type from the combo box below. * @param filter a pattern for choosing a file type. */ public void selectFileType(String filter) { selectFileType(filter, getComparator()); } /** * Checks if file is currently displayed in the list. * @param file File name (foo.c). Do not use full path (/tmp/foo.c) here. * @param comparator a comparator defining string comparision criteria * @return true if file is displayed. */ public boolean checkFileDisplayed(String file, StringComparator comparator) { waitPainted(-1); return(findFileIndex(file, comparator) != -1); } /** * Checks if file is currently displayed in the list. * @param file File name (foo.c). Do not use full path (/tmp/foo.c) here. * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @return true if file is displayed. * @deprecated Use checkFileDisplayed(String) or checkFileDisplayed(String, StringComparator) */ public boolean checkFileDisplayed(String file, boolean ce, boolean cc) { return(checkFileDisplayed(file, new DefaultStringComparator(ce, cc))); } /** * Checks if file is currently displayed in the list. * @param file File name (foo.c). Do not use full path (/tmp/foo.c) here. * @return true if file is displayed. */ public boolean checkFileDisplayed(String file) { return(checkFileDisplayed(file, getComparator())); } /** * Return count of files currently displayed. * @return a number of items in the file list. */ public int getFileCount() { waitPainted(-1); return(getFileList().getModel().getSize()); } /** * Return files currently displayed. * @return an array of items from the file list. */ public File[] getFiles() { waitPainted(-1); ListModel listModel = getFileList().getModel(); File[] result = new File[listModel.getSize()]; for(int i = 0; i < listModel.getSize(); i++) { result[i] = (File)listModel.getElementAt(i); } return(result); } /** * Waits for the file list to have required number of items. * @param count Number of files to wait. */ public void waitFileCount(final int count) { waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(getFileCount() == count); } public String getDescription() { return("Count of files to be equal " + Integer.toString(count)); } }); } /** * Waits for a file to be displayed in the file list. * @param fileName a file to wait. */ public void waitFileDisplayed(final String fileName) { waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(checkFileDisplayed(fileName)); } public String getDescription() { return("\"" + fileName + "\"file to be displayed"); } }); } //////////////////////////////////////////////////////// //Mapping // /**Maps JFileChooser.accept(File) through queue*/ public boolean accept(final File file) { return(runMapping(new MapBooleanAction("accept") { public boolean map() { return(((JFileChooser)getSource()).accept(file)); }}));} /**Maps JFileChooser.addActionListener(ActionListener) through queue*/ public void addActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("addActionListener") { public void map() { ((JFileChooser)getSource()).addActionListener(actionListener); }});} /**Maps JFileChooser.addChoosableFileFilter(FileFilter) through queue*/ public void addChoosableFileFilter(final FileFilter fileFilter) { runMapping(new MapVoidAction("addChoosableFileFilter") { public void map() { ((JFileChooser)getSource()).addChoosableFileFilter(fileFilter); }});} /**Maps JFileChooser.approveSelection() through queue*/ public void approveSelection() { runMapping(new MapVoidAction("approveSelection") { public void map() { ((JFileChooser)getSource()).approveSelection(); }});} /**Maps JFileChooser.cancelSelection() through queue*/ public void cancelSelection() { runMapping(new MapVoidAction("cancelSelection") { public void map() { ((JFileChooser)getSource()).cancelSelection(); }});} /**Maps JFileChooser.changeToParentDirectory() through queue*/ public void changeToParentDirectory() { runMapping(new MapVoidAction("changeToParentDirectory") { public void map() { ((JFileChooser)getSource()).changeToParentDirectory(); }});} /**Maps JFileChooser.ensureFileIsVisible(File) through queue*/ public void ensureFileIsVisible(final File file) { runMapping(new MapVoidAction("ensureFileIsVisible") { public void map() { ((JFileChooser)getSource()).ensureFileIsVisible(file); }});} /**Maps JFileChooser.getAcceptAllFileFilter() through queue*/ public FileFilter getAcceptAllFileFilter() { return((FileFilter)runMapping(new MapAction("getAcceptAllFileFilter") { public Object map() { return(((JFileChooser)getSource()).getAcceptAllFileFilter()); }}));} /**Maps JFileChooser.getAccessory() through queue*/ public JComponent getAccessory() { return((JComponent)runMapping(new MapAction("getAccessory") { public Object map() { return(((JFileChooser)getSource()).getAccessory()); }}));} /**Maps JFileChooser.getApproveButtonMnemonic() through queue*/ public int getApproveButtonMnemonic() { return(runMapping(new MapIntegerAction("getApproveButtonMnemonic") { public int map() { return(((JFileChooser)getSource()).getApproveButtonMnemonic()); }}));} /**Maps JFileChooser.getApproveButtonText() through queue*/ public String getApproveButtonText() { return((String)runMapping(new MapAction("getApproveButtonText") { public Object map() { return(((JFileChooser)getSource()).getApproveButtonText()); }}));} /**Maps JFileChooser.getApproveButtonToolTipText() through queue*/ public String getApproveButtonToolTipText() { return((String)runMapping(new MapAction("getApproveButtonToolTipText") { public Object map() { return(((JFileChooser)getSource()).getApproveButtonToolTipText()); }}));} /**Maps JFileChooser.getChoosableFileFilters() through queue*/ public FileFilter[] getChoosableFileFilters() { return((FileFilter[])runMapping(new MapAction("getChoosableFileFilters") { public Object map() { return(((JFileChooser)getSource()).getChoosableFileFilters()); }}));} /**Maps JFileChooser.getCurrentDirectory() through queue*/ public File getCurrentDirectory() { return((File)runMapping(new MapAction("getCurrentDirectory") { public Object map() { return(((JFileChooser)getSource()).getCurrentDirectory()); }}));} /**Maps JFileChooser.getDescription(File) through queue*/ public String getDescription(final File file) { return((String)runMapping(new MapAction("getDescription") { public Object map() { return(((JFileChooser)getSource()).getDescription(file)); }}));} /**Maps JFileChooser.getDialogTitle() through queue*/ public String getDialogTitle() { return((String)runMapping(new MapAction("getDialogTitle") { public Object map() { return(((JFileChooser)getSource()).getDialogTitle()); }}));} /**Maps JFileChooser.getDialogType() through queue*/ public int getDialogType() { return(runMapping(new MapIntegerAction("getDialogType") { public int map() { return(((JFileChooser)getSource()).getDialogType()); }}));} /**Maps JFileChooser.getFileFilter() through queue*/ public FileFilter getFileFilter() { return((FileFilter)runMapping(new MapAction("getFileFilter") { public Object map() { return(((JFileChooser)getSource()).getFileFilter()); }}));} /**Maps JFileChooser.getFileSelectionMode() through queue*/ public int getFileSelectionMode() { return(runMapping(new MapIntegerAction("getFileSelectionMode") { public int map() { return(((JFileChooser)getSource()).getFileSelectionMode()); }}));} /**Maps JFileChooser.getFileSystemView() through queue*/ public FileSystemView getFileSystemView() { return((FileSystemView)runMapping(new MapAction("getFileSystemView") { public Object map() { return(((JFileChooser)getSource()).getFileSystemView()); }}));} /**Maps JFileChooser.getFileView() through queue*/ public FileView getFileView() { return((FileView)runMapping(new MapAction("getFileView") { public Object map() { return(((JFileChooser)getSource()).getFileView()); }}));} /**Maps JFileChooser.getIcon(File) through queue*/ public Icon getIcon(final File file) { return((Icon)runMapping(new MapAction("getIcon") { public Object map() { return(((JFileChooser)getSource()).getIcon(file)); }}));} /**Maps JFileChooser.getName(File) through queue*/ public String getName(final File file) { return((String)runMapping(new MapAction("getName") { public Object map() { return(((JFileChooser)getSource()).getName(file)); }}));} /**Maps JFileChooser.getSelectedFile() through queue*/ public File getSelectedFile() { return((File)runMapping(new MapAction("getSelectedFile") { public Object map() { return(((JFileChooser)getSource()).getSelectedFile()); }}));} /**Maps JFileChooser.getSelectedFiles() through queue*/ public File[] getSelectedFiles() { return((File[])runMapping(new MapAction("getSelectedFiles") { public Object map() { return(((JFileChooser)getSource()).getSelectedFiles()); }}));} /**Maps JFileChooser.getTypeDescription(File) through queue*/ public String getTypeDescription(final File file) { return((String)runMapping(new MapAction("getTypeDescription") { public Object map() { return(((JFileChooser)getSource()).getTypeDescription(file)); }}));} /**Maps JFileChooser.getUI() through queue*/ public FileChooserUI getUI() { return((FileChooserUI)runMapping(new MapAction("getUI") { public Object map() { return(((JFileChooser)getSource()).getUI()); }}));} /**Maps JFileChooser.isDirectorySelectionEnabled() through queue*/ public boolean isDirectorySelectionEnabled() { return(runMapping(new MapBooleanAction("isDirectorySelectionEnabled") { public boolean map() { return(((JFileChooser)getSource()).isDirectorySelectionEnabled()); }}));} /**Maps JFileChooser.isFileHidingEnabled() through queue*/ public boolean isFileHidingEnabled() { return(runMapping(new MapBooleanAction("isFileHidingEnabled") { public boolean map() { return(((JFileChooser)getSource()).isFileHidingEnabled()); }}));} /**Maps JFileChooser.isFileSelectionEnabled() through queue*/ public boolean isFileSelectionEnabled() { return(runMapping(new MapBooleanAction("isFileSelectionEnabled") { public boolean map() { return(((JFileChooser)getSource()).isFileSelectionEnabled()); }}));} /**Maps JFileChooser.isMultiSelectionEnabled() through queue*/ public boolean isMultiSelectionEnabled() { return(runMapping(new MapBooleanAction("isMultiSelectionEnabled") { public boolean map() { return(((JFileChooser)getSource()).isMultiSelectionEnabled()); }}));} /**Maps JFileChooser.isTraversable(File) through queue*/ public boolean isTraversable(final File file) { return(runMapping(new MapBooleanAction("isTraversable") { public boolean map() { return(((JFileChooser)getSource()).isTraversable(file)); }}));} /**Maps JFileChooser.removeActionListener(ActionListener) through queue*/ public void removeActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("removeActionListener") { public void map() { ((JFileChooser)getSource()).removeActionListener(actionListener); }});} /**Maps JFileChooser.removeChoosableFileFilter(FileFilter) through queue*/ public boolean removeChoosableFileFilter(final FileFilter fileFilter) { return(runMapping(new MapBooleanAction("removeChoosableFileFilter") { public boolean map() { return(((JFileChooser)getSource()).removeChoosableFileFilter(fileFilter)); }}));} /**Maps JFileChooser.rescanCurrentDirectory() through queue*/ public void rescanCurrentDirectory() { runMapping(new MapVoidAction("rescanCurrentDirectory") { public void map() { ((JFileChooser)getSource()).rescanCurrentDirectory(); }});} /**Maps JFileChooser.resetChoosableFileFilters() through queue*/ public void resetChoosableFileFilters() { runMapping(new MapVoidAction("resetChoosableFileFilters") { public void map() { ((JFileChooser)getSource()).resetChoosableFileFilters(); }});} /**Maps JFileChooser.setAccessory(JComponent) through queue*/ public void setAccessory(final JComponent jComponent) { runMapping(new MapVoidAction("setAccessory") { public void map() { ((JFileChooser)getSource()).setAccessory(jComponent); }});} /**Maps JFileChooser.setApproveButtonMnemonic(char) through queue*/ public void setApproveButtonMnemonic(final char c) { runMapping(new MapVoidAction("setApproveButtonMnemonic") { public void map() { ((JFileChooser)getSource()).setApproveButtonMnemonic(c); }});} /**Maps JFileChooser.setApproveButtonMnemonic(int) through queue*/ public void setApproveButtonMnemonic(final int i) { runMapping(new MapVoidAction("setApproveButtonMnemonic") { public void map() { ((JFileChooser)getSource()).setApproveButtonMnemonic(i); }});} /**Maps JFileChooser.setApproveButtonText(String) through queue*/ public void setApproveButtonText(final String string) { runMapping(new MapVoidAction("setApproveButtonText") { public void map() { ((JFileChooser)getSource()).setApproveButtonText(string); }});} /**Maps JFileChooser.setApproveButtonToolTipText(String) through queue*/ public void setApproveButtonToolTipText(final String string) { runMapping(new MapVoidAction("setApproveButtonToolTipText") { public void map() { ((JFileChooser)getSource()).setApproveButtonToolTipText(string); }});} /**Maps JFileChooser.setCurrentDirectory(File) through queue*/ public void setCurrentDirectory(final File file) { runMapping(new MapVoidAction("setCurrentDirectory") { public void map() { ((JFileChooser)getSource()).setCurrentDirectory(file); }});} /**Maps JFileChooser.setDialogTitle(String) through queue*/ public void setDialogTitle(final String string) { runMapping(new MapVoidAction("setDialogTitle") { public void map() { ((JFileChooser)getSource()).setDialogTitle(string); }});} /**Maps JFileChooser.setDialogType(int) through queue*/ public void setDialogType(final int i) { runMapping(new MapVoidAction("setDialogType") { public void map() { ((JFileChooser)getSource()).setDialogType(i); }});} /**Maps JFileChooser.setFileFilter(FileFilter) through queue*/ public void setFileFilter(final FileFilter fileFilter) { runMapping(new MapVoidAction("setFileFilter") { public void map() { ((JFileChooser)getSource()).setFileFilter(fileFilter); }});} /**Maps JFileChooser.setFileHidingEnabled(boolean) through queue*/ public void setFileHidingEnabled(final boolean b) { runMapping(new MapVoidAction("setFileHidingEnabled") { public void map() { ((JFileChooser)getSource()).setFileHidingEnabled(b); }});} /**Maps JFileChooser.setFileSelectionMode(int) through queue*/ public void setFileSelectionMode(final int i) { runMapping(new MapVoidAction("setFileSelectionMode") { public void map() { ((JFileChooser)getSource()).setFileSelectionMode(i); }});} /**Maps JFileChooser.setFileSystemView(FileSystemView) through queue*/ public void setFileSystemView(final FileSystemView fileSystemView) { runMapping(new MapVoidAction("setFileSystemView") { public void map() { ((JFileChooser)getSource()).setFileSystemView(fileSystemView); }});} /**Maps JFileChooser.setFileView(FileView) through queue*/ public void setFileView(final FileView fileView) { runMapping(new MapVoidAction("setFileView") { public void map() { ((JFileChooser)getSource()).setFileView(fileView); }});} /**Maps JFileChooser.setMultiSelectionEnabled(boolean) through queue*/ public void setMultiSelectionEnabled(final boolean b) { runMapping(new MapVoidAction("setMultiSelectionEnabled") { public void map() { ((JFileChooser)getSource()).setMultiSelectionEnabled(b); }});} /**Maps JFileChooser.setSelectedFile(File) through queue*/ public void setSelectedFile(final File file) { runMapping(new MapVoidAction("setSelectedFile") { public void map() { ((JFileChooser)getSource()).setSelectedFile(file); }});} /**Maps JFileChooser.setSelectedFiles(File[]) through queue*/ public void setSelectedFiles(final File[] file) { runMapping(new MapVoidAction("setSelectedFiles") { public void map() { ((JFileChooser)getSource()).setSelectedFiles(file); }});} /**Maps JFileChooser.showDialog(Component, String) through queue*/ public int showDialog(final Component component, final String string) { return(runMapping(new MapIntegerAction("showDialog") { public int map() { return(((JFileChooser)getSource()).showDialog(component, string)); }}));} /**Maps JFileChooser.showOpenDialog(Component) through queue*/ public int showOpenDialog(final Component component) { return(runMapping(new MapIntegerAction("showOpenDialog") { public int map() { return(((JFileChooser)getSource()).showOpenDialog(component)); }}));} /**Maps JFileChooser.showSaveDialog(Component) through queue*/ public int showSaveDialog(final Component component) { return(runMapping(new MapIntegerAction("showSaveDialog") { public int map() { return(((JFileChooser)getSource()).showSaveDialog(component)); }}));} //End of mapping // //////////////////////////////////////////////////////// private void waitPainted(int index) { Waiter drawingWaiter = new Waiter(new Waitable() { public Object actionProduced(Object param) { JList list = getFileList(); int last_one = list.getModel().getSize() - 1; if(last_one == -1) { return(""); } int current = (param != null) ? ((Integer)param).intValue() : 0; try { if(list.getCellBounds(current, current) != null) { return(list.getCellBounds(last_one, last_one)); } else { return(null); } } catch(NullPointerException e) { //sometimes thrown from list.getCellBounds when item exists but not painted return(null); } } public String getDescription() { return("List drawed"); } }); drawingWaiter.setTimeoutsToCloneOf(getTimeouts(), "JFileChooserOperator.WaitListPaintedTimeout"); drawingWaiter.setOutput(getOutput().createErrorOutput()); try { drawingWaiter.waitAction((index != -1) ? new Integer(index) : null); } catch(InterruptedException e) { output.printStackTrace(e); } } private JComboBox getCombo(int index) { return((JComboBox)innerSearcher. findComponent(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp != null && comp instanceof JComboBox); } public String getDescription() { return("JComboBox"); } }, index)); } private JButton getNoTextButton(int index) { return((JButton)innerSearcher. findComponent(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp != null && comp instanceof JButton && !(comp.getParent() instanceof JComboBox) && (((JButton)comp).getText() == null || ((JButton)comp).getText().length() == 0)); } public String getDescription() { return("JButton"); } }, index)); } private JToggleButton getToggleButton(int index) { return((JToggleButton)innerSearcher. findComponent(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp != null && comp instanceof JToggleButton); } public String getDescription() { return("JToggleButton"); } }, index)); } private int findFileIndex(final String file, final StringComparator comparator) { Waiter fileWaiter = new Waiter(new Waitable() { public Object actionProduced(Object obj) { File[] files = getFiles(); for(int i = 0; i < files.length; i++) { if(comparator.equals(files[i].getName(), file)) { return(new Integer(i)); } } return(null); } public String getDescription() { return("\"" + file + "\" file to be displayed"); } }); fileWaiter.setOutput(getOutput().createErrorOutput()); fileWaiter.setTimeoutsToCloneOf(getTimeouts(), "JFileChooserOperator.WaitListPaintedTimeout"); try { return(((Integer)fileWaiter.waitAction(null)).intValue()); } catch(InterruptedException e) { throw(new JemmyException("Waiting has been interrupted!")); } } private int findDirIndex(String dir, StringComparator comparator) { ComboBoxModel cbModel = getPathCombo().getModel(); for(int i = cbModel.getSize() - 1; i >= 0; i--) { if(comparator.equals(((File)cbModel.getElementAt(i)).getName(), dir)) { return(i); } } return(-1); } private int findFileTypeIndex(String fileType, StringComparator comparator) { ComboBoxModel cbModel = getFileTypesCombo().getModel(); for(int i = 0; i < cbModel.getSize(); i++) { if(comparator.equals(((FileFilter)cbModel.getElementAt(i)).getDescription(), fileType)) { return(i); } } return(-1); } /** * Allows to find a dialog containing JFileChooser. */ public static class JFileChooserJDialogFinder implements ComponentChooser { TestOut output; ComponentChooser subChooser; /** * Constructs JFileChooserJDialogFinder. * @param output an output to put searching message into. */ public JFileChooserJDialogFinder(TestOut output) { this.output = output; subChooser = new JFileChooserFinder(); } public boolean checkComponent(Component comp) { if(comp != null && comp instanceof Window && ((Window)comp).isVisible()) { ComponentSearcher searcher = new ComponentSearcher((Container)comp); searcher.setOutput(output); return(searcher.findComponent(subChooser) != null); } else { return(false); } } public String getDescription() { return("JFileChooser's window"); } } /** * Checks component type. */ public static class JFileChooserFinder extends Finder { /** * Constructs JFileChooserFinder. * @param sf other searching criteria. */ public JFileChooserFinder(ComponentChooser sf) { super(JFileChooser.class, sf); } /** * Constructs JFileChooserFinder. */ public JFileChooserFinder() { super(JFileChooser.class); } } private class ButtonFinder implements ComponentChooser { String text; public ButtonFinder(String text) { this.text = text; } public boolean checkComponent(Component comp) { return(comp != null && comp instanceof JButton && ((JButton)comp).getText() != null && ((JButton)comp).getText().equals(text)); } public String getDescription() { return("\"" + text + "\" button"); } } } Jemmy2/src/org/netbeans/jemmy/operators/JSliderOperator.java0000644000175000017500000005743411245712347023237 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Container; import java.util.Dictionary; import java.util.Hashtable; import javax.swing.BoundedRangeModel; import javax.swing.JSlider; import javax.swing.event.ChangeListener; import javax.swing.plaf.SliderUI; import org.netbeans.jemmy.Action; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.ScrollDriver; import org.netbeans.jemmy.drivers.scrolling.ScrollAdjuster; /** * Covers javax.swing.JSlider component. * *

Timeouts used:
* JSliderOperator.WholeScrollTimeout - time for the whole scrolling.
* JSliderOperator.ScrollingDelta - time delta to verify result durong scrolling.
* * @author Alexandre Iline (alexandre.iline@sun.com) */ public class JSliderOperator extends JComponentOperator implements Timeoutable, Outputable{ private final static long ONE_SCROLL_CLICK_TIMEOUT = 0; private final static long WHOLE_SCROLL_TIMEOUT = 60000; private final static long SCROLLING_DELTA = 0; private ScrollDriver driver; /** * Identifier for a "minimum" property. * @see #getDump */ public static final String MINIMUM_DPROP = "Minimum"; /** * Identifier for a "maximum" property. * @see #getDump */ public static final String MAXIMUM_DPROP = "Maximum"; /** * Identifier for a "value" property. * @see #getDump */ public static final String VALUE_DPROP = "Value"; /** * Identifier for a "orientation" property. * @see #getDump */ public static final String ORIENTATION_DPROP = "Orientation"; /** * Identifier for a "HORIZONTAL" value of "orientation" property. * @see #getDump */ public static final String HORIZONTAL_ORIENTATION_DPROP_VALUE = "HORIZONTAL"; /** * Identifier for a "VERTICAL" value of "orientation" property. * @see #getDump */ public static final String VERTICAL_ORIENTATION_DPROP_VALUE = "VERTICAL"; /** * Identifier for a "inverted" property. */ public static final String IS_INVERTED_DPROP = "Inverted"; /** * Scrolling model. * @see #setScrollModel(int) * @deprecated All actions are prformed throw a ScrollDriver registered * for this component, So this field is useless. */ public static final int CLICK_SCROLL_MODEL = 1; /** * Push and wait scroll model. Mouse is pressed, and released after necessary position reached. * @see #setScrollModel(int) * @deprecated All actions are prformed throw a ScrollDriver registered * for this component, So this field is useless. */ public static final int PUSH_AND_WAIT_SCROLL_MODEL = 2; private Timeouts timeouts; private TestOut output; private int scrollModel = CLICK_SCROLL_MODEL; /** * Constructor. * @param b JSlider component. */ public JSliderOperator(JSlider b) { super(b); driver = DriverManager.getScrollDriver(getClass()); } /** * Constructs a JSliderOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JSliderOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JSlider)cont. waitSubComponent(new JSliderFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JSliderOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JSliderOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JSliderOperator(ContainerOperator cont, int index) { this((JSlider)waitComponent(cont, new JSliderFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @throws TimeoutExpiredException */ public JSliderOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JSlider in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JSlider instance or null if component was not found. */ public static JSlider findJSlider(Container cont, ComponentChooser chooser, int index) { return((JSlider)findComponent(cont, new JSliderFinder(chooser), index)); } /** * Searches 0'th JSlider in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JSlider instance or null if component was not found. */ public static JSlider findJSlider(Container cont, ComponentChooser chooser) { return(findJSlider(cont, chooser, 0)); } /** * Searches JSlider in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JSlider instance or null if component was not found. */ public static JSlider findJSlider(Container cont, int index) { return(findJSlider(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JSlider instance"), index)); } /** * Searches 0'th JSlider in container. * @param cont Container to search component in. * @return JSlider instance or null if component was not found. */ public static JSlider findJSlider(Container cont) { return(findJSlider(cont, 0)); } /** * Waits JSlider in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JSlider instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JSlider waitJSlider(Container cont, ComponentChooser chooser, int index) { return((JSlider)waitComponent(cont, new JSliderFinder(chooser), index)); } /** * Waits 0'th JSlider in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JSlider instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JSlider waitJSlider(Container cont, ComponentChooser chooser) { return(waitJSlider(cont, chooser, 0)); } /** * Waits JSlider in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JSlider instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JSlider waitJSlider(Container cont, int index) { return(waitJSlider(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JSlider instance"), index)); } /** * Waits 0'th JSlider in container. * @param cont Container to search component in. * @return JSlider instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JSlider waitJSlider(Container cont) { return(waitJSlider(cont, 0)); } static { Timeouts.initDefault("JSliderOperator.OneScrollClickTimeout", ONE_SCROLL_CLICK_TIMEOUT); Timeouts.initDefault("JSliderOperator.WholeScrollTimeout", WHOLE_SCROLL_TIMEOUT); Timeouts.initDefault("JSliderOperator.ScrollingDelta", SCROLLING_DELTA); } /** * Defines scroll model. Default model value - CLICK_SCROLL_MODEL. * @param model New scroll model value. * @see #CLICK_SCROLL_MODEL * @see #PUSH_AND_WAIT_SCROLL_MODEL * @see #getScrollModel() * @see #scrollToValue(int) * @deprecated All actions are prformed throw a ScrollDriver registered * for this component, so value set by this method is ignored. */ public void setScrollModel(int model) { scrollModel = model; } /** * Specifies the scroll model. * @return Current scroll model value. * @see #setScrollModel(int) * @deprecated All actions are prformed throw a ScrollDriver registered * for this component, so value returned by this method is ignored. */ public int getScrollModel() { return(scrollModel); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; super.setTimeouts(timeouts); } public Timeouts getTimeouts() { return(timeouts); } /** * Scrolls slider to the position defined by a ScrollAdjuster implementation. * @param adj defines scrolling direction, and so on. * @throws TimeoutExpiredException */ public void scrollTo(final ScrollAdjuster adj) { makeComponentVisible(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scroll(JSliderOperator.this, adj); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("JSliderOperator.WholeScrollTimeout")); } /** * Moves slider to the necessary value. * @param value Value to move slider to. * @throws TimeoutExpiredException */ public void scrollToValue(int value) { output.printTrace("Move JSlider to " + Integer.toString(value) + " value\n" + toStringSource()); output.printGolden("Move JSlider to " + Integer.toString(value) + " value"); scrollTo(new ValueScrollAdjuster(value)); } /** * Moves slider to the maximal value. * @throws TimeoutExpiredException */ public void scrollToMaximum() { output.printTrace("Move JSlider to maximum value\n" + toStringSource()); output.printGolden("Move JSlider to maximum value"); scrollToValue(getMaximum()); } /** * Moves slider to the minimal value. * @throws TimeoutExpiredException */ public void scrollToMinimum() { output.printTrace("Move JSlider to minimum value\n" + toStringSource()); output.printGolden("Move JSlider to minimum value"); scrollToValue(getMinimum()); } public Hashtable getDump() { Hashtable result = super.getDump(); result.put(MINIMUM_DPROP, Integer.toString(((JSlider)getSource()).getMinimum())); result.put(MAXIMUM_DPROP, Integer.toString(((JSlider)getSource()).getMaximum())); result.put(ORIENTATION_DPROP, (((JSlider)getSource()).getOrientation() == JSlider.HORIZONTAL) ? HORIZONTAL_ORIENTATION_DPROP_VALUE : VERTICAL_ORIENTATION_DPROP_VALUE); result.put(IS_INVERTED_DPROP, ((JSlider)getSource()).getInverted() ? "true" : "false"); result.put(VALUE_DPROP, Integer.toString(((JSlider)getSource()).getValue())); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JSlider.addChangeListener(ChangeListener) through queue*/ public void addChangeListener(final ChangeListener changeListener) { runMapping(new MapVoidAction("addChangeListener") { public void map() { ((JSlider)getSource()).addChangeListener(changeListener); }});} /**Maps JSlider.createStandardLabels(int) through queue*/ public Hashtable createStandardLabels(final int i) { return((Hashtable)runMapping(new MapAction("createStandardLabels") { public Object map() { return(((JSlider)getSource()).createStandardLabels(i)); }}));} /**Maps JSlider.createStandardLabels(int, int) through queue*/ public Hashtable createStandardLabels(final int i, final int i1) { return((Hashtable)runMapping(new MapAction("createStandardLabels") { public Object map() { return(((JSlider)getSource()).createStandardLabels(i, i1)); }}));} /**Maps JSlider.getExtent() through queue*/ public int getExtent() { return(runMapping(new MapIntegerAction("getExtent") { public int map() { return(((JSlider)getSource()).getExtent()); }}));} /**Maps JSlider.getInverted() through queue*/ public boolean getInverted() { return(runMapping(new MapBooleanAction("getInverted") { public boolean map() { return(((JSlider)getSource()).getInverted()); }}));} /**Maps JSlider.getLabelTable() through queue*/ public Dictionary getLabelTable() { return((Dictionary)runMapping(new MapAction("getLabelTable") { public Object map() { return(((JSlider)getSource()).getLabelTable()); }}));} /**Maps JSlider.getMajorTickSpacing() through queue*/ public int getMajorTickSpacing() { return(runMapping(new MapIntegerAction("getMajorTickSpacing") { public int map() { return(((JSlider)getSource()).getMajorTickSpacing()); }}));} /**Maps JSlider.getMaximum() through queue*/ public int getMaximum() { return(runMapping(new MapIntegerAction("getMaximum") { public int map() { return(((JSlider)getSource()).getMaximum()); }}));} /**Maps JSlider.getMinimum() through queue*/ public int getMinimum() { return(runMapping(new MapIntegerAction("getMinimum") { public int map() { return(((JSlider)getSource()).getMinimum()); }}));} /**Maps JSlider.getMinorTickSpacing() through queue*/ public int getMinorTickSpacing() { return(runMapping(new MapIntegerAction("getMinorTickSpacing") { public int map() { return(((JSlider)getSource()).getMinorTickSpacing()); }}));} /**Maps JSlider.getModel() through queue*/ public BoundedRangeModel getModel() { return((BoundedRangeModel)runMapping(new MapAction("getModel") { public Object map() { return(((JSlider)getSource()).getModel()); }}));} /**Maps JSlider.getOrientation() through queue*/ public int getOrientation() { return(runMapping(new MapIntegerAction("getOrientation") { public int map() { return(((JSlider)getSource()).getOrientation()); }}));} /**Maps JSlider.getPaintLabels() through queue*/ public boolean getPaintLabels() { return(runMapping(new MapBooleanAction("getPaintLabels") { public boolean map() { return(((JSlider)getSource()).getPaintLabels()); }}));} /**Maps JSlider.getPaintTicks() through queue*/ public boolean getPaintTicks() { return(runMapping(new MapBooleanAction("getPaintTicks") { public boolean map() { return(((JSlider)getSource()).getPaintTicks()); }}));} /**Maps JSlider.getPaintTrack() through queue*/ public boolean getPaintTrack() { return(runMapping(new MapBooleanAction("getPaintTrack") { public boolean map() { return(((JSlider)getSource()).getPaintTrack()); }}));} /**Maps JSlider.getSnapToTicks() through queue*/ public boolean getSnapToTicks() { return(runMapping(new MapBooleanAction("getSnapToTicks") { public boolean map() { return(((JSlider)getSource()).getSnapToTicks()); }}));} /**Maps JSlider.getUI() through queue*/ public SliderUI getUI() { return((SliderUI)runMapping(new MapAction("getUI") { public Object map() { return(((JSlider)getSource()).getUI()); }}));} /**Maps JSlider.getValue() through queue*/ public int getValue() { return(runMapping(new MapIntegerAction("getValue") { public int map() { return(((JSlider)getSource()).getValue()); }}));} /**Maps JSlider.getValueIsAdjusting() through queue*/ public boolean getValueIsAdjusting() { return(runMapping(new MapBooleanAction("getValueIsAdjusting") { public boolean map() { return(((JSlider)getSource()).getValueIsAdjusting()); }}));} /**Maps JSlider.removeChangeListener(ChangeListener) through queue*/ public void removeChangeListener(final ChangeListener changeListener) { runMapping(new MapVoidAction("removeChangeListener") { public void map() { ((JSlider)getSource()).removeChangeListener(changeListener); }});} /**Maps JSlider.setExtent(int) through queue*/ public void setExtent(final int i) { runMapping(new MapVoidAction("setExtent") { public void map() { ((JSlider)getSource()).setExtent(i); }});} /**Maps JSlider.setInverted(boolean) through queue*/ public void setInverted(final boolean b) { runMapping(new MapVoidAction("setInverted") { public void map() { ((JSlider)getSource()).setInverted(b); }});} /**Maps JSlider.setLabelTable(Dictionary) through queue*/ public void setLabelTable(final Dictionary dictionary) { runMapping(new MapVoidAction("setLabelTable") { public void map() { ((JSlider)getSource()).setLabelTable(dictionary); }});} /**Maps JSlider.setMajorTickSpacing(int) through queue*/ public void setMajorTickSpacing(final int i) { runMapping(new MapVoidAction("setMajorTickSpacing") { public void map() { ((JSlider)getSource()).setMajorTickSpacing(i); }});} /**Maps JSlider.setMaximum(int) through queue*/ public void setMaximum(final int i) { runMapping(new MapVoidAction("setMaximum") { public void map() { ((JSlider)getSource()).setMaximum(i); }});} /**Maps JSlider.setMinimum(int) through queue*/ public void setMinimum(final int i) { runMapping(new MapVoidAction("setMinimum") { public void map() { ((JSlider)getSource()).setMinimum(i); }});} /**Maps JSlider.setMinorTickSpacing(int) through queue*/ public void setMinorTickSpacing(final int i) { runMapping(new MapVoidAction("setMinorTickSpacing") { public void map() { ((JSlider)getSource()).setMinorTickSpacing(i); }});} /**Maps JSlider.setModel(BoundedRangeModel) through queue*/ public void setModel(final BoundedRangeModel boundedRangeModel) { runMapping(new MapVoidAction("setModel") { public void map() { ((JSlider)getSource()).setModel(boundedRangeModel); }});} /**Maps JSlider.setOrientation(int) through queue*/ public void setOrientation(final int i) { runMapping(new MapVoidAction("setOrientation") { public void map() { ((JSlider)getSource()).setOrientation(i); }});} /**Maps JSlider.setPaintLabels(boolean) through queue*/ public void setPaintLabels(final boolean b) { runMapping(new MapVoidAction("setPaintLabels") { public void map() { ((JSlider)getSource()).setPaintLabels(b); }});} /**Maps JSlider.setPaintTicks(boolean) through queue*/ public void setPaintTicks(final boolean b) { runMapping(new MapVoidAction("setPaintTicks") { public void map() { ((JSlider)getSource()).setPaintTicks(b); }});} /**Maps JSlider.setPaintTrack(boolean) through queue*/ public void setPaintTrack(final boolean b) { runMapping(new MapVoidAction("setPaintTrack") { public void map() { ((JSlider)getSource()).setPaintTrack(b); }});} /**Maps JSlider.setSnapToTicks(boolean) through queue*/ public void setSnapToTicks(final boolean b) { runMapping(new MapVoidAction("setSnapToTicks") { public void map() { ((JSlider)getSource()).setSnapToTicks(b); }});} /**Maps JSlider.setUI(SliderUI) through queue*/ public void setUI(final SliderUI sliderUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JSlider)getSource()).setUI(sliderUI); }});} /**Maps JSlider.setValue(int) through queue*/ public void setValue(final int i) { runMapping(new MapVoidAction("setValue") { public void map() { ((JSlider)getSource()).setValue(i); }});} /**Maps JSlider.setValueIsAdjusting(boolean) through queue*/ public void setValueIsAdjusting(final boolean b) { runMapping(new MapVoidAction("setValueIsAdjusting") { public void map() { ((JSlider)getSource()).setValueIsAdjusting(b); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Checks component type. */ public static class JSliderFinder extends Finder { /** * Constructs JSliderFinder. * @param sf other searching criteria. */ public JSliderFinder(ComponentChooser sf) { super(JSlider.class, sf); } /** * Constructs JSliderFinder. */ public JSliderFinder() { super(JSlider.class); } } private class ValueScrollAdjuster implements ScrollAdjuster { int value; public ValueScrollAdjuster(int value) { this.value = value; } public int getScrollDirection() { if(getValue() == value) { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } else { return((getValue() < value) ? ScrollAdjuster.INCREASE_SCROLL_DIRECTION : ScrollAdjuster.DECREASE_SCROLL_DIRECTION); } } public int getScrollOrientation() { return(getOrientation()); } public String getDescription() { return("Scroll to " + Integer.toString(value) + " value"); } } } Jemmy2/src/org/netbeans/jemmy/operators/JMenuBarOperator.java0000644000175000017500000007305311245712237023337 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Insets; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.Hashtable; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.SingleSelectionModel; import javax.swing.plaf.MenuBarUI; import org.netbeans.jemmy.Action; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.MenuDriver; /** *

Timeouts used:
* JMenuOperator.WaitBeforePopupTimeout - time to sleep before popup expanding
* JMenuOperator.WaitPopupTimeout - time to wait popup displayed
* ComponentOperator.WaitComponentTimeout - time to wait button displayed
. * * @see org.netbeans.jemmy.Timeouts * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JMenuBarOperator extends JComponentOperator implements Outputable, Timeoutable { /** * Identifier for a "submenu" properties. * @see #getDump */ public static final String SUBMENU_PREFIX_DPROP = "Submenu"; private TestOut output; private Timeouts timeouts; private MenuDriver driver; /** * Constructor. * @param b a component */ public JMenuBarOperator(JMenuBar b) { super(b); driver = DriverManager.getMenuDriver(getClass()); } /** * Constructs a JMenuBarOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JMenuBarOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JMenuBar)cont. waitSubComponent(new JMenuBarFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JMenuBarOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JMenuBarOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @throws TimeoutExpiredException */ public JMenuBarOperator(ContainerOperator cont) { this((JMenuBar)waitComponent(cont, new JMenuBarFinder(), 0)); copyEnvironment(cont); } /** * Searches JMenuBar in frame. * @param frame a container * @return found JMenuBar */ public static JMenuBar findJMenuBar(JFrame frame) { return(findJMenuBar((Container)frame)); } /** * Searches JMenuBar in dialog. * @param dialog a container * @return found JMenuBar */ public static JMenuBar findJMenuBar(JDialog dialog) { return(findJMenuBar((Container)dialog)); } /** * Searches JMenuBar in container. * @param cont a container * @return found JMenuBar * @throws TimeoutExpiredException */ public static JMenuBar waitJMenuBar(Container cont) { return((JMenuBar)waitComponent(cont, new JMenuBarFinder())); } /** * Waits JMenuBar in frame. * @param frame a container * @return found JMenuBar * @throws TimeoutExpiredException */ public static JMenuBar waitJMenuBar(JFrame frame) { return(waitJMenuBar((Container)frame)); } /** * Waits JMenuBar in dialog. * @param dialog a container * @return found JMenuBar * @throws TimeoutExpiredException */ public static JMenuBar waitJMenuBar(JDialog dialog) { return(waitJMenuBar((Container)dialog)); } /** * Waits JMenuBar in container. * @param cont a container * @return found JMenuBar */ public static JMenuBar findJMenuBar(Container cont) { return((JMenuBar)findComponent(cont, new JMenuBarFinder())); } static { //necessary to init timeouts JMenuOperator.performInit(); } public void setOutput(TestOut out) { super.setOutput(out); output = out; } public TestOut getOutput() { return(output); } public void setTimeouts(Timeouts times) { super.setTimeouts(times); timeouts = times; } public Timeouts getTimeouts() { return(timeouts); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = DriverManager.getMenuDriver(this); } /** * Pushes menu. * @param choosers Array of choosers to find menuItems to push. * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(final ComponentChooser[] choosers) { makeComponentVisible(); return((JMenuItem)produceTimeRestricted(new Action() { public Object launch(Object obj) { //TDB 1.5 menu workaround getQueueTool().waitEmpty(); Object result = driver.pushMenu(JMenuBarOperator.this, JMenuOperator.converChoosers(choosers)); getQueueTool().waitEmpty(); return(result); } public String getDescription() { return(JMenuOperator.createDescription(choosers)); } }, getTimeouts().getTimeout("JMenuOperator.PushMenuTimeout"))); } /** * Executes pushMenu(choosers) in a separate thread. * @param choosers Array of choosers to find menuItems to push. * @see #pushMenu(ComponentChooser[]) */ public void pushMenuNoBlock(final ComponentChooser[] choosers) { makeComponentVisible(); produceNoBlocking(new NoBlockingAction("Menu pushing") { public Object doAction(Object param) { //TDB 1.5 menu workaround getQueueTool().waitEmpty(); Object result = driver.pushMenu(JMenuBarOperator.this, JMenuOperator.converChoosers(choosers)); getQueueTool().waitEmpty(); return(result); } }); } /** * Pushes menu. * @param names an array of menu texts. * @param comparator a string comparision algorithm * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String[] names, StringComparator comparator) { return(pushMenu(JMenuItemOperator.createChoosers(names, comparator))); } /** * Pushes menu. * @param names Menu items texts. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @return Last pushed JMenuItem. * @throws TimeoutExpiredException * @deprecated Use pushMenu(String[]) or pushMenu(String[], StringComparator) */ public JMenuItem pushMenu(String[] names, boolean ce, boolean ccs) { return(pushMenu(names, new DefaultStringComparator(ce, ccs))); } /** * Executes pushMenu(names, ce, ccs) in a separate thread. * @param names an array of menu texts. * @param comparator a string comparision algorithm */ public void pushMenuNoBlock(String[] names, StringComparator comparator) { pushMenuNoBlock(JMenuItemOperator.createChoosers(names, comparator)); } /** * Executes pushMenu(names, ce, ccs) in a separate thread. * @param names Menu items texts. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @see #pushMenu(String[], boolean,boolean) * @deprecated Use pushMenuNoBlock(String[]) or pushMenuNoBlock(String[], StringComparator) */ public void pushMenuNoBlock(String[] names, boolean ce, boolean ccs) { pushMenuNoBlock(names, new DefaultStringComparator(ce, ccs)); } /** * Pushes menu. * @param names Menu items texts. * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String[] names) { return(pushMenu(names, getComparator())); } /** * Executes pushMenu(names) in a separate thread. * @param names Menu items texts. * @see #pushMenu(String[]) */ public void pushMenuNoBlock(String[] names) { pushMenuNoBlock(names, getComparator()); } /** * Pushes menu. * @param path a menu path. * @param delim a path delimiter. * @param comparator a string comparision algorithm * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String path, String delim, StringComparator comparator) { return(pushMenu(parseString(path, delim), comparator)); } /** * Pushes menu. Uses PathParser assigned to this operator. * @param path a menu path. * @param comparator a string comparision algorithm * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String path, StringComparator comparator) { return(pushMenu(parseString(path), comparator)); } /** * Pushes menu. * @param path String menupath representation ("File/New", for example). * @param delim String menupath divider ("/"). * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @return Last pushed JMenuItem. * @throws TimeoutExpiredException * @deprecated Use pushMenu(String, String) or pushMenu(String, String, StringComparator) */ public JMenuItem pushMenu(String path, String delim, boolean ce, boolean ccs) { return(pushMenu(parseString(path, delim), ce, ccs)); } /** * Executes pushMenu(names, delim, comparator) in a separate thread. * @param path a menu path. * @param delim a path delimiter. * @param comparator a string comparision algorithm */ public void pushMenuNoBlock(String path, String delim, StringComparator comparator) { pushMenuNoBlock(parseString(path, delim), comparator); } /** * Executes pushMenu(names, comparator) in a separate thread. * Uses PathParser assigned to this operator. * @param path a menu path. * @param comparator a string comparision algorithm */ public void pushMenuNoBlock(String path, StringComparator comparator) { pushMenuNoBlock(parseString(path), comparator); } /** * Executes pushMenu(path, delim, ce, ccs) in a separate thread. * @param path String menupath representation ("File/New", for example). * @param delim String menupath divider ("/"). * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @see #pushMenu * @deprecated Use pushMenuNoBlock(String, String) or pushMenuNoBlock(String, String, StringComparator) */ public void pushMenuNoBlock(String path, String delim, boolean ce, boolean ccs) { pushMenuNoBlock(parseString(path, delim), ce, ccs); } /** * Pushes menu. * @param path String menupath representation ("File/New", for example). * @param delim String menupath divider ("/"). * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String path, String delim) { return(pushMenu(parseString(path, delim))); } /** * Pushes menu. Uses PathParser assigned to this operator. * @param path String menupath representation ("File/New", for example). * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String path) { return(pushMenu(parseString(path))); } /** * Executes pushMenu(path, delim) in a separate thread. * @param path String menupath representation ("File/New", for example). * @param delim String menupath divider ("/"). */ public void pushMenuNoBlock(String path, String delim) { pushMenuNoBlock(parseString(path, delim)); } /** * Executes pushMenu(path) in a separate thread. * @param path String menupath representation ("File/New", for example). */ public void pushMenuNoBlock(String path) { pushMenuNoBlock(parseString(path)); } public JMenuItemOperator[] showMenuItems(ComponentChooser[] choosers) { if(choosers == null || choosers.length == 0) { return(JMenuItemOperator.getMenuItems((MenuElement)getSource(), this)); } else { return(JMenuItemOperator.getMenuItems((JMenu)pushMenu(choosers), this)); } } /** * Shows submenu of menu specified by a path parameter. * @param path an array of menu texts. * @param comparator a string comparision algorithm * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String[] path, StringComparator comparator) { if(path == null || path.length == 0) { return(JMenuItemOperator.getMenuItems((MenuElement)getSource(), this)); } else { return(JMenuItemOperator.getMenuItems((JMenu)pushMenu(path, comparator), this)); } } /** * Shows submenu of menu specified by a path parameter. * Uses StringComparator assigned to the operator. * @param path an array of menu texts. * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String[] path) { return(showMenuItems(path, getComparator())); } /** * Shows submenu of menu specified by a path parameter. * @param path a string identifying the menu path. * @param delim a path delimiter. * @param comparator a string comparision algorithm * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String path, String delim, StringComparator comparator ) { return(showMenuItems(parseString(path, delim), comparator)); } /** * Shows submenu of menu specified by a path parameter. * Uses PathParser assigned to this operator. * @param path a string identifying the menu path. * @param comparator a string comparision algorithm * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String path, StringComparator comparator ) { return(showMenuItems(parseString(path), comparator)); } /** * Shows submenu of menu specified by a path parameter. * Uses StringComparator assigned to the operator. * @param path a string identifying the menu path. * @param delim a path delimiter. * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String path, String delim) { return(showMenuItems(path, delim, getComparator())); } /** * Shows submenu of menu specified by a path parameter. * Uses PathParser assigned to this operator. * Uses StringComparator assigned to the operator. * @param path a string identifying the menu path. * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String path) { return(showMenuItems(path, getComparator())); } public JMenuItemOperator showMenuItem(ComponentChooser[] choosers) { ComponentChooser[] parentPath = getParentPath(choosers); JMenu menu; ContainerOperator menuCont; if(parentPath.length > 0) { menu = (JMenu)pushMenu(getParentPath(choosers)); menuCont = new ContainerOperator(menu.getPopupMenu()); menuCont.copyEnvironment(this); } else { menuCont = this; } JMenuItemOperator result = new JMenuItemOperator(menuCont, choosers[choosers.length - 1]); result.copyEnvironment(this); return(result); } /** * Expends all menus to show menu item specified by a path parameter. * @param path an array of menu texts. * @param comparator a string comparision algorithm * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String[] path, StringComparator comparator ) { String[] parentPath = getParentPath(path); JMenu menu; ContainerOperator menuCont; if(parentPath.length > 0) { menu = (JMenu)pushMenu(getParentPath(path), comparator); menuCont = new ContainerOperator(menu.getPopupMenu()); menuCont.copyEnvironment(this); } else { menuCont = this; } JMenuItemOperator result; // isVisible() on items returns false on mac, so we need a special searcher. if(System.getProperty("os.name").toLowerCase().indexOf("mac") > -1) { // NOI18N ComponentSearcher searcher = new ComponentSearcher((Container)menuCont.getSource()); searcher.setOutput(output); Component c = searcher.findComponent(new JMenuItemOperator.JMenuItemByLabelFinder(path[path.length-1], getComparator())); result = new JMenuItemOperator((JMenuItem)c); } else { result = new JMenuItemOperator(menuCont, path[path.length - 1]); } result.copyEnvironment(this); return(result); } /** * Expands all menus to show menu item specified by a path parameter. * @param path an array of menu texts. * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String[] path) { return(showMenuItem(path, getComparator())); } /** * Expands all menus to show menu item specified by a path parameter. * @param path a string identifying the menu path. * @param delim a path delimiter. * @param comparator a string comparision algorithm * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String path, String delim, StringComparator comparator ) { return(showMenuItem(parseString(path, delim), comparator)); } /** * Expands all menus to show menu item specified by a path parameter. * Uses PathParser assigned to this operator. * @param path a string identifying the menu path. * @param comparator a string comparision algorithm * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String path, StringComparator comparator ) { return(showMenuItem(parseString(path), comparator)); } /** * Expands all menus to show menu item specified by a path parameter. * Uses StringComparator assigned to the operator. * @param path a string identifying the menu path. * @param delim a path delimiter. * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String path, String delim) { return(showMenuItem(path, delim, getComparator())); } /** * Expands all menus to show menu item specified by a path parameter. * Uses PathParser assigned to this operator. * Uses StringComparator assigned to the operator. * @param path a string identifying the menu path. * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String path) { return(showMenuItem(path, getComparator())); } /** * Closes all expanded submenus. */ public void closeSubmenus() { JMenu menu = (JMenu)findSubComponent(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp instanceof JMenu && ((JMenu)comp).isPopupMenuVisible()); } public String getDescription() { return("Expanded JMenu"); } }); if(menu != null) { JMenuOperator oper = new JMenuOperator(menu); oper.copyEnvironment(this); oper.push(); } } public Hashtable getDump() { Hashtable result = super.getDump(); String[] items = new String[((JMenuBar)getSource()).getMenuCount()]; for(int i = 0; i < ((JMenuBar)getSource()).getMenuCount(); i++) { if(((JMenuBar)getSource()).getMenu(i) != null) { items[i] = ((JMenuBar)getSource()).getMenu(i).getText(); } else { items[i] = "null"; } } addToDump(result, SUBMENU_PREFIX_DPROP, items); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JMenuBar.add(JMenu) through queue*/ public JMenu add(final JMenu jMenu) { return((JMenu)runMapping(new MapAction("add") { public Object map() { return(((JMenuBar)getSource()).add(jMenu)); }}));} /**Maps JMenuBar.getComponentIndex(Component) through queue*/ public int getComponentIndex(final Component component) { return(runMapping(new MapIntegerAction("getComponentIndex") { public int map() { return(((JMenuBar)getSource()).getComponentIndex(component)); }}));} /**Maps JMenuBar.getHelpMenu() through queue*/ public JMenu getHelpMenu() { return((JMenu)runMapping(new MapAction("getHelpMenu") { public Object map() { return(((JMenuBar)getSource()).getHelpMenu()); }}));} /**Maps JMenuBar.getMargin() through queue*/ public Insets getMargin() { return((Insets)runMapping(new MapAction("getMargin") { public Object map() { return(((JMenuBar)getSource()).getMargin()); }}));} /**Maps JMenuBar.getMenu(int) through queue*/ public JMenu getMenu(final int i) { return((JMenu)runMapping(new MapAction("getMenu") { public Object map() { return(((JMenuBar)getSource()).getMenu(i)); }}));} /**Maps JMenuBar.getMenuCount() through queue*/ public int getMenuCount() { return(runMapping(new MapIntegerAction("getMenuCount") { public int map() { return(((JMenuBar)getSource()).getMenuCount()); }}));} /**Maps JMenuBar.getSelectionModel() through queue*/ public SingleSelectionModel getSelectionModel() { return((SingleSelectionModel)runMapping(new MapAction("getSelectionModel") { public Object map() { return(((JMenuBar)getSource()).getSelectionModel()); }}));} /**Maps JMenuBar.getSubElements() through queue*/ public MenuElement[] getSubElements() { return((MenuElement[])runMapping(new MapAction("getSubElements") { public Object map() { return(((JMenuBar)getSource()).getSubElements()); }}));} /**Maps JMenuBar.getUI() through queue*/ public MenuBarUI getUI() { return((MenuBarUI)runMapping(new MapAction("getUI") { public Object map() { return(((JMenuBar)getSource()).getUI()); }}));} /**Maps JMenuBar.isBorderPainted() through queue*/ public boolean isBorderPainted() { return(runMapping(new MapBooleanAction("isBorderPainted") { public boolean map() { return(((JMenuBar)getSource()).isBorderPainted()); }}));} /**Maps JMenuBar.isSelected() through queue*/ public boolean isSelected() { return(runMapping(new MapBooleanAction("isSelected") { public boolean map() { return(((JMenuBar)getSource()).isSelected()); }}));} /**Maps JMenuBar.menuSelectionChanged(boolean) through queue*/ public void menuSelectionChanged(final boolean b) { runMapping(new MapVoidAction("menuSelectionChanged") { public void map() { ((JMenuBar)getSource()).menuSelectionChanged(b); }});} /**Maps JMenuBar.processKeyEvent(KeyEvent, MenuElement[], MenuSelectionManager) through queue*/ public void processKeyEvent(final KeyEvent keyEvent, final MenuElement[] menuElement, final MenuSelectionManager menuSelectionManager) { runMapping(new MapVoidAction("processKeyEvent") { public void map() { ((JMenuBar)getSource()).processKeyEvent(keyEvent, menuElement, menuSelectionManager); }});} /**Maps JMenuBar.processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager) through queue*/ public void processMouseEvent(final MouseEvent mouseEvent, final MenuElement[] menuElement, final MenuSelectionManager menuSelectionManager) { runMapping(new MapVoidAction("processMouseEvent") { public void map() { ((JMenuBar)getSource()).processMouseEvent(mouseEvent, menuElement, menuSelectionManager); }});} /**Maps JMenuBar.setBorderPainted(boolean) through queue*/ public void setBorderPainted(final boolean b) { runMapping(new MapVoidAction("setBorderPainted") { public void map() { ((JMenuBar)getSource()).setBorderPainted(b); }});} /**Maps JMenuBar.setHelpMenu(JMenu) through queue*/ public void setHelpMenu(final JMenu jMenu) { runMapping(new MapVoidAction("setHelpMenu") { public void map() { ((JMenuBar)getSource()).setHelpMenu(jMenu); }});} /**Maps JMenuBar.setMargin(Insets) through queue*/ public void setMargin(final Insets insets) { runMapping(new MapVoidAction("setMargin") { public void map() { ((JMenuBar)getSource()).setMargin(insets); }});} /**Maps JMenuBar.setSelected(Component) through queue*/ public void setSelected(final Component component) { runMapping(new MapVoidAction("setSelected") { public void map() { ((JMenuBar)getSource()).setSelected(component); }});} /**Maps JMenuBar.setSelectionModel(SingleSelectionModel) through queue*/ public void setSelectionModel(final SingleSelectionModel singleSelectionModel) { runMapping(new MapVoidAction("setSelectionModel") { public void map() { ((JMenuBar)getSource()).setSelectionModel(singleSelectionModel); }});} /**Maps JMenuBar.setUI(MenuBarUI) through queue*/ public void setUI(final MenuBarUI menuBarUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JMenuBar)getSource()).setUI(menuBarUI); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Checks component type. */ public static class JMenuBarFinder extends Finder { /** * Constructs JMenuBarFinder. * @param sf other searching criteria. */ public JMenuBarFinder(ComponentChooser sf) { super(JMenuBar.class, sf); } /** * Constructs JMenuBarFinder. */ public JMenuBarFinder() { super(JMenuBar.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JRadioButtonOperator.java0000644000175000017500000002450211245712237024233 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Container; import javax.swing.JRadioButton; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.TimeoutExpiredException; /** * *

Timeouts used:
* AbstractButtonOperator.PushButtonTimeout - time between button pressing and releasing
* ComponentOperator.WaitComponentTimeout - time to wait button displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait button enabled
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JRadioButtonOperator extends JToggleButtonOperator{ /** * Constructor. * @param b a component */ public JRadioButtonOperator(JRadioButton b) { super(b); } /** * Constructs a JRadioButtonOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JRadioButtonOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JRadioButton)cont. waitSubComponent(new JRadioButtonFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JRadioButtonOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JRadioButtonOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JRadioButtonOperator(ContainerOperator cont, String text, int index) { this((JRadioButton) waitComponent(cont, new JRadioButtonFinder(new AbstractButtonOperator. AbstractButtonByLabelFinder(text, cont.getComparator())), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JRadioButtonOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JRadioButtonOperator(ContainerOperator cont, int index) { this((JRadioButton) waitComponent(cont, new JRadioButtonFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JRadioButtonOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JRadioButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JRadioButton instance or null if component was not found. */ public static JRadioButton findJRadioButton(Container cont, ComponentChooser chooser, int index) { return((JRadioButton)findJToggleButton(cont, new JRadioButtonFinder(chooser), index)); } /** * Searches 0'th JRadioButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JRadioButton instance or null if component was not found. */ public static JRadioButton findJRadioButton(Container cont, ComponentChooser chooser) { return(findJRadioButton(cont, chooser, 0)); } /** * Searches JRadioButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JRadioButton instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JRadioButton findJRadioButton(Container cont, String text, boolean ce, boolean ccs, int index) { return(findJRadioButton(cont, new JRadioButtonFinder(new AbstractButtonOperator. AbstractButtonByLabelFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Searches JRadioButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JRadioButton instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JRadioButton findJRadioButton(Container cont, String text, boolean ce, boolean ccs) { return(findJRadioButton(cont, text, ce, ccs, 0)); } /** * Waits JRadioButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JRadioButton instance. * @throws TimeoutExpiredException */ public static JRadioButton waitJRadioButton(Container cont, ComponentChooser chooser, int index) { return((JRadioButton)waitJToggleButton(cont, new JRadioButtonFinder(chooser), index)); } /** * Waits 0'th JRadioButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JRadioButton instance. * @throws TimeoutExpiredException */ public static JRadioButton waitJRadioButton(Container cont, ComponentChooser chooser) { return(waitJRadioButton(cont, chooser, 0)); } /** * Waits JRadioButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JRadioButton instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JRadioButton waitJRadioButton(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitJRadioButton(cont, new JRadioButtonFinder(new AbstractButtonOperator. AbstractButtonByLabelFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Waits JRadioButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JRadioButton instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JRadioButton waitJRadioButton(Container cont, String text, boolean ce, boolean ccs) { return(waitJRadioButton(cont, text, ce, ccs, 0)); } /** * Checks component type. */ public static class JRadioButtonFinder extends Finder { /** * Constructs JRadioButtonFinder. * @param sf other searching criteria. */ public JRadioButtonFinder(ComponentChooser sf) { super(JRadioButton.class, sf); } /** * Constructs JRadioButtonFinder. */ public JRadioButtonFinder() { super(JRadioButton.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JSpinnerOperator.java0000644000175000017500000011255011245712304023413 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.text.ParseException; import java.util.Date; import java.util.Hashtable; import java.util.List; import javax.swing.JComponent; import javax.swing.JSpinner; import javax.swing.SpinnerDateModel; import javax.swing.SpinnerListModel; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.event.ChangeListener; import javax.swing.plaf.SpinnerUI; import org.netbeans.jemmy.Action; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.ScrollDriver; import org.netbeans.jemmy.drivers.scrolling.ScrollAdjuster; /** * Provides methods to work with javax.swing.JSpinner component
* * @see NumberSpinnerOperator * @see ListSpinnerOperator * @see DateSpinnerOperator * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class JSpinnerOperator extends JComponentOperator implements Timeoutable, Outputable { /** * Identifier for a "value" property. * @see #getDump */ public static final String VALUE_DPROP = "Value"; private final static long WHOLE_SCROLL_TIMEOUT = 60000; private Timeouts timeouts; private TestOut output; private ScrollDriver driver; private JButtonOperator increaseOperator = null; private JButtonOperator decreaseOperator = null; /** * Constructor. * @param b JSpinner component. */ public JSpinnerOperator(JSpinner b) { super(b); driver = DriverManager.getScrollDriver(getClass()); } /** * Constructs a JSpinnerOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @throws TimeoutExpiredException */ public JSpinnerOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JSpinner)cont. waitSubComponent(new JSpinnerFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JSpinnerOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @throws TimeoutExpiredException */ public JSpinnerOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructs a JSpinnerOperator object. * @param cont The operator for a container containing the sought for button. * @param text toString() representation of the current spinner value. * @param index Ordinal component index. The first component has index 0. * @throws TimeoutExpiredException */ public JSpinnerOperator(ContainerOperator cont, String text, int index) { this((JSpinner)waitComponent(cont, new JSpinnerByTextFinder(text, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructs a JSpinnerOperator object. * @param cont The operator for a container containing the sought for button. * @param text toString() representation of the current spinner value. * @throws TimeoutExpiredException */ public JSpinnerOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JSpinnerOperator(ContainerOperator cont, int index) { this((JSpinner)waitComponent(cont, new JSpinnerFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @throws TimeoutExpiredException */ public JSpinnerOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JSpinner in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JSpinner instance or null if component was not found. */ public static JSpinner findJSpinner(Container cont, ComponentChooser chooser, int index) { return((JSpinner)findComponent(cont, new JSpinnerFinder(chooser), index)); } /** * Searches 0'th JSpinner in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JSpinner instance or null if component was not found. */ public static JSpinner findJSpinner(Container cont, ComponentChooser chooser) { return(findJSpinner(cont, chooser, 0)); } /** * Searches JSpinner in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JSpinner instance or null if component was not found. */ public static JSpinner findJSpinner(Container cont, int index) { return(findJSpinner(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JSpinner instance"), index)); } /** * Searches 0'th JSpinner in container. * @param cont Container to search component in. * @return JSpinner instance or null if component was not found. */ public static JSpinner findJSpinner(Container cont) { return(findJSpinner(cont, 0)); } /** * Waits JSpinner in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JSpinner instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JSpinner waitJSpinner(Container cont, ComponentChooser chooser, int index) { return((JSpinner)waitComponent(cont, new JSpinnerFinder(chooser), index)); } /** * Waits 0'th JSpinner in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JSpinner instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JSpinner waitJSpinner(Container cont, ComponentChooser chooser) { return(waitJSpinner(cont, chooser, 0)); } /** * Waits JSpinner in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JSpinner instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JSpinner waitJSpinner(Container cont, int index) { return(waitJSpinner(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JSpinner instance"), index)); } /** * Waits 0'th JSpinner in container. * @param cont Container to search component in. * @return JSpinner instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JSpinner waitJSpinner(Container cont) { return(waitJSpinner(cont, 0)); } /** * Checks operator's model type. * @param oper an operator to check model * @param modelClass a model class. * @throws SpinnerModelException if an operator's model is not an instance of * specified class. */ public static void checkModel(JSpinnerOperator oper, Class modelClass) { if(!modelClass.isInstance(oper.getModel())) { throw(new SpinnerModelException("JSpinner model is not a " + modelClass.getName(), oper.getSource())); } } static { Timeouts.initDefault("JSpinnerOperator.WholeScrollTimeout", WHOLE_SCROLL_TIMEOUT); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; super.setTimeouts(timeouts); } public Timeouts getTimeouts() { return(timeouts); } /** * Returns an instance of NumberSpinnerOperator operator, * the operator used for JSpinner having SpinnerNumberModel model. * @return a NumberSpinnerOperator created for the same JSpinner as this operator. * @throws SpinnerModelException if an operator's model is not an instance of SpinnerNumberModel */ public NumberSpinnerOperator getNumberSpinner() { return(new NumberSpinnerOperator(this)); } /** * Returns an instance of ListSpinnerOperator operator, * the operator used for JSpinner having SpinnerListModel model. * @return a ListSpinnerOperator created for the same JSpinner as this operator. * @throws SpinnerModelException if an operator's model is not an instance of SpinnerListModel */ public ListSpinnerOperator getListSpinner() { return(new ListSpinnerOperator(this)); } /** * Returns an instance of DateSpinnerOperator operator, * the operator used for JSpinner having SpinnerDateModel model. * @return a DateSpinnerOperator created for the same JSpinner as this operator. * @throws SpinnerModelException if an operator's model is not an instance of SpinnerDateModel */ public DateSpinnerOperator getDateSpinner() { return(new DateSpinnerOperator(this)); } /** * Scrolls to reach a condition specified by ScrollAdjuster * @param adj scrolling criteria. */ public void scrollTo(final ScrollAdjuster adj) { produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scroll(JSpinnerOperator.this, adj); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("JSpinnerOperator.WholeScrollTimeout")); } /** * Scrolls to maximum value. * @throws SpinnerModelException if an operator's model does not have a maximum value. */ public void scrollToMaximum() { produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scrollToMaximum(JSpinnerOperator.this, SwingConstants.VERTICAL); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("JSpinnerOperator.WholeScrollTimeout")); } /** * Scrolls to minimum value. * @throws SpinnerModelException if an operator's model does not have a minimum value. */ public void scrollToMinimum() { produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scrollToMinimum(JSpinnerOperator.this, SwingConstants.VERTICAL); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("JSpinnerOperator.WholeScrollTimeout")); } /** * Scrolls to exact match of a spinner value to the specified value. * @param value an value to scroll to. * @param direction a scrolling direction - one of ScrollAdjuster.*_SCROLL_DIRECTION fields. */ public void scrollToObject(Object value, int direction) { scrollTo(new ExactScrollAdjuster(this, value, direction)); } /** * Scrolls to matching of getValue().toString() with the pattern. * @param pattern a pattern to compare with * @param comparator a string comparision criteria * @param direction a scrolling direction - one of ScrollAdjuster.*_SCROLL_DIRECTION fields. */ public void scrollToString(String pattern, StringComparator comparator, int direction) { scrollTo(new ToStringScrollAdjuster(this, pattern, comparator, direction)); } /** * Scrolls to matching of getValue().toString() with the pattern. * Uses StringComparator assigned to the operator. * @param pattern a pattern to compare with * @param direction a scrolling direction - one of ScrollAdjuster.*_SCROLL_DIRECTION fields. */ public void scrollToString(String pattern, int direction) { scrollToString(pattern, getComparator(), direction); } /** * Returns an operator for a button used for value increasing. * @return an operator for a first JButton inside this spinner. */ public JButtonOperator getIncreaseOperator() { if(increaseOperator == null) { increaseOperator = (JButtonOperator)createSubOperator(new JButtonOperator.JButtonFinder(), 0); increaseOperator.copyEnvironment(this); increaseOperator.setOutput(getOutput().createErrorOutput()); } return(increaseOperator); } /** * Returns an operator for a button used for value decreasing. * @return an operator for a second JButton inside this spinner. */ public JButtonOperator getDecreaseOperator() { if(decreaseOperator == null) { decreaseOperator = (JButtonOperator)createSubOperator(new JButtonOperator.JButtonFinder(), 1); decreaseOperator.copyEnvironment(this); decreaseOperator.setOutput(getOutput().createErrorOutput()); } return(decreaseOperator); } /** * Returns a minimal value. Returns null if model is not * one of the following: * javax.swing.SpinnerDateModel, * javax.swing.SpinnerListModel, * javax.swing.SpinnerNumberModel. * Also, returns null if the model does not have a minimal value. * @return a minimal value. */ public Object getMinimum() { SpinnerModel model = getModel(); if (model instanceof SpinnerNumberModel) { return(((SpinnerNumberModel)model).getMinimum()); } else if(model instanceof SpinnerDateModel) { return(((SpinnerDateModel)model).getEnd()); } else if(model instanceof SpinnerListModel) { List list = ((SpinnerListModel)model).getList(); return(list.get(list.size() - 1)); } else { return(null); } } /** * Returns a maximal value. Returns null if model is not * one of the following: * javax.swing.SpinnerDateModel, * javax.swing.SpinnerListModel, * javax.swing.SpinnerNumberModel. * Also, returns null if the model does not have a maximal value. * @return a maximal value. */ public Object getMaximum() { SpinnerModel model = getModel(); if (model instanceof SpinnerNumberModel) { return(((SpinnerNumberModel)model).getMaximum()); } else if(model instanceof SpinnerDateModel) { return(((SpinnerDateModel)model).getEnd()); } else if(model instanceof SpinnerListModel) { List list = ((SpinnerListModel)model).getList(); return(list.get(list.size() - 1)); } else { return(null); } } public Hashtable getDump() { Hashtable result = super.getDump(); result.put(VALUE_DPROP, ((JSpinner)getSource()).getValue().toString()); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JSpinner.getValue() through queue*/ public Object getValue() { return((Object)runMapping(new MapAction("getValue") { public Object map() { return(((JSpinner)getSource()).getValue()); }}));} /**Maps JSpinner.setValue(Object) through queue*/ public void setValue(final Object object) { runMapping(new MapVoidAction("setValue") { public void map() { ((JSpinner)getSource()).setValue(object); }});} /**Maps JSpinner.getUI() through queue*/ public SpinnerUI getUI() { return((SpinnerUI)runMapping(new MapAction("getUI") { public Object map() { return(((JSpinner)getSource()).getUI()); }}));} /**Maps JSpinner.setUI(SpinnerUI) through queue*/ public void setUI(final SpinnerUI spinnerUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JSpinner)getSource()).setUI(spinnerUI); }});} /**Maps JSpinner.setModel(SpinnerModel) through queue*/ public void setModel(final SpinnerModel spinnerModel) { runMapping(new MapVoidAction("setModel") { public void map() { ((JSpinner)getSource()).setModel(spinnerModel); }});} /**Maps JSpinner.getModel() through queue*/ public SpinnerModel getModel() { return((SpinnerModel)runMapping(new MapAction("getModel") { public Object map() { return(((JSpinner)getSource()).getModel()); }}));} /**Maps JSpinner.getNextValue() through queue*/ public Object getNextValue() { return((Object)runMapping(new MapAction("getNextValue") { public Object map() { return(((JSpinner)getSource()).getNextValue()); }}));} /**Maps JSpinner.addChangeListener(ChangeListener) through queue*/ public void addChangeListener(final ChangeListener changeListener) { runMapping(new MapVoidAction("addChangeListener") { public void map() { ((JSpinner)getSource()).addChangeListener(changeListener); }});} /**Maps JSpinner.removeChangeListener(ChangeListener) through queue*/ public void removeChangeListener(final ChangeListener changeListener) { runMapping(new MapVoidAction("removeChangeListener") { public void map() { ((JSpinner)getSource()).removeChangeListener(changeListener); }});} /**Maps JSpinner.getChangeListeners() through queue*/ public ChangeListener[] getChangeListeners() { return((ChangeListener[])runMapping(new MapAction("getChangeListeners") { public Object map() { return(((JSpinner)getSource()).getChangeListeners()); }}));} /**Maps JSpinner.getPreviousValue() through queue*/ public Object getPreviousValue() { return((Object)runMapping(new MapAction("getPreviousValue") { public Object map() { return(((JSpinner)getSource()).getPreviousValue()); }}));} /**Maps JSpinner.setEditor(JComponent) through queue*/ public void setEditor(final JComponent jComponent) { runMapping(new MapVoidAction("setEditor") { public void map() { ((JSpinner)getSource()).setEditor(jComponent); }});} /**Maps JSpinner.getEditor() through queue*/ public JComponent getEditor() { return((JComponent)runMapping(new MapAction("getEditor") { public Object map() { return(((JSpinner)getSource()).getEditor()); }}));} /**Maps JSpinner.commitEdit() through queue*/ public void commitEdit() { runMapping(new MapVoidAction("commitEdit") { public void map() throws ParseException { ((JSpinner)getSource()).commitEdit(); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Allows to find component by text. */ public static class JSpinnerByTextFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs JSpinnerByTextFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public JSpinnerByTextFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs JSpinnerByTextFinder. * @param lb a text pattern */ public JSpinnerByTextFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JSpinner) { if(((JSpinner)comp).getValue() != null) { return(comparator.equals(((JSpinner)comp).getValue().toString(), label)); } } return(false); } public String getDescription() { return("JSpinner with text \"" + label + "\""); } } /** * Checks component type. */ public static class JSpinnerFinder extends Finder { /** * Constructs JSpinnerFinder. * @param sf other searching criteria. */ public JSpinnerFinder(ComponentChooser sf) { super(JSpinner.class, sf); } /** * Constructs JSpinnerFinder. */ public JSpinnerFinder() { super(JSpinner.class); } } /** * A ScrollAdjuster to be used for JSpinner * component having SpinnerNumberModel model. * @see NumberSpinnerOperator */ public static class NumberScrollAdjuster implements ScrollAdjuster { SpinnerNumberModel model; double value; /** * Constructs a NumberScrollAdjuster object. * @param oper an operator to work with. * @param value a value to scroll to. */ public NumberScrollAdjuster(JSpinnerOperator oper, double value) { this.value = value; checkModel(oper, SpinnerNumberModel.class); model = (SpinnerNumberModel)oper.getModel(); } /** * Constructs a NumberScrollAdjuster object. * @param oper an operator to work with. * @param value a value to scroll to. */ public NumberScrollAdjuster(JSpinnerOperator oper, Number value) { this(oper, value.doubleValue()); } public int getScrollDirection() { if (value > model.getNumber().doubleValue()) { return(ScrollAdjuster.INCREASE_SCROLL_DIRECTION); } else if(value < model.getNumber().doubleValue()) { return(ScrollAdjuster.DECREASE_SCROLL_DIRECTION); } else { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } } public int getScrollOrientation() { return(SwingConstants.VERTICAL); } public String getDescription() { return("Spin to " + value + " value"); } } /** * A ScrollAdjuster to be used for JSpinner * component having SpinnerListModel model. * @see ListSpinnerOperator */ public static class ListScrollAdjuster implements ScrollAdjuster { SpinnerListModel model; int itemIndex; List elements; private ListScrollAdjuster(JSpinnerOperator oper) { checkModel(oper, SpinnerListModel.class); model = (SpinnerListModel)oper.getModel(); elements = model.getList(); } /** * Constructs a ListScrollAdjuster object. * @param oper an operator to work with. * @param value a value to scroll to. */ public ListScrollAdjuster(JSpinnerOperator oper, Object value) { this(oper); this.itemIndex = elements.indexOf(value); } /** * Constructs a ListScrollAdjuster object. * @param oper an operator to work with. * @param itemIndex an item index to scroll to. */ public ListScrollAdjuster(JSpinnerOperator oper, int itemIndex) { this(oper); this.itemIndex = itemIndex; } public int getScrollDirection() { int curIndex = elements.indexOf(model.getValue()); if (itemIndex > curIndex) { return(ScrollAdjuster.INCREASE_SCROLL_DIRECTION); } else if(itemIndex < curIndex) { return(ScrollAdjuster.DECREASE_SCROLL_DIRECTION); } else { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } } public int getScrollOrientation() { return(SwingConstants.VERTICAL); } public String getDescription() { return("Spin to " + Integer.toString(itemIndex) + "'th item"); } } /** * A ScrollAdjuster to be used for JSpinner * component having SpinnerDateModel model. * @see DateSpinnerOperator */ public static class DateScrollAdjuster implements ScrollAdjuster { Date date; SpinnerDateModel model; /** * Constructs a DateScrollAdjuster object. * @param oper an operator to work with. * @param date a date to scroll to. */ public DateScrollAdjuster(JSpinnerOperator oper, Date date) { this.date = date; checkModel(oper, SpinnerDateModel.class); model = (SpinnerDateModel)oper.getModel(); } public int getScrollDirection() { if (date.after (model.getDate())) { return(ScrollAdjuster.INCREASE_SCROLL_DIRECTION); } else if(date.before(model.getDate())) { return(ScrollAdjuster.DECREASE_SCROLL_DIRECTION); } else { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } } public int getScrollOrientation() { return(SwingConstants.VERTICAL); } public String getDescription() { return("Spin to " + date.toString() + " date"); } } /** * Abstract class for a scrolling of a spinner having unknown model type. * A subclass needs to override equals(Object) value * to specify a criteria of successful scrolling. */ public abstract static class ObjectScrollAdjuster implements ScrollAdjuster { SpinnerModel model; int direction; /** * Constructs a ObjectScrollAdjuster object. * @param oper an operator to work with. * @param direction a scrolling direction - one of ScrollAdjuster.*_SCROLL_DIRECTION fields. */ public ObjectScrollAdjuster(JSpinnerOperator oper, int direction) { this.direction = direction; model = oper.getModel(); } public int getScrollDirection() { if(equals(model.getValue())) { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } else if(direction == ScrollAdjuster.INCREASE_SCROLL_DIRECTION && model.getNextValue() != null || direction == ScrollAdjuster.DECREASE_SCROLL_DIRECTION && model.getPreviousValue() != null) { return(direction); } else { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } } public abstract boolean equals(Object curvalue); public int getScrollOrientation() { return(SwingConstants.VERTICAL); } } /** * Class for a scrolling of a spinner having unknown model type. * Checks spinner value for exact equality with a specified value. */ public static class ExactScrollAdjuster extends ObjectScrollAdjuster { Object obj; /** * Constructs a ExactScrollAdjuster object. * @param oper an operator to work with. * @param direction a scrolling direction - one of ScrollAdjuster.*_SCROLL_DIRECTION fields. */ public ExactScrollAdjuster(JSpinnerOperator oper, Object obj, int direction) { super(oper, direction); this.obj = obj; } public boolean equals(Object curvalue) { return(curvalue.equals(obj)); } public String getDescription() { return("Spin to " + obj.toString() + " value"); } public int getScrollOrientation() { return(SwingConstants.VERTICAL); } } /** * Class for a scrolling of a spinner having unknown model type. * Checks spinner value's toString() reprsentation to match a string pattern. */ public static class ToStringScrollAdjuster extends ObjectScrollAdjuster { String pattern; StringComparator comparator; /** * Constructs a ToStringScrollAdjuster object. * @param oper an operator to work with. * @param pattern a pattern to compare with * @param comparator specifies string comparision algorithm. * @param direction a scrolling direction - one of ScrollAdjuster.*_SCROLL_DIRECTION fields. */ public ToStringScrollAdjuster(JSpinnerOperator oper, String pattern, StringComparator comparator, int direction) { super(oper, direction); this.pattern = pattern; this.comparator = comparator; } /** * Constructs a ToStringScrollAdjuster object. * Uses StringComparator assigned to the operator. * @param oper an operator to work with. * @param pattern a pattern to compare with * @param direction a scrolling direction - one of ScrollAdjuster.*_SCROLL_DIRECTION fields. */ public ToStringScrollAdjuster(JSpinnerOperator oper, String pattern, int direction) { this(oper, pattern, oper.getComparator(), direction); } public boolean equals(Object curvalue) { return(comparator.equals(curvalue.toString(), pattern)); } public String getDescription() { return("Spin to \"" + pattern + "\" value"); } public int getScrollOrientation() { return(SwingConstants.VERTICAL); } } /** * Provides some specific functionality for JSpinner * components having SpinnerNumberModel model. * Constructor of this object is private - it cannot be received only from * another JSpinnerOperator instance. * @see #getNumberSpinner */ public class NumberSpinnerOperator extends JSpinnerOperator { private NumberSpinnerOperator(JSpinnerOperator spinner) { super((JSpinner)spinner.getSource()); copyEnvironment(spinner); checkModel(this, SpinnerNumberModel.class); } /** * Costs spinner's model to SpinnerNumberModel. * @return a spinner model. */ public SpinnerNumberModel getNumberModel() { return((SpinnerNumberModel)getModel()); } /** * Scrolls to a double value. * @param value a value to scroll to. */ public void scrollToValue(double value) { scrollTo(new NumberScrollAdjuster(this, value)); } /** * Scrolls to a number value. * @param value a value to scroll to. */ public void scrollToValue(Number value) { scrollTo(new NumberScrollAdjuster(this, value)); } } /** * Provides some specific functionality for JSpinner * components having SpinnerListModel model. * Constructor of this object is private - it cannot be received only from * another JSpinnerOperator instance. * @see #getListSpinner */ public class ListSpinnerOperator extends JSpinnerOperator { private ListSpinnerOperator(JSpinnerOperator spinner) { super((JSpinner)spinner.getSource()); copyEnvironment(spinner); checkModel(this, SpinnerListModel.class); } /** * Costs spinner's model to SpinnerListModel. * @return a spinner model. */ public SpinnerListModel getListModel() { return((SpinnerListModel)getModel()); } /** * Looks for an index of an item having toString() matching a specified pattern. * @param pattern a string pattern * @param comparator a string comparision criteria. */ public int findItem(String pattern, StringComparator comparator) { List list = getListModel().getList(); for(int i = 0; i < list.size(); i++) { if(comparator.equals(list.get(i).toString(), pattern)) { return(i); } } return(-1); } /** * Looks for an index of an item having toString() matching a specified pattern. * Uses a StringComparator assigned to the operator. * @param pattern a string pattern */ public int findItem(String pattern) { return(findItem(pattern, getComparator())); } /** * Scrolls to an item having specified instance. * @param index an index to scroll to. */ public void scrollToIndex(int index) { scrollTo(new ListScrollAdjuster(this, index)); } /** * Scrolls to getValue().toString() match a specified pattern. * @param pattern a string pattern * @param comparator a string comparision criteria. */ public void scrollToString(String pattern, StringComparator comparator) { int index = findItem(pattern, comparator); if(index != -1) { scrollToIndex(index); } else { throw(new JemmyException("No \"" + pattern + "\" item in JSpinner", getSource())); } } /** * Scrolls to getValue().toString() match a specified pattern. * Uses a StringComparator assigned to the operator. * @param pattern a string pattern */ public void scrollToString(String pattern) { scrollToString(pattern, getComparator()); } } /** * Provides some specific functionality for JSpinner * components having SpinnerDateModel model. * Constructor of this object is private - it cannot be received only from * another JSpinnerOperator instance. * @see #getDateSpinner */ public class DateSpinnerOperator extends JSpinnerOperator { private DateSpinnerOperator(JSpinnerOperator spinner) { super((JSpinner)spinner.getSource()); copyEnvironment(spinner); checkModel(this, SpinnerDateModel.class); } /** * Costs spinner's model to SpinnerDateModel. * @return a spinner model. */ public SpinnerDateModel getDateModel() { return((SpinnerDateModel)getModel()); } /** * Scrolls to a date. * @param date a date to scroll to. */ public void scrollToDate(Date date) { scrollTo(new DateScrollAdjuster(this, date)); } } /** * Exception is thown whenever spinner model is threated wrong. */ public static class SpinnerModelException extends JemmyException { /** * Constructs a SpinnerModelException object. * @param message error message. * @param comp a spinner which model cased the exception. */ public SpinnerModelException(String message, Component comp) { super(message, comp); } } } Jemmy2/src/org/netbeans/jemmy/operators/JTableHeaderOperator.java0000644000175000017500000003627511245712237024153 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Point; import java.awt.Rectangle; import javax.swing.JTable; import javax.swing.event.ChangeEvent; import javax.swing.event.ListSelectionEvent; import javax.swing.event.TableColumnModelEvent; import javax.swing.plaf.TableHeaderUI; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.OrderedListDriver; /** * ComponentOperator.BeforeDragTimeout - time to sleep before column moving
* ComponentOperator.AfterDragTimeout - time to sleep after column moving
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
. * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JTableHeaderOperator extends JComponentOperator implements Outputable, Timeoutable { private TestOut output; private Timeouts timeouts; private OrderedListDriver driver; /** * Constructor. * @param b a component */ public JTableHeaderOperator(JTableHeader b) { super(b); driver = DriverManager.getOrderedListDriver(getClass()); } /** * Constructs a JTableHeaderOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JTableHeaderOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JTableHeader)cont. waitSubComponent(new JTableHeaderFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JTableHeaderOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JTableHeaderOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructs a JTableHeaderOperator object. * @param cont a container * @param index an index between appropriate ones. */ public JTableHeaderOperator(ContainerOperator cont, int index) { this((JTableHeader) waitComponent(cont, new JTableHeaderFinder(ComponentSearcher. getTrueChooser("Any JTableHeader")), index)); copyEnvironment(cont); } /** * Constructs a JTableHeaderOperator object. * @param cont a container */ public JTableHeaderOperator(ContainerOperator cont) { this(cont, 0); } public void setTimeouts(Timeouts times) { this.timeouts = times; super.setTimeouts(timeouts); } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output); } public TestOut getOutput() { return(output); } /** * Selects a column. * @param columnIndex an index of a column to select. */ public void selectColumn(int columnIndex) { driver.selectItem(this, columnIndex); } /** * Selects some columns. * @param columnIndices indices of columns to select. */ public void selectColumns(int[] columnIndices) { driver.selectItems(this, columnIndices); } /** * Moves a column to a different location. * @param moveColumn an original column index. * @param moveTo a desctination column index. */ public void moveColumn(int moveColumn, int moveTo) { driver.moveItem(this, moveColumn, moveTo); } /** * Return a point to click on column header. * @param columnIndex an index of a column to click on. * @return the point to click. */ public Point getPointToClick(int columnIndex) { Rectangle rect = getHeaderRect(columnIndex); return(new Point(rect.x + rect.width/2, rect.y + rect.height/2)); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (OrderedListDriver)DriverManager. getDriver(DriverManager.ORDEREDLIST_DRIVER_ID, getClass(), anotherOperator.getProperties()); } //////////////////////////////////////////////////////// //Mapping // /**Maps JTableHeader.setTable(JTable) through queue*/ public void setTable(final JTable jTable) { runMapping(new MapVoidAction("setTable") { public void map() { ((JTableHeader)getSource()).setTable(jTable); }});} /**Maps JTableHeader.getTable() through queue*/ public JTable getTable() { return((JTable)runMapping(new MapAction("getTable") { public Object map() { return(((JTableHeader)getSource()).getTable()); }}));} /**Maps JTableHeader.setReorderingAllowed(boolean) through queue*/ public void setReorderingAllowed(final boolean b) { runMapping(new MapVoidAction("setReorderingAllowed") { public void map() { ((JTableHeader)getSource()).setReorderingAllowed(b); }});} /**Maps JTableHeader.getReorderingAllowed() through queue*/ public boolean getReorderingAllowed() { return(runMapping(new MapBooleanAction("getReorderingAllowed") { public boolean map() { return(((JTableHeader)getSource()).getReorderingAllowed()); }}));} /**Maps JTableHeader.setResizingAllowed(boolean) through queue*/ public void setResizingAllowed(final boolean b) { runMapping(new MapVoidAction("setResizingAllowed") { public void map() { ((JTableHeader)getSource()).setResizingAllowed(b); }});} /**Maps JTableHeader.getResizingAllowed() through queue*/ public boolean getResizingAllowed() { return(runMapping(new MapBooleanAction("getResizingAllowed") { public boolean map() { return(((JTableHeader)getSource()).getResizingAllowed()); }}));} /**Maps JTableHeader.getDraggedColumn() through queue*/ public TableColumn getDraggedColumn() { return((TableColumn)runMapping(new MapAction("getDraggedColumn") { public Object map() { return(((JTableHeader)getSource()).getDraggedColumn()); }}));} /**Maps JTableHeader.getDraggedDistance() through queue*/ public int getDraggedDistance() { return(runMapping(new MapIntegerAction("getDraggedDistance") { public int map() { return(((JTableHeader)getSource()).getDraggedDistance()); }}));} /**Maps JTableHeader.getResizingColumn() through queue*/ public TableColumn getResizingColumn() { return((TableColumn)runMapping(new MapAction("getResizingColumn") { public Object map() { return(((JTableHeader)getSource()).getResizingColumn()); }}));} /**Maps JTableHeader.setUpdateTableInRealTime(boolean) through queue*/ public void setUpdateTableInRealTime(final boolean b) { runMapping(new MapVoidAction("setUpdateTableInRealTime") { public void map() { ((JTableHeader)getSource()).setUpdateTableInRealTime(b); }});} /**Maps JTableHeader.getUpdateTableInRealTime() through queue*/ public boolean getUpdateTableInRealTime() { return(runMapping(new MapBooleanAction("getUpdateTableInRealTime") { public boolean map() { return(((JTableHeader)getSource()).getUpdateTableInRealTime()); }}));} /**Maps JTableHeader.setDefaultRenderer(TableCellRenderer) through queue*/ public void setDefaultRenderer(final TableCellRenderer tableCellRenderer) { runMapping(new MapVoidAction("setDefaultRenderer") { public void map() { ((JTableHeader)getSource()).setDefaultRenderer(tableCellRenderer); }});} /**Maps JTableHeader.getDefaultRenderer() through queue*/ public TableCellRenderer getDefaultRenderer() { return((TableCellRenderer)runMapping(new MapAction("getDefaultRenderer") { public Object map() { return(((JTableHeader)getSource()).getDefaultRenderer()); }}));} /**Maps JTableHeader.columnAtPoint(Point) through queue*/ public int columnAtPoint(final Point point) { return(runMapping(new MapIntegerAction("columnAtPoint") { public int map() { return(((JTableHeader)getSource()).columnAtPoint(point)); }}));} /**Maps JTableHeader.getHeaderRect(int) through queue*/ public Rectangle getHeaderRect(final int i) { return((Rectangle)runMapping(new MapAction("getHeaderRect") { public Object map() { return(((JTableHeader)getSource()).getHeaderRect(i)); }}));} /**Maps JTableHeader.getUI() through queue*/ public TableHeaderUI getUI() { return((TableHeaderUI)runMapping(new MapAction("getUI") { public Object map() { return(((JTableHeader)getSource()).getUI()); }}));} /**Maps JTableHeader.setUI(TableHeaderUI) through queue*/ public void setUI(final TableHeaderUI tableHeaderUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JTableHeader)getSource()).setUI(tableHeaderUI); }});} /**Maps JTableHeader.setColumnModel(TableColumnModel) through queue*/ public void setColumnModel(final TableColumnModel tableColumnModel) { runMapping(new MapVoidAction("setColumnModel") { public void map() { ((JTableHeader)getSource()).setColumnModel(tableColumnModel); }});} /**Maps JTableHeader.getColumnModel() through queue*/ public TableColumnModel getColumnModel() { return((TableColumnModel)runMapping(new MapAction("getColumnModel") { public Object map() { return(((JTableHeader)getSource()).getColumnModel()); }}));} /**Maps JTableHeader.columnAdded(TableColumnModelEvent) through queue*/ public void columnAdded(final TableColumnModelEvent tableColumnModelEvent) { runMapping(new MapVoidAction("columnAdded") { public void map() { ((JTableHeader)getSource()).columnAdded(tableColumnModelEvent); }});} /**Maps JTableHeader.columnRemoved(TableColumnModelEvent) through queue*/ public void columnRemoved(final TableColumnModelEvent tableColumnModelEvent) { runMapping(new MapVoidAction("columnRemoved") { public void map() { ((JTableHeader)getSource()).columnRemoved(tableColumnModelEvent); }});} /**Maps JTableHeader.columnMoved(TableColumnModelEvent) through queue*/ public void columnMoved(final TableColumnModelEvent tableColumnModelEvent) { runMapping(new MapVoidAction("columnMoved") { public void map() { ((JTableHeader)getSource()).columnMoved(tableColumnModelEvent); }});} /**Maps JTableHeader.columnMarginChanged(ChangeEvent) through queue*/ public void columnMarginChanged(final ChangeEvent changeEvent) { runMapping(new MapVoidAction("columnMarginChanged") { public void map() { ((JTableHeader)getSource()).columnMarginChanged(changeEvent); }});} /**Maps JTableHeader.columnSelectionChanged(ListSelectionEvent) through queue*/ public void columnSelectionChanged(final ListSelectionEvent listSelectionEvent) { runMapping(new MapVoidAction("columnSelectionChanged") { public void map() { ((JTableHeader)getSource()).columnSelectionChanged(listSelectionEvent); }});} /**Maps JTableHeader.resizeAndRepaint() through queue*/ public void resizeAndRepaint() { runMapping(new MapVoidAction("resizeAndRepaint") { public void map() { ((JTableHeader)getSource()).resizeAndRepaint(); }});} /**Maps JTableHeader.setDraggedColumn(TableColumn) through queue*/ public void setDraggedColumn(final TableColumn tableColumn) { runMapping(new MapVoidAction("setDraggedColumn") { public void map() { ((JTableHeader)getSource()).setDraggedColumn(tableColumn); }});} /**Maps JTableHeader.setDraggedDistance(int) through queue*/ public void setDraggedDistance(final int i) { runMapping(new MapVoidAction("setDraggedDistance") { public void map() { ((JTableHeader)getSource()).setDraggedDistance(i); }});} /**Maps JTableHeader.setResizingColumn(TableColumn) through queue*/ public void setResizingColumn(final TableColumn tableColumn) { runMapping(new MapVoidAction("setResizingColumn") { public void map() { ((JTableHeader)getSource()).setResizingColumn(tableColumn); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Checks component type. */ public static class JTableHeaderFinder implements ComponentChooser { ComponentChooser subFinder; /** * Constructs JTableHeaderFinder. * @param sf other searching criteria. */ public JTableHeaderFinder(ComponentChooser sf) { subFinder = sf; } public boolean checkComponent(Component comp) { if(comp instanceof JTableHeader) { return(subFinder.checkComponent(comp)); } return(false); } public String getDescription() { return(subFinder.getDescription()); } } } Jemmy2/src/org/netbeans/jemmy/operators/JTabbedPaneOperator.java0000644000175000017500000010071411245712237023766 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Rectangle; import java.util.Hashtable; import javax.swing.Icon; import javax.swing.JTabbedPane; import javax.swing.SingleSelectionModel; import javax.swing.event.ChangeListener; import javax.swing.plaf.TabbedPaneUI; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.JemmyInputException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.ListDriver; /** *

Timeouts used:
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JTabbedPaneOperator extends JComponentOperator implements Outputable { /** * Identifier for a "selected page" property. * @see #getDump */ public static final String SELECTED_PAGE_DPROP = "Selected"; /** * Identifier for a "page" properties. * @see #getDump */ public static final String PAGE_PREFIX_DPROP = "Page"; private TestOut output; private ListDriver driver; /** * Constructor. * @param b a component */ public JTabbedPaneOperator(JTabbedPane b) { super(b); driver = DriverManager.getListDriver(getClass()); } /** * Constructs a JTabbedPaneOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JTabbedPaneOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JTabbedPane)cont. waitSubComponent(new JTabbedPaneFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JTabbedPaneOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JTabbedPaneOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component by tab title first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Tab title. * @param tabIndex a page index to check. if equal to -1, selected page is checked. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTabbedPaneOperator(ContainerOperator cont, String text, int tabIndex, int index) { this((JTabbedPane)waitComponent(cont, new JTabbedPaneByItemFinder(text, tabIndex, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits component by activetab title first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Title of tab which is currently selected. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTabbedPaneOperator(ContainerOperator cont, String text, int index) { this(cont, text, -1, index); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Title of tab which is currently selected. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTabbedPaneOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JTabbedPaneOperator(ContainerOperator cont, int index) { this((JTabbedPane) waitComponent(cont, new JTabbedPaneFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JTabbedPaneOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JTabbedPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JTabbedPane instance or null if component was not found. */ public static JTabbedPane findJTabbedPane(Container cont, ComponentChooser chooser, int index) { return((JTabbedPane)findComponent(cont, new JTabbedPaneFinder(chooser), index)); } /** * Searches 0'th JTabbedPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JTabbedPane instance or null if component was not found. */ public static JTabbedPane findJTabbedPane(Container cont, ComponentChooser chooser) { return(findJTabbedPane(cont, chooser, 0)); } /** * Searches JTabbedPane by tab title. * @param cont Container to search component in. * @param text Tooltip text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param itemIndex Tab index. if -1 selected one is checked. * @param index Ordinal component index. * @return JTabbedPane instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTabbedPane findJTabbedPane(Container cont, String text, boolean ce, boolean ccs, int itemIndex, int index) { return(findJTabbedPane(cont, new JTabbedPaneByItemFinder(text, itemIndex, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches JTabbedPane by tab title. * @param cont Container to search component in. * @param text Tooltip text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param itemIndex Tab index. if -1 selected one is checked. * @return JTabbedPane instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTabbedPane findJTabbedPane(Container cont, String text, boolean ce, boolean ccs, int itemIndex) { return(findJTabbedPane(cont, text, ce, ccs, itemIndex, 0)); } /** * Searches JTabbedPane object which component lies on. * @param comp Component to find JTabbedPane under. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JTabbedPane instance or null if component was not found. */ public static JTabbedPane findJTabbedPaneUnder(Component comp, ComponentChooser chooser) { return((JTabbedPane)findContainerUnder(comp, new JTabbedPaneFinder(chooser))); } /** * Searches JTabbedPane object which component lies on. * @param comp Component to find JTabbedPane under. * @return JTabbedPane instance or null if component was not found. */ public static JTabbedPane findJTabbedPaneUnder(Component comp) { return(findJTabbedPaneUnder(comp, new JTabbedPaneFinder())); } /** * Waits JTabbedPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JTabbedPane instance. * @throws TimeoutExpiredException */ public static JTabbedPane waitJTabbedPane(Container cont, ComponentChooser chooser, int index) { return((JTabbedPane)waitComponent(cont, new JTabbedPaneFinder(chooser), index)); } /** * Waits 0'th JTabbedPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JTabbedPane instance. * @throws TimeoutExpiredException */ public static JTabbedPane waitJTabbedPane(Container cont, ComponentChooser chooser) { return(waitJTabbedPane(cont, chooser, 0)); } /** * Waits JTabbedPane by tab title. * @param cont Container to search component in. * @param text Tooltip text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param itemIndex Tab index. if -1 selected one is checked. * @param index Ordinal component index. * @return JTabbedPane instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JTabbedPane waitJTabbedPane(Container cont, String text, boolean ce, boolean ccs, int itemIndex, int index) { return(waitJTabbedPane(cont, new JTabbedPaneByItemFinder(text, itemIndex, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits JTabbedPane by tab title. * @param cont Container to search component in. * @param text Tooltip text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param itemIndex Tab index. if -1 selected one is checked. * @return JTabbedPane instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JTabbedPane waitJTabbedPane(Container cont, String text, boolean ce, boolean ccs, int itemIndex) { return(waitJTabbedPane(cont, text, ce, ccs, itemIndex, 0)); } public void setOutput(TestOut output) { super.setOutput(output.createErrorOutput()); this.output = output; } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (ListDriver)DriverManager. getDriver(DriverManager.LIST_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Searches tab index by tab title. * @param chooser page searching criteria * @return a page index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @deprecated Use findPage(String) or findPage(String, StringComparator) */ public int findPage(TabPageChooser chooser) { for(int i = 0; i < getTabCount(); i++) { if(chooser.checkPage(this, i)) { return(i); } } return(-1); } /** * Searches tab index by tab title. * @param title a page title. * @param comparator a string comparision algorithm * @return a page index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @deprecated Use findPage(String) or findPage(String, StringComparator) */ public int findPage(String title, StringComparator comparator) { return(findPage(new BySubStringTabPageChooser(title, comparator))); } /** * Searches tab index by tab title. * isCaptionEqual method is used to compare page title with * match. * @param title a page title. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return a page index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @deprecated Use findPage(String) or findPage(String, StringComparator) */ public int findPage(String title, boolean ce, boolean ccs) { return(findPage(title, new DefaultStringComparator(ce, ccs))); } /** * Searches tab index by tab title. * isCaptionEqual method is used to compare page title with * match. * Uses StringComparator assigned to this object. * @param title a page title. * @return a page index. */ public int findPage(String title) { return(findPage(title, getComparator())); } /** * Selects tab. * @param index a page ordinal index. * @return a root corresponding to the page. */ public Component selectPage(int index) { output.printLine("Selecting " + index + "'th page in tabbed pane\n :" + toStringSource()); makeComponentVisible(); driver.selectItem(this, index); if(getVerification()) { waitSelected(index); } return(getComponentAt(index)); } /** * Selects tab. * @param chooser page searching criteria * @return a root corresponding to the page. */ public Component selectPage(TabPageChooser chooser) { output.printLine("Selecting \"" + chooser.getDescription() + "\" page in tabbed pane\n :" + toStringSource()); return(selectPage(waitPage(chooser))); } /** * Selects tab. * @param title a page title. * @param comparator a string comparision algorithm * @return a root corresponding to the page. */ public Component selectPage(String title, StringComparator comparator) { return(selectPage(new BySubStringTabPageChooser(title, comparator))); } /** * Selects tab by tab title. * @param title a page title. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @deprecated Use selectPage(String) or selectPage(String, StringComparator) * @return a root corresponding to the page. */ public Component selectPage(String title, boolean ce, boolean ccs) { return(selectPage(title, new DefaultStringComparator(ce, ccs))); } /** * Selects tab by tab title. * Uses StringComparator assigned to this object. * @param title a page title. * @return a root corresponding to the page. */ public Component selectPage(String title) { return(selectPage(title, getComparator())); } /** * Wait for a page to exist. * @param chooser page searching criteria * @return a page index. */ public int waitPage(final TabPageChooser chooser) { waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(findPage(chooser) > -1); } public String getDescription() { return("Tabbed with " + chooser.getDescription() + " page."); } }); return(findPage(chooser)); } /** * Wait for a page to exist. * @param title a page title. * @param comparator a string comparision algorithm * @return a page index. */ public int waitPage(String title, StringComparator comparator) { return(waitPage(new BySubStringTabPageChooser(title, comparator))); } /** * Wait for a page to exist. * @param title a page title. * @return a page index. */ public int waitPage(String title) { return(waitPage(title, getComparator())); } /** * Waits for a page to be selected. * @param pageIndex an index of a page to be selected. */ public void waitSelected(final int pageIndex) { getOutput().printLine("Wait " + Integer.toString(pageIndex) + "'th page to be " + " selected in component \n : "+ toStringSource()); getOutput().printGolden("Wait " + Integer.toString(pageIndex) + "'th page to be " + " selected"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(getSelectedIndex() == pageIndex); } public String getDescription() { return(Integer.toString(pageIndex) + "'th page has been selected"); } }); } /** * Waits for a page to be selected. * @param pageTitle a title of a page to be selected. */ public void waitSelected(final String pageTitle) { waitSelected(findPage(pageTitle)); } public Hashtable getDump() { Hashtable result = super.getDump(); if(((JTabbedPane)getSource()).getSelectedIndex() != -1) { result.put(SELECTED_PAGE_DPROP, ((JTabbedPane)getSource()). getTitleAt(((JTabbedPane)getSource()).getSelectedIndex())); } String[] pages = new String[((JTabbedPane)getSource()).getTabCount()]; for(int i = 0; i < ((JTabbedPane)getSource()).getTabCount(); i++) { pages[i] = ((JTabbedPane)getSource()).getTitleAt(i); } addToDump(result, PAGE_PREFIX_DPROP, pages); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JTabbedPane.addChangeListener(ChangeListener) through queue*/ public void addChangeListener(final ChangeListener changeListener) { runMapping(new MapVoidAction("addChangeListener") { public void map() { ((JTabbedPane)getSource()).addChangeListener(changeListener); }});} /**Maps JTabbedPane.addTab(String, Component) through queue*/ public void addTab(final String string, final Component component) { runMapping(new MapVoidAction("addTab") { public void map() { ((JTabbedPane)getSource()).addTab(string, component); }});} /**Maps JTabbedPane.addTab(String, Icon, Component) through queue*/ public void addTab(final String string, final Icon icon, final Component component) { runMapping(new MapVoidAction("addTab") { public void map() { ((JTabbedPane)getSource()).addTab(string, icon, component); }});} /**Maps JTabbedPane.addTab(String, Icon, Component, String) through queue*/ public void addTab(final String string, final Icon icon, final Component component, final String string1) { runMapping(new MapVoidAction("addTab") { public void map() { ((JTabbedPane)getSource()).addTab(string, icon, component, string1); }});} /**Maps JTabbedPane.getBackgroundAt(int) through queue*/ public Color getBackgroundAt(final int i) { return((Color)runMapping(new MapAction("getBackgroundAt") { public Object map() { return(((JTabbedPane)getSource()).getBackgroundAt(i)); }}));} /**Maps JTabbedPane.getBoundsAt(int) through queue*/ public Rectangle getBoundsAt(final int i) { return((Rectangle)runMapping(new MapAction("getBoundsAt") { public Object map() { return(((JTabbedPane)getSource()).getBoundsAt(i)); }}));} /**Maps JTabbedPane.getComponentAt(int) through queue*/ public Component getComponentAt(final int i) { return((Component)runMapping(new MapAction("getComponentAt") { public Object map() { return(((JTabbedPane)getSource()).getComponentAt(i)); }}));} /**Maps JTabbedPane.getDisabledIconAt(int) through queue*/ public Icon getDisabledIconAt(final int i) { return((Icon)runMapping(new MapAction("getDisabledIconAt") { public Object map() { return(((JTabbedPane)getSource()).getDisabledIconAt(i)); }}));} /**Maps JTabbedPane.getForegroundAt(int) through queue*/ public Color getForegroundAt(final int i) { return((Color)runMapping(new MapAction("getForegroundAt") { public Object map() { return(((JTabbedPane)getSource()).getForegroundAt(i)); }}));} /**Maps JTabbedPane.getIconAt(int) through queue*/ public Icon getIconAt(final int i) { return((Icon)runMapping(new MapAction("getIconAt") { public Object map() { return(((JTabbedPane)getSource()).getIconAt(i)); }}));} /**Maps JTabbedPane.getModel() through queue*/ public SingleSelectionModel getModel() { return((SingleSelectionModel)runMapping(new MapAction("getModel") { public Object map() { return(((JTabbedPane)getSource()).getModel()); }}));} /**Maps JTabbedPane.getSelectedComponent() through queue*/ public Component getSelectedComponent() { return((Component)runMapping(new MapAction("getSelectedComponent") { public Object map() { return(((JTabbedPane)getSource()).getSelectedComponent()); }}));} /**Maps JTabbedPane.getSelectedIndex() through queue*/ public int getSelectedIndex() { return(runMapping(new MapIntegerAction("getSelectedIndex") { public int map() { return(((JTabbedPane)getSource()).getSelectedIndex()); }}));} /**Maps JTabbedPane.getTabCount() through queue*/ public int getTabCount() { return(runMapping(new MapIntegerAction("getTabCount") { public int map() { return(((JTabbedPane)getSource()).getTabCount()); }}));} /**Maps JTabbedPane.getTabPlacement() through queue*/ public int getTabPlacement() { return(runMapping(new MapIntegerAction("getTabPlacement") { public int map() { return(((JTabbedPane)getSource()).getTabPlacement()); }}));} /**Maps JTabbedPane.getTabRunCount() through queue*/ public int getTabRunCount() { return(runMapping(new MapIntegerAction("getTabRunCount") { public int map() { return(((JTabbedPane)getSource()).getTabRunCount()); }}));} /**Maps JTabbedPane.getTitleAt(int) through queue*/ public String getTitleAt(final int i) { return((String)runMapping(new MapAction("getTitleAt") { public Object map() { return(((JTabbedPane)getSource()).getTitleAt(i)); }}));} /**Maps JTabbedPane.getUI() through queue*/ public TabbedPaneUI getUI() { return((TabbedPaneUI)runMapping(new MapAction("getUI") { public Object map() { return(((JTabbedPane)getSource()).getUI()); }}));} /**Maps JTabbedPane.indexOfComponent(Component) through queue*/ public int indexOfComponent(final Component component) { return(runMapping(new MapIntegerAction("indexOfComponent") { public int map() { return(((JTabbedPane)getSource()).indexOfComponent(component)); }}));} /**Maps JTabbedPane.indexOfTab(String) through queue*/ public int indexOfTab(final String string) { return(runMapping(new MapIntegerAction("indexOfTab") { public int map() { return(((JTabbedPane)getSource()).indexOfTab(string)); }}));} /**Maps JTabbedPane.indexOfTab(Icon) through queue*/ public int indexOfTab(final Icon icon) { return(runMapping(new MapIntegerAction("indexOfTab") { public int map() { return(((JTabbedPane)getSource()).indexOfTab(icon)); }}));} /**Maps JTabbedPane.insertTab(String, Icon, Component, String, int) through queue*/ public void insertTab(final String string, final Icon icon, final Component component, final String string1, final int i) { runMapping(new MapVoidAction("insertTab") { public void map() { ((JTabbedPane)getSource()).insertTab(string, icon, component, string1, i); }});} /**Maps JTabbedPane.isEnabledAt(int) through queue*/ public boolean isEnabledAt(final int i) { return(runMapping(new MapBooleanAction("isEnabledAt") { public boolean map() { return(((JTabbedPane)getSource()).isEnabledAt(i)); }}));} /**Maps JTabbedPane.removeChangeListener(ChangeListener) through queue*/ public void removeChangeListener(final ChangeListener changeListener) { runMapping(new MapVoidAction("removeChangeListener") { public void map() { ((JTabbedPane)getSource()).removeChangeListener(changeListener); }});} /**Maps JTabbedPane.removeTabAt(int) through queue*/ public void removeTabAt(final int i) { runMapping(new MapVoidAction("removeTabAt") { public void map() { ((JTabbedPane)getSource()).removeTabAt(i); }});} /**Maps JTabbedPane.setBackgroundAt(int, Color) through queue*/ public void setBackgroundAt(final int i, final Color color) { runMapping(new MapVoidAction("setBackgroundAt") { public void map() { ((JTabbedPane)getSource()).setBackgroundAt(i, color); }});} /**Maps JTabbedPane.setComponentAt(int, Component) through queue*/ public void setComponentAt(final int i, final Component component) { runMapping(new MapVoidAction("setComponentAt") { public void map() { ((JTabbedPane)getSource()).setComponentAt(i, component); }});} /**Maps JTabbedPane.setDisabledIconAt(int, Icon) through queue*/ public void setDisabledIconAt(final int i, final Icon icon) { runMapping(new MapVoidAction("setDisabledIconAt") { public void map() { ((JTabbedPane)getSource()).setDisabledIconAt(i, icon); }});} /**Maps JTabbedPane.setEnabledAt(int, boolean) through queue*/ public void setEnabledAt(final int i, final boolean b) { runMapping(new MapVoidAction("setEnabledAt") { public void map() { ((JTabbedPane)getSource()).setEnabledAt(i, b); }});} /**Maps JTabbedPane.setForegroundAt(int, Color) through queue*/ public void setForegroundAt(final int i, final Color color) { runMapping(new MapVoidAction("setForegroundAt") { public void map() { ((JTabbedPane)getSource()).setForegroundAt(i, color); }});} /**Maps JTabbedPane.setIconAt(int, Icon) through queue*/ public void setIconAt(final int i, final Icon icon) { runMapping(new MapVoidAction("setIconAt") { public void map() { ((JTabbedPane)getSource()).setIconAt(i, icon); }});} /**Maps JTabbedPane.setModel(SingleSelectionModel) through queue*/ public void setModel(final SingleSelectionModel singleSelectionModel) { runMapping(new MapVoidAction("setModel") { public void map() { ((JTabbedPane)getSource()).setModel(singleSelectionModel); }});} /**Maps JTabbedPane.setSelectedComponent(Component) through queue*/ public void setSelectedComponent(final Component component) { runMapping(new MapVoidAction("setSelectedComponent") { public void map() { ((JTabbedPane)getSource()).setSelectedComponent(component); }});} /**Maps JTabbedPane.setSelectedIndex(int) through queue*/ public void setSelectedIndex(final int i) { runMapping(new MapVoidAction("setSelectedIndex") { public void map() { ((JTabbedPane)getSource()).setSelectedIndex(i); }});} /**Maps JTabbedPane.setTabPlacement(int) through queue*/ public void setTabPlacement(final int i) { runMapping(new MapVoidAction("setTabPlacement") { public void map() { ((JTabbedPane)getSource()).setTabPlacement(i); }});} /**Maps JTabbedPane.setTitleAt(int, String) through queue*/ public void setTitleAt(final int i, final String string) { runMapping(new MapVoidAction("setTitleAt") { public void map() { ((JTabbedPane)getSource()).setTitleAt(i, string); }});} /**Maps JTabbedPane.setUI(TabbedPaneUI) through queue*/ public void setUI(final TabbedPaneUI tabbedPaneUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JTabbedPane)getSource()).setUI(tabbedPaneUI); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Specifies criteria for a tab page searching. */ public interface TabPageChooser { /** * Should be true if a page is good. * @param oper Operator used to search item. * @param index Index of a page be checked. * @return true if a page fits the criteria. */ public boolean checkPage(JTabbedPaneOperator oper, int index); /** * Page description. * @return a description. */ public String getDescription(); } /** * Exception is thrown if a nonexistent page is trying to be selected. */ public class NoSuchPageException extends JemmyInputException { /** * Constructor. * @param item nonexistent page title. */ public NoSuchPageException(String item) { super("No such page as \"" + item + "\"", getSource()); } } /** * Allows to find component by page title. */ public static class JTabbedPaneByItemFinder implements ComponentChooser { String title; int itemIndex; StringComparator comparator; /** * Constructs JTabbedPaneByItemFinder. * @param lb a text pattern * @param ii page index to check. If equal to -1, selected page is checked. * @param comparator specifies string comparision algorithm. */ public JTabbedPaneByItemFinder(String lb, int ii, StringComparator comparator) { title = lb; itemIndex = ii; this.comparator = comparator; } /** * Constructs JTabbedPaneByItemFinder. * @param lb a text pattern * @param ii page index to check. If equal to -1, selected page is checked. */ public JTabbedPaneByItemFinder(String lb, int ii) { this(lb, ii, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JTabbedPane) { if(title == null) { return(true); } JTabbedPaneOperator tpo = new JTabbedPaneOperator((JTabbedPane)comp); if(tpo.getTabCount() > itemIndex) { int ii = itemIndex; if(ii == -1) { ii = tpo.getSelectedIndex(); if(ii == -1) { return(false); } } return(comparator.equals(tpo.getTitleAt(ii), title)); } } return(false); } public String getDescription() { return("JTabbedPane with text \"" + title + "\" in " + (new Integer(itemIndex)).toString() + "'th item"); } } /** * Checks component type. */ public static class JTabbedPaneFinder extends Finder { /** * Constructs JTabbedPaneFinder. * @param sf other searching criteria. */ public JTabbedPaneFinder(ComponentChooser sf) { super(JTabbedPane.class, sf); } /** * Constructs JTabbedPaneFinder. */ public JTabbedPaneFinder() { super(JTabbedPane.class); } } private class BySubStringTabPageChooser implements TabPageChooser { String title; StringComparator comparator; public BySubStringTabPageChooser(String title, StringComparator comparator) { this.title = title; this.comparator = comparator; } public boolean checkPage(JTabbedPaneOperator oper, int index) { return(comparator.equals(oper.getTitleAt(index), title)); } public String getDescription() { return("Page having \"" + title + "\" title."); } } } Jemmy2/src/org/netbeans/jemmy/operators/JEditorPaneOperator.java0000644000175000017500000003711711245712347024043 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Container; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Hashtable; import javax.swing.JEditorPane; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.EditorKit; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.TimeoutExpiredException; /** * Class provides basic functions to operate with JEditorPane * (selection, typing, deleting) * *

Timeouts used:
* JTextComponentOperator.PushKeyTimeout - time between key pressing and releasing during text typing
* JTextComponentOperator.BetweenKeysTimeout - time to sleep between two chars typing
* JTextComponentOperator.ChangeCaretPositionTimeout - maximum time to change caret position
* JTextComponentOperator.TypeTextTimeout - maximum time to type text
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.WaitFocusTimeout - time to wait component focus
* JScrollBarOperator.OneScrollClickTimeout - time for one scroll click
* JScrollBarOperator.WholeScrollTimeout - time for the whole scrolling
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class JEditorPaneOperator extends JTextComponentOperator { /** * Identifier for a "content type" property. * @see #getDump */ public static final String CONTENT_TYPE_DPROP = "Content type"; /** * Constructor. * @param b a component */ public JEditorPaneOperator(JEditorPane b) { super(b); } /** * Constructs a JEditorPaneOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JEditorPaneOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JEditorPane)cont. waitSubComponent(new JEditorPaneFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JEditorPaneOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JEditorPaneOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JEditorPaneOperator(ContainerOperator cont, String text, int index) { this((JEditorPane) waitComponent(cont, new JEditorPaneFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, cont.getComparator())), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JEditorPaneOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JEditorPaneOperator(ContainerOperator cont, int index) { this((JEditorPane) waitComponent(cont, new JEditorPaneFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JEditorPaneOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JEditorPane in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JEditorPane instance or null if component was not found. */ public static JEditorPane findJEditorPane(Container cont, ComponentChooser chooser, int index) { return((JEditorPane)findJTextComponent(cont, new JEditorPaneFinder(chooser), index)); } /** * Searches JEditorPane in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JEditorPane instance or null if component was not found. */ public static JEditorPane findJEditorPane(Container cont, ComponentChooser chooser) { return(findJEditorPane(cont, chooser, 0)); } /** * Searches JEditorPane by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JEditorPane instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JEditorPane findJEditorPane(Container cont, String text, boolean ce, boolean ccs, int index) { return(findJEditorPane(cont, new JEditorPaneFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Searches JEditorPane by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JEditorPane instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JEditorPane findJEditorPane(Container cont, String text, boolean ce, boolean ccs) { return(findJEditorPane(cont, text, ce, ccs, 0)); } /** * Waits JEditorPane in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JEditorPane instance. * @throws TimeoutExpiredException */ public static JEditorPane waitJEditorPane(Container cont, ComponentChooser chooser, int index) { return((JEditorPane)waitJTextComponent(cont, new JEditorPaneFinder(chooser), index)); } /** * Waits JEditorPane in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JEditorPane instance. * @throws TimeoutExpiredException */ public static JEditorPane waitJEditorPane(Container cont, ComponentChooser chooser) { return(waitJEditorPane(cont, chooser, 0)); } /** * Waits JEditorPane by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JEditorPane instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JEditorPane waitJEditorPane(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitJEditorPane(cont, new JEditorPaneFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Waits JEditorPane by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JEditorPane instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JEditorPane waitJEditorPane(Container cont, String text, boolean ce, boolean ccs) { return(waitJEditorPane(cont, text, ce, ccs, 0)); } /** * Notifies whether "PageUp" and "PageDown" should be used * to change caret position. If can be useful if text takes * some pages. * @param yesOrNo whether to use "PageUp" and "PageDown" * @deprecated vlue set by this method is not used anymore: * all navigating is performed by TextDriver. */ public void usePageNavigationKeys(boolean yesOrNo) { } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); result.put(CONTENT_TYPE_DPROP, ((JEditorPane)getSource()).getContentType()); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JEditorPane.addHyperlinkListener(HyperlinkListener) through queue*/ public void addHyperlinkListener(final HyperlinkListener hyperlinkListener) { runMapping(new MapVoidAction("addHyperlinkListener") { public void map() { ((JEditorPane)getSource()).addHyperlinkListener(hyperlinkListener); }});} /**Maps JEditorPane.fireHyperlinkUpdate(HyperlinkEvent) through queue*/ public void fireHyperlinkUpdate(final HyperlinkEvent hyperlinkEvent) { runMapping(new MapVoidAction("fireHyperlinkUpdate") { public void map() { ((JEditorPane)getSource()).fireHyperlinkUpdate(hyperlinkEvent); }});} /**Maps JEditorPane.getContentType() through queue*/ public String getContentType() { return((String)runMapping(new MapAction("getContentType") { public Object map() { return(((JEditorPane)getSource()).getContentType()); }}));} /**Maps JEditorPane.getEditorKit() through queue*/ public EditorKit getEditorKit() { return((EditorKit)runMapping(new MapAction("getEditorKit") { public Object map() { return(((JEditorPane)getSource()).getEditorKit()); }}));} /**Maps JEditorPane.getEditorKitForContentType(String) through queue*/ public EditorKit getEditorKitForContentType(final String string) { return((EditorKit)runMapping(new MapAction("getEditorKitForContentType") { public Object map() { return(((JEditorPane)getSource()).getEditorKitForContentType(string)); }}));} /**Maps JEditorPane.getPage() through queue*/ public URL getPage() { return((URL)runMapping(new MapAction("getPage") { public Object map() { return(((JEditorPane)getSource()).getPage()); }}));} /**Maps JEditorPane.read(InputStream, Object) through queue*/ public void read(final InputStream inputStream, final Object object) { runMapping(new MapVoidAction("read") { public void map() throws IOException { ((JEditorPane)getSource()).read(inputStream, object); }});} /**Maps JEditorPane.removeHyperlinkListener(HyperlinkListener) through queue*/ public void removeHyperlinkListener(final HyperlinkListener hyperlinkListener) { runMapping(new MapVoidAction("removeHyperlinkListener") { public void map() { ((JEditorPane)getSource()).removeHyperlinkListener(hyperlinkListener); }});} /**Maps JEditorPane.setContentType(String) through queue*/ public void setContentType(final String string) { runMapping(new MapVoidAction("setContentType") { public void map() { ((JEditorPane)getSource()).setContentType(string); }});} /**Maps JEditorPane.setEditorKit(EditorKit) through queue*/ public void setEditorKit(final EditorKit editorKit) { runMapping(new MapVoidAction("setEditorKit") { public void map() { ((JEditorPane)getSource()).setEditorKit(editorKit); }});} /**Maps JEditorPane.setEditorKitForContentType(String, EditorKit) through queue*/ public void setEditorKitForContentType(final String string, final EditorKit editorKit) { runMapping(new MapVoidAction("setEditorKitForContentType") { public void map() { ((JEditorPane)getSource()).setEditorKitForContentType(string, editorKit); }});} /**Maps JEditorPane.setPage(String) through queue*/ public void setPage(final String string) { runMapping(new MapVoidAction("setPage") { public void map() throws IOException { ((JEditorPane)getSource()).setPage(string); }});} /**Maps JEditorPane.setPage(URL) through queue*/ public void setPage(final URL uRL) { runMapping(new MapVoidAction("setPage") { public void map() throws IOException { ((JEditorPane)getSource()).setPage(uRL); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Checks component type. */ public static class JEditorPaneFinder extends Finder { /** * Constructs JEditorPaneFinder. * @param sf other searching criteria. */ public JEditorPaneFinder(ComponentChooser sf) { super(JEditorPane.class, sf); } /** * Constructs JEditorPaneFinder. */ public JEditorPaneFinder() { super(JEditorPane.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JPopupMenuOperator.java0000644000175000017500000012251011245712237023727 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.Window; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.Hashtable; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.SingleSelectionModel; import javax.swing.event.PopupMenuListener; import javax.swing.plaf.PopupMenuUI; import org.netbeans.jemmy.Action; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.WindowWaiter; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.MenuDriver; /** *

Timeouts used:
* JMenuOperator.WaitBeforePopupTimeout - time to sleep before popup expanding
* JMenuOperator.WaitPopupTimeout - time to wait popup displayed
* ComponentOperator.WaitComponentTimeout - time to wait button displayed
* WindowWaiter.WaitWindowTimeout - time to wait popup window displayed
* WindowWaiter.AfterWindowTimeout - time to sleep after popup window has been dispayed
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JPopupMenuOperator extends JComponentOperator implements Outputable, Timeoutable { /** * Identifier for a "label" property. * @see #getDump */ public static final String LABEL_DPROP = "Label"; private TestOut output; private Timeouts timeouts; private MenuDriver driver; /** * Constructor. * @param popup a component */ public JPopupMenuOperator(JPopupMenu popup) { super(popup); driver = DriverManager.getMenuDriver(getClass()); } /** * Constructs a JPopupMenuOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JPopupMenuOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JPopupMenu)cont. waitSubComponent(new JPopupMenuFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JPopupMenuOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JPopupMenuOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component first. * Constructor can be used in complicated cases when * output or timeouts should differ from default. * @param env an operator to copy environment from. * @throws TimeoutExpiredException */ public JPopupMenuOperator(Operator env) { this((JPopupMenu) waitComponent(WindowOperator. waitWindow(new JPopupWindowFinder(), 0, env.getTimeouts(), env.getOutput()), new JPopupMenuFinder(), 0, env.getTimeouts(), env.getOutput())); copyEnvironment(env); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JPopupMenuOperator(ContainerOperator cont) { this((JPopupMenu) waitComponent(cont, new JPopupMenuFinder(), 0)); copyEnvironment(cont); } /** * Constructor. * Waits component first. * @throws TimeoutExpiredException */ public JPopupMenuOperator() { this(Operator.getEnvironmentOperator()); } /** * Searches JPopupMenu in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JPopupMenu instance or null if component was not found. */ public static JPopupMenu findJPopupMenu(Container cont, ComponentChooser chooser, int index) { return((JPopupMenu)findComponent(cont, new JPopupMenuFinder(chooser), index)); } /** * Searches JPopupMenu in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JPopupMenu instance or null if component was not found. */ public static JPopupMenu findJPopupMenu(Container cont, ComponentChooser chooser) { return(findJPopupMenu(cont, chooser, 0)); } /** * Waits JPopupMenu in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JPopupMenu instance. * @throws TimeoutExpiredException */ public static JPopupMenu waitJPopupMenu(Container cont, ComponentChooser chooser, int index) { return((JPopupMenu)waitComponent(cont, new JPopupMenuFinder(chooser), index)); } /** * Waits JPopupMenu in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JPopupMenu instance. * @throws TimeoutExpiredException */ public static JPopupMenu waitJPopupMenu(Container cont, ComponentChooser chooser) { return(waitJPopupMenu(cont, chooser, 0)); } /** * Searches for a window which contains JPopupMenu. * @param chooser a component chooser specifying criteria for JPopupMenu. * @return a window containing JPopupMenu. */ public static Window findJPopupWindow(ComponentChooser chooser) { return((new WindowWaiter()).getWindow(new JPopupWindowFinder(chooser))); } /** * Waits for a window which contains JPopupMenu. * @param chooser a component chooser specifying criteria for JPopupMenu. * @return a window containing JPopupMenu. * @throws TimeoutExpiredException */ public static Window waitJPopupWindow(ComponentChooser chooser) { try { return((new WindowWaiter()).waitWindow(new JPopupWindowFinder(chooser))); } catch(InterruptedException e) { return(null); } } /** * Waits popup defined by popupChooser parameter. * @param popupChooser a component chooser specifying criteria for JPopupMenu. * @return a JPopupMenu fitting the criteria. */ public static JPopupMenuOperator waitJPopupMenu(final ComponentChooser popupChooser) { try { WindowOperator wind = new WindowOperator(new WindowWaiter().waitWindow(new ComponentChooser() { public boolean checkComponent(Component comp) { ComponentSearcher searcher = new ComponentSearcher((Container)comp); searcher.setOutput(JemmyProperties.getCurrentOutput().createErrorOutput()); return(searcher.findComponent(popupChooser) != null); } public String getDescription() { return("Window containing \"" + popupChooser.getDescription() + "\" popup"); } })); return(new JPopupMenuOperator(wind)); } catch(InterruptedException e) { throw(new JemmyException("Popup waiting has been interrupted", e)); } } /** * Waits popup containing menu item with menuItemText text. * @param menuItemText a text of a menu item which supposed to be displayed inside the popup. * @return a JPopupMenu fitting the criteria. */ public static JPopupMenuOperator waitJPopupMenu(final String menuItemText) { return(waitJPopupMenu(new ComponentChooser() { public boolean checkComponent(Component comp) { if(comp instanceof JPopupMenu) { ComponentSearcher searcher = new ComponentSearcher((Container)comp); searcher.setOutput(JemmyProperties.getCurrentOutput().createErrorOutput()); return(searcher.findComponent(new JMenuItemOperator. JMenuItemByLabelFinder(menuItemText, Operator.getDefaultStringComparator())) != null); } else { return(false); } } public String getDescription() { return("Popup containing \"" + menuItemText + "\" menu item"); } })); } /** * Calls popup by clicking on (x, y) point in component. * @param oper Component operator to call popup on. * @param x X coordinate of click point in the component coordinate system. * @param y Y coordinate of click point in the component coordinate system. * @param mouseButton Mouse button mask to call popup. * @return an opened JPopupMenu * @throws TimeoutExpiredException */ public static JPopupMenu callPopup(final ComponentOperator oper, int x, int y, int mouseButton) { oper.makeComponentVisible(); //1.5 workaround if(System.getProperty("java.specification.version").compareTo("1.4") > 0) { QueueTool qt = new QueueTool(); qt.setOutput(oper.getOutput().createErrorOutput()); qt.waitEmpty(10); qt.waitEmpty(10); qt.waitEmpty(10); } //end of 1.5 workaround oper.clickForPopup(x, y, mouseButton); oper.getTimeouts().sleep("JMenuOperator.WaitBeforePopupTimeout"); return(waitJPopupMenu(waitJPopupWindow(new ComponentChooser() { public boolean checkComponent(Component cmp) { Component invoker = ((JPopupMenu)cmp).getInvoker(); return(invoker == oper.getSource() || (invoker instanceof Container && ((Container)invoker).isAncestorOf(oper.getSource())) || (oper.getSource() instanceof Container && ((Container)oper.getSource()).isAncestorOf(invoker))); } public String getDescription() { return("Popup menu"); } }), ComponentSearcher.getTrueChooser("Popup menu"))); } /** * Calls popup by clicking on (x, y) point in component. * @param oper Component operator to call popup on. * @param x X coordinate of click point in the component coordinate system. * @param y Y coordinate of click point in the component coordinate system. * @return an opened JPopupMenu * @see ComponentOperator#getPopupMouseButton() * @throws TimeoutExpiredException */ public static JPopupMenu callPopup(ComponentOperator oper, int x, int y) { return(callPopup(oper, x, y, getPopupMouseButton())); } /** * Calls popup by clicking on (x, y) point in component. * @param comp Component to call popup on. * @param x X coordinate of click point in the component coordinate system. * @param y Y coordinate of click point in the component coordinate system. * @param mouseButton Mouse button mask to call popup. * @return an opened JPopupMenu * @throws TimeoutExpiredException */ public static JPopupMenu callPopup(Component comp, int x, int y, int mouseButton) { return(callPopup(new ComponentOperator(comp), x, y, mouseButton)); } /** * Calls popup by clicking on (x, y) point in component. * @param comp Component to call popup on. * @param x X coordinate of click point in the component coordinate system. * @param y Y coordinate of click point in the component coordinate system. * @return an opened JPopupMenu * @see ComponentOperator#getPopupMouseButton() * @throws TimeoutExpiredException */ public static JPopupMenu callPopup(Component comp, int x, int y) { return(callPopup(comp, x, y, getPopupMouseButton())); } /** * Calls popup by clicking component center. * @param comp Component to call popup on. * @param mouseButton Mouse button mask to call popup. * @return an opened JPopupMenu * @throws TimeoutExpiredException */ public static JPopupMenu callPopup(Component comp, int mouseButton) { ComponentOperator co = new ComponentOperator(comp); co.makeComponentVisible(); co.clickForPopup(mouseButton); return(findJPopupMenu(waitJPopupWindow(ComponentSearcher.getTrueChooser("Popup menu window")), ComponentSearcher.getTrueChooser("Popup menu"))); } /** * Calls popup by clicking component center. * @param comp Component to call popup on. * @return an opened JPopupMenu * @see ComponentOperator#getPopupMouseButton() * @throws TimeoutExpiredException */ public static JPopupMenu callPopup(Component comp) { return(callPopup(comp, getPopupMouseButton())); } static { //necessary to init timeouts JMenuOperator.performInit(); } public void setOutput(TestOut out) { super.setOutput(out); output = out; } public TestOut getOutput() { return(output); } public void setTimeouts(Timeouts times) { super.setTimeouts(times); timeouts = times; } public Timeouts getTimeouts() { return(timeouts); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = DriverManager.getMenuDriver(this); } /** * Pushes menu. * @param choosers Array of choosers to find menuItems to push. * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(final ComponentChooser[] choosers) { return((JMenuItem)produceTimeRestricted(new Action() { public Object launch(Object obj) { //TDB 1.5 menu workaround getQueueTool().waitEmpty(); Object result = driver.pushMenu(JPopupMenuOperator.this, JMenuOperator.converChoosers(choosers)); getQueueTool().waitEmpty(); return(result); } public String getDescription() { return(JMenuOperator.createDescription(choosers)); } }, getTimeouts().getTimeout("JMenuOperator.PushMenuTimeout"))); } /** * Executes pushMenu(choosers) in a separate thread. * @param choosers Array of choosers to find menuItems to push. * @see #pushMenu(ComponentChooser[]) */ public void pushMenuNoBlock(final ComponentChooser[] choosers) { produceNoBlocking(new NoBlockingAction("Menu pushing") { public Object doAction(Object param) { //TDB 1.5 menu workaround getQueueTool().waitEmpty(); Object result = driver.pushMenu(JPopupMenuOperator.this, JMenuOperator.converChoosers(choosers)); getQueueTool().waitEmpty(); return(result); } }); } /** * Pushes menu. * @param names an array of menu texts. * @param comparator a string comparision algorithm * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String[] names, StringComparator comparator) { return(pushMenu(JMenuItemOperator.createChoosers(names, comparator))); } /** * Pushes menu. * @param names Menu items texts. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @return Last pushed JMenuItem. * @throws TimeoutExpiredException * @deprecated Use pushMenu(String[]) or pushMenu(String[], StringComparator) */ public JMenuItem pushMenu(String[] names, boolean ce, boolean ccs) { return(pushMenu(names, new DefaultStringComparator(ce, ccs))); } /** * Executes pushMenu(names, ce, ccs) in a separate thread. * @param names an array of menu texts. * @param comparator a string comparision algorithm */ public void pushMenuNoBlock(String[] names, StringComparator comparator) { pushMenuNoBlock(JMenuItemOperator.createChoosers(names, comparator)); } /** * Executes pushMenu(names, ce, ccs) in a separate thread. * @param names Menu items texts. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @see #pushMenu(String[], boolean,boolean) * @deprecated Use pushMenuNoBlock(String[]) or pushMenuNoBlock(String[], StringComparator) */ public void pushMenuNoBlock(String[] names, boolean ce, boolean ccs) { pushMenuNoBlock(names, new DefaultStringComparator(ce, ccs)); } /** * Pushes menu. * @param names Menu items texts. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String[] names) { return(pushMenu(names, getComparator())); } /** * Executes pushMenu(names) in a separate thread. * @param names Menu items texts. * @see #pushMenu(String[]) */ public void pushMenuNoBlock(String[] names) { pushMenuNoBlock(names, getComparator()); } /** * Pushes menu. * @param path a menu path. * @param delim a path delimiter. * @param comparator a string comparision algorithm * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String path, String delim, StringComparator comparator) { return(pushMenu(parseString(path, delim), comparator)); } /** * Pushes menu. Uses PathParser assigned to this operator. * @param path a menu path. * @param comparator a string comparision algorithm * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String path, StringComparator comparator) { return(pushMenu(parseString(path), comparator)); } /** * Pushes menu. * @param path String menupath representation ("File/New", for example). * @param delim String menupath divider ("/"). * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @return Last pushed JMenuItem. * @throws TimeoutExpiredException * @deprecated Use pushMenu(String, String) or pushMenu(String, String, StringComparator) */ public JMenuItem pushMenu(String path, String delim, boolean ce, boolean ccs) { return(pushMenu(parseString(path, delim), ce, ccs)); } /** * Executes pushMenu(names, delim, comparator) in a separate thread. * @param path a menu path. * @param delim a path delimiter. * @param comparator a string comparision algorithm */ public void pushMenuNoBlock(String path, String delim, StringComparator comparator) { pushMenuNoBlock(parseString(path, delim), comparator); } /** * Executes pushMenu(names, comparator) in a separate thread. * Uses PathParser assigned to this operator. * @param path a menu path. * @param comparator a string comparision algorithm */ public void pushMenuNoBlock(String path, StringComparator comparator) { pushMenuNoBlock(parseString(path), comparator); } /** * Executes pushMenu(path, delim, ce, ccs) in a separate thread. * @param path String menupath representation ("File/New", for example). * @param delim String menupath divider ("/"). * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @see #pushMenu * @deprecated Use pushMenuNoBlock(String, String) or pushMenuNoBlock(String, String, StringComparator) */ public void pushMenuNoBlock(String path, String delim, boolean ce, boolean ccs) { pushMenuNoBlock(parseString(path, delim), ce, ccs); } /** * Pushes menu. * @param path String menupath representation ("File/New", for example). * @param delim String menupath divider ("/"). * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String path, String delim) { return(pushMenu(parseString(path, delim))); } /** * Pushes menu. Uses PathParser assigned to this operator. * @param path String menupath representation ("File/New", for example). * @return Last pushed JMenuItem. * @throws TimeoutExpiredException */ public JMenuItem pushMenu(String path) { return(pushMenu(parseString(path))); } /** * Executes pushMenu(path, delim) in a separate thread. * @param path String menupath representation ("File/New", for example). * @param delim String menupath divider ("/"). */ public void pushMenuNoBlock(String path, String delim) { pushMenuNoBlock(parseString(path, delim)); } /** * Executes pushMenu(path) in a separate thread. * @param path String menupath representation ("File/New", for example). */ public void pushMenuNoBlock(String path) { pushMenuNoBlock(parseString(path)); } public JMenuItemOperator[] showMenuItems(ComponentChooser[] choosers) { if(choosers == null || choosers.length == 0) { return(JMenuItemOperator.getMenuItems((MenuElement)getSource(), this)); } else { return(JMenuItemOperator.getMenuItems((JMenu)pushMenu(choosers), this)); } } /** * Shows submenu of menu specified by a path parameter. * @param path an array of menu texts. * @param comparator a string comparision algorithm * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String[] path, StringComparator comparator) { if(path == null || path.length == 0) { return(JMenuItemOperator.getMenuItems((MenuElement)getSource(), this)); } else { return(JMenuItemOperator.getMenuItems((JMenu)pushMenu(path, comparator), this)); } } /** * Shows submenu of menu specified by a path parameter. * Uses StringComparator assigned to the operator. * @param path an array of menu texts. * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String[] path) { return(showMenuItems(path, getComparator())); } /** * Shows submenu of menu specified by a path parameter. * @param path a string identifying the menu path. * @param delim a path delimiter. * @param comparator a string comparision algorithm * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String path, String delim, StringComparator comparator ) { return(showMenuItems(parseString(path, delim), comparator)); } /** * Shows submenu of menu specified by a path parameter. * Uses PathParser assigned to this operator. * @param path a string identifying the menu path. * @param comparator a string comparision algorithm * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String path, StringComparator comparator ) { return(showMenuItems(parseString(path), comparator)); } /** * Shows submenu of menu specified by a path parameter. * Uses StringComparator assigned to the operator. * @param path a string identifying the menu path. * @param delim a path delimiter. * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String path, String delim) { return(showMenuItems(path, delim, getComparator())); } /** * Shows submenu of menu specified by a path parameter. * Uses PathParser assigned to this operator. * Uses StringComparator assigned to the operator. * @param path a string identifying the menu path. * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator[] showMenuItems(String path) { return(showMenuItems(path, getComparator())); } public JMenuItemOperator showMenuItem(ComponentChooser[] choosers) { ComponentChooser[] parentPath = getParentPath(choosers); JMenu menu; ContainerOperator menuCont; if(parentPath.length > 0) { menu = (JMenu)pushMenu(getParentPath(choosers)); menuCont = new ContainerOperator(menu.getPopupMenu()); menuCont.copyEnvironment(this); } else { menuCont = this; } JMenuItemOperator result = new JMenuItemOperator(menuCont, choosers[choosers.length - 1]); result.copyEnvironment(this); return(result); } /** * Expends all menus to show menu item specified by a path parameter. * @param path an array of menu texts. * @param comparator a string comparision algorithm * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String[] path, StringComparator comparator ) { String[] parentPath = getParentPath(path); JMenu menu; ContainerOperator menuCont; if(parentPath.length > 0) { menu = (JMenu)pushMenu(getParentPath(path), comparator); menuCont = new ContainerOperator(menu.getPopupMenu()); menuCont.copyEnvironment(this); } else { menuCont = this; } JMenuItemOperator result = new JMenuItemOperator(menuCont, path[path.length - 1]); result.copyEnvironment(this); return(result); } /** * Expands all menus to show menu item specified by a path parameter. * @param path an array of menu texts. * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String[] path) { return(showMenuItem(path, getComparator())); } /** * Expands all menus to show menu item specified by a path parameter. * @param path a string identifying the menu path. * @param delim a path delimiter. * @param comparator a string comparision algorithm * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String path, String delim, StringComparator comparator ) { return(showMenuItem(parseString(path, delim), comparator)); } /** * Expands all menus to show menu item specified by a path parameter. * Uses PathParser assigned to this operator. * @param path a string identifying the menu path. * @param comparator a string comparision algorithm * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String path, StringComparator comparator ) { return(showMenuItem(parseString(path), comparator)); } /** * Expands all menus to show menu item specified by a path parameter. * Uses StringComparator assigned to the operator. * @param path a string identifying the menu path. * @param delim a path delimiter. * @return an operator for the last menu item in path. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String path, String delim) { return(showMenuItem(path, delim, getComparator())); } /** * Expands all menus to show menu item specified by a path parameter. * Uses PathParser assigned to this operator. * Uses StringComparator assigned to the operator. * @param path a string identifying the menu path. * @return an array of operators created tor items from the submenu. * @throws TimeoutExpiredException */ public JMenuItemOperator showMenuItem(String path) { return(showMenuItem(path, getComparator())); } public Hashtable getDump() { Hashtable result = super.getDump(); if(((JPopupMenu)getSource()).getLabel() != null) { result.put(LABEL_DPROP, ((JPopupMenu)getSource()).getLabel()); } return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JPopupMenu.add(String) through queue*/ public JMenuItem add(final String string) { return((JMenuItem)runMapping(new MapAction("add") { public Object map() { return(((JPopupMenu)getSource()).add(string)); }}));} /**Maps JPopupMenu.add(Action) through queue*/ public JMenuItem add(final javax.swing.Action action) { return((JMenuItem)runMapping(new MapAction("add") { public Object map() { return(((JPopupMenu)getSource()).add(action)); }}));} /**Maps JPopupMenu.add(JMenuItem) through queue*/ public JMenuItem add(final JMenuItem jMenuItem) { return((JMenuItem)runMapping(new MapAction("add") { public Object map() { return(((JPopupMenu)getSource()).add(jMenuItem)); }}));} /**Maps JPopupMenu.addPopupMenuListener(PopupMenuListener) through queue*/ public void addPopupMenuListener(final PopupMenuListener popupMenuListener) { runMapping(new MapVoidAction("addPopupMenuListener") { public void map() { ((JPopupMenu)getSource()).addPopupMenuListener(popupMenuListener); }});} /**Maps JPopupMenu.addSeparator() through queue*/ public void addSeparator() { runMapping(new MapVoidAction("addSeparator") { public void map() { ((JPopupMenu)getSource()).addSeparator(); }});} /**Maps JPopupMenu.getComponentIndex(Component) through queue*/ public int getComponentIndex(final Component component) { return(runMapping(new MapIntegerAction("getComponentIndex") { public int map() { return(((JPopupMenu)getSource()).getComponentIndex(component)); }}));} /**Maps JPopupMenu.getInvoker() through queue*/ public Component getInvoker() { return((Component)runMapping(new MapAction("getInvoker") { public Object map() { return(((JPopupMenu)getSource()).getInvoker()); }}));} /**Maps JPopupMenu.getLabel() through queue*/ public String getLabel() { return((String)runMapping(new MapAction("getLabel") { public Object map() { return(((JPopupMenu)getSource()).getLabel()); }}));} /**Maps JPopupMenu.getMargin() through queue*/ public Insets getMargin() { return((Insets)runMapping(new MapAction("getMargin") { public Object map() { return(((JPopupMenu)getSource()).getMargin()); }}));} /**Maps JPopupMenu.getSelectionModel() through queue*/ public SingleSelectionModel getSelectionModel() { return((SingleSelectionModel)runMapping(new MapAction("getSelectionModel") { public Object map() { return(((JPopupMenu)getSource()).getSelectionModel()); }}));} /**Maps JPopupMenu.getSubElements() through queue*/ public MenuElement[] getSubElements() { return((MenuElement[])runMapping(new MapAction("getSubElements") { public Object map() { return(((JPopupMenu)getSource()).getSubElements()); }}));} /**Maps JPopupMenu.getUI() through queue*/ public PopupMenuUI getUI() { return((PopupMenuUI)runMapping(new MapAction("getUI") { public Object map() { return(((JPopupMenu)getSource()).getUI()); }}));} /**Maps JPopupMenu.insert(Component, int) through queue*/ public void insert(final Component component, final int i) { runMapping(new MapVoidAction("insert") { public void map() { ((JPopupMenu)getSource()).insert(component, i); }});} /**Maps JPopupMenu.insert(Action, int) through queue*/ public void insert(final javax.swing.Action action, final int i) { runMapping(new MapVoidAction("insert") { public void map() { ((JPopupMenu)getSource()).insert(action, i); }});} /**Maps JPopupMenu.isBorderPainted() through queue*/ public boolean isBorderPainted() { return(runMapping(new MapBooleanAction("isBorderPainted") { public boolean map() { return(((JPopupMenu)getSource()).isBorderPainted()); }}));} /**Maps JPopupMenu.isLightWeightPopupEnabled() through queue*/ public boolean isLightWeightPopupEnabled() { return(runMapping(new MapBooleanAction("isLightWeightPopupEnabled") { public boolean map() { return(((JPopupMenu)getSource()).isLightWeightPopupEnabled()); }}));} /**Maps JPopupMenu.menuSelectionChanged(boolean) through queue*/ public void menuSelectionChanged(final boolean b) { runMapping(new MapVoidAction("menuSelectionChanged") { public void map() { ((JPopupMenu)getSource()).menuSelectionChanged(b); }});} /**Maps JPopupMenu.pack() through queue*/ public void pack() { runMapping(new MapVoidAction("pack") { public void map() { ((JPopupMenu)getSource()).pack(); }});} /**Maps JPopupMenu.processKeyEvent(KeyEvent, MenuElement[], MenuSelectionManager) through queue*/ public void processKeyEvent(final KeyEvent keyEvent, final MenuElement[] menuElement, final MenuSelectionManager menuSelectionManager) { runMapping(new MapVoidAction("processKeyEvent") { public void map() { ((JPopupMenu)getSource()).processKeyEvent(keyEvent, menuElement, menuSelectionManager); }});} /**Maps JPopupMenu.processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager) through queue*/ public void processMouseEvent(final MouseEvent mouseEvent, final MenuElement[] menuElement, final MenuSelectionManager menuSelectionManager) { runMapping(new MapVoidAction("processMouseEvent") { public void map() { ((JPopupMenu)getSource()).processMouseEvent(mouseEvent, menuElement, menuSelectionManager); }});} /**Maps JPopupMenu.removePopupMenuListener(PopupMenuListener) through queue*/ public void removePopupMenuListener(final PopupMenuListener popupMenuListener) { runMapping(new MapVoidAction("removePopupMenuListener") { public void map() { ((JPopupMenu)getSource()).removePopupMenuListener(popupMenuListener); }});} /**Maps JPopupMenu.setBorderPainted(boolean) through queue*/ public void setBorderPainted(final boolean b) { runMapping(new MapVoidAction("setBorderPainted") { public void map() { ((JPopupMenu)getSource()).setBorderPainted(b); }});} /**Maps JPopupMenu.setInvoker(Component) through queue*/ public void setInvoker(final Component component) { runMapping(new MapVoidAction("setInvoker") { public void map() { ((JPopupMenu)getSource()).setInvoker(component); }});} /**Maps JPopupMenu.setLabel(String) through queue*/ public void setLabel(final String string) { runMapping(new MapVoidAction("setLabel") { public void map() { ((JPopupMenu)getSource()).setLabel(string); }});} /**Maps JPopupMenu.setLightWeightPopupEnabled(boolean) through queue*/ public void setLightWeightPopupEnabled(final boolean b) { runMapping(new MapVoidAction("setLightWeightPopupEnabled") { public void map() { ((JPopupMenu)getSource()).setLightWeightPopupEnabled(b); }});} /**Maps JPopupMenu.setPopupSize(int, int) through queue*/ public void setPopupSize(final int i, final int i1) { runMapping(new MapVoidAction("setPopupSize") { public void map() { ((JPopupMenu)getSource()).setPopupSize(i, i1); }});} /**Maps JPopupMenu.setPopupSize(Dimension) through queue*/ public void setPopupSize(final Dimension dimension) { runMapping(new MapVoidAction("setPopupSize") { public void map() { ((JPopupMenu)getSource()).setPopupSize(dimension); }});} /**Maps JPopupMenu.setSelected(Component) through queue*/ public void setSelected(final Component component) { runMapping(new MapVoidAction("setSelected") { public void map() { ((JPopupMenu)getSource()).setSelected(component); }});} /**Maps JPopupMenu.setSelectionModel(SingleSelectionModel) through queue*/ public void setSelectionModel(final SingleSelectionModel singleSelectionModel) { runMapping(new MapVoidAction("setSelectionModel") { public void map() { ((JPopupMenu)getSource()).setSelectionModel(singleSelectionModel); }});} /**Maps JPopupMenu.setUI(PopupMenuUI) through queue*/ public void setUI(final PopupMenuUI popupMenuUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JPopupMenu)getSource()).setUI(popupMenuUI); }});} /**Maps JPopupMenu.show(Component, int, int) through queue*/ public void show(final Component component, final int i, final int i1) { runMapping(new MapVoidAction("show") { public void map() { ((JPopupMenu)getSource()).show(component, i, i1); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Checks component type. */ public static class JPopupMenuFinder extends Finder { /** * Constructs JPopupMenuFinder. * @param sf other searching criteria. */ public JPopupMenuFinder(ComponentChooser sf) { super(JPopupMenu.class, sf); } /** * Constructs JPopupMenuFinder. */ public JPopupMenuFinder() { super(JPopupMenu.class); } public boolean checkComponent(Component comp) { return(comp.isShowing() && super.checkComponent(comp)); } } /** * Allwos to find a window containing JPopupMenu. */ public static class JPopupWindowFinder implements ComponentChooser { ComponentChooser subFinder; ComponentChooser ppFinder; /** * Constructs JPopupWindowFinder. * @param sf searching criteria for a JPopupMenu inside the window.. */ public JPopupWindowFinder(ComponentChooser sf) { subFinder = new JPopupMenuFinder(sf); ppFinder = new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp.isShowing() && comp.isVisible() && subFinder.checkComponent(comp)); } public String getDescription() { return(subFinder.getDescription()); } }; } /** * Constructs JPopupWindowFinder. */ public JPopupWindowFinder() { this(ComponentSearcher.getTrueChooser("Any JPopupWindow")); } public boolean checkComponent(Component comp) { if(comp.isShowing() && comp instanceof Window) { ComponentSearcher cs = new ComponentSearcher((Container)comp); cs.setOutput(JemmyProperties.getCurrentOutput().createErrorOutput()); return(cs.findComponent(ppFinder) != null); } return(false); } public String getDescription() { return(subFinder.getDescription()); } } } Jemmy2/src/org/netbeans/jemmy/operators/ChoiceOperator.java0000644000175000017500000004524611245712237023071 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Choice; import java.awt.Component; import java.awt.Container; import java.awt.event.ItemListener; import java.util.Hashtable; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.ListDriver; /** * *

Timeouts used:
* ButtonOperator.PushButtonTimeout - time between choice pressing and releasing
* ComponentOperator.WaitComponentTimeout - time to wait choice displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait choice enabled
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class ChoiceOperator extends ComponentOperator implements Outputable{ /** * Identifier for a selected item property. * @see #getDump */ public static final String SELECTED_ITEM_DPROP = "Selected item"; /** * Identifier for a items properties. * @see #getDump */ public static final String ITEM_PREFIX_DPROP = "Item"; private TestOut output; private ListDriver driver; /** * Constructor. * @param b a component */ public ChoiceOperator(Choice b) { super(b); driver = DriverManager.getListDriver(getClass()); } /** * Constructs a ChoiceOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public ChoiceOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((Choice)cont. waitSubComponent(new ChoiceFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a ChoiceOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. */ public ChoiceOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont container * @param text Choice text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public ChoiceOperator(ContainerOperator cont, String text, int index) { this((Choice) waitComponent(cont, new ChoiceBySelectedItemFinder(text, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont container * @param text Choice text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public ChoiceOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public ChoiceOperator(ContainerOperator cont, int index) { this((Choice) waitComponent(cont, new ChoiceFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont container * @throws TimeoutExpiredException */ public ChoiceOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches Choice in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return Choice instance or null if component was not found. */ public static Choice findChoice(Container cont, ComponentChooser chooser, int index) { return((Choice)findComponent(cont, new ChoiceFinder(chooser), index)); } /** * Searches 0'th Choice in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return Choice instance or null if component was not found. */ public static Choice findChoice(Container cont, ComponentChooser chooser) { return(findChoice(cont, chooser, 0)); } /** * Searches Choice by text. * @param cont Container to search component in. * @param text Choice text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return Choice instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static Choice findChoice(Container cont, String text, boolean ce, boolean ccs, int index) { return(findChoice(cont, new ChoiceBySelectedItemFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches Choice by text. * @param cont Container to search component in. * @param text Choice text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return Choice instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static Choice findChoice(Container cont, String text, boolean ce, boolean ccs) { return(findChoice(cont, text, ce, ccs, 0)); } /** * Waits Choice in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return Choice instance. * @throws TimeoutExpiredException */ public static Choice waitChoice(Container cont, ComponentChooser chooser, int index) { return((Choice)waitComponent(cont, new ChoiceFinder(chooser), index)); } /** * Waits 0'th Choice in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return Choice instance. * @throws TimeoutExpiredException */ public static Choice waitChoice(Container cont, ComponentChooser chooser) { return(waitChoice(cont, chooser, 0)); } /** * Waits Choice by text. * @param cont Container to search component in. * @param text Choice text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return Choice instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static Choice waitChoice(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitChoice(cont, new ChoiceBySelectedItemFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits Choice by text. * @param cont Container to search component in. * @param text Choice text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return Choice instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static Choice waitChoice(Container cont, String text, boolean ce, boolean ccs) { return(waitChoice(cont, text, ce, ccs, 0)); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (ListDriver)DriverManager. getDriver(DriverManager.LIST_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Finds an item between choice items. * @param item a text pattern. * @param index an ordinal index between appropriate items. * @return an item index. */ public int findItemIndex(String item, int index){ return(findItemIndex(item, getComparator(), index)); } /** * Finds an item between choice items. * @param item a text pattern. * @return an item index. */ public int findItemIndex(String item){ return(findItemIndex(item, 0)); } /** * Selects an item by text. * @param item a text pattern. * @param index an ordinal index between appropriate items. */ public void selectItem(String item, int index) { selectItem(item, getComparator(), index); } /** * Selects an item by text. * @param item a text pattern. */ public void selectItem(String item) { selectItem(item, 0); } /** * Selects an item by index. * @param index an item index. */ public void selectItem(int index) { output.printLine("Select " + Integer.toString(index) + "`th item in combobox\n : " + toStringSource()); output.printGolden("Select " + Integer.toString(index) + "`th item in combobox"); makeComponentVisible(); try { waitComponentEnabled(); } catch(InterruptedException e) { throw(new JemmyException("Interrupted!", e)); } driver.selectItem(this, index); if(getVerification()) { waitItemSelected(index); } } /** * Waits for item to be selected. * @param index Item index. */ public void waitItemSelected(final int index) { getOutput().printLine("Wait " + Integer.toString(index) + "'th item to be selected in component \n : "+ toStringSource()); getOutput().printGolden("Wait " + Integer.toString(index) + "'th item to be selected"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(getSelectedIndex() == index); } public String getDescription() { return("Has " + Integer.toString(index) + "'th item selected"); } }); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); if(((Choice)getSource()).getSelectedItem() != null) { result.put(SELECTED_ITEM_DPROP, ((Choice)getSource()).getSelectedItem()); } String[] items = new String[((Choice)getSource()).getItemCount()]; for (int i=0; i<((Choice)getSource()).getItemCount(); i++) { items[i] = ((Choice)getSource()).getItem(i); } addToDump(result, ITEM_PREFIX_DPROP, items); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps Choice.add(String) through queue*/ public void add(final String item) { runMapping(new MapVoidAction("add") { public void map() { ((Choice)getSource()).add(item); }});} /**Maps Choice.addItemListener(ItemListener) through queue*/ public void addItemListener(final ItemListener itemListener) { runMapping(new MapVoidAction("addItemListener") { public void map() { ((Choice)getSource()).addItemListener(itemListener); }});} /**Maps Choice.addNotify() through queue*/ public void addNotify() { runMapping(new MapVoidAction("addNotify") { public void map() { ((Choice)getSource()).addNotify(); }});} /**Maps Choice.getItem(int) through queue*/ public String getItem(final int index) { return((String)runMapping(new MapAction("getItem") { public Object map() { return(((Choice)getSource()).getItem(index)); }}));} /**Maps Choice.getItemCount() through queue*/ public int getItemCount() { return(runMapping(new MapIntegerAction("getItemCount") { public int map() { return(((Choice)getSource()).getItemCount()); }}));} /**Maps Choice.getSelectedIndex() through queue*/ public int getSelectedIndex() { return(runMapping(new MapIntegerAction("getSelectedIndex") { public int map() { return(((Choice)getSource()).getSelectedIndex()); }}));} /**Maps Choice.getSelectedItem() through queue*/ public String getSelectedItem() { return((String)runMapping(new MapAction("getSelectedItem") { public Object map() { return(((Choice)getSource()).getSelectedItem()); }}));} /**Maps Choice.insert(String) through queue*/ public void insert(final String item,final int index) { runMapping(new MapVoidAction("insert") { public void map() { ((Choice)getSource()).insert(item,index); }});} /**Maps Choice.remove(int) through queue*/ public void remove(final int position) { runMapping(new MapVoidAction("remove") { public void map() { ((Choice)getSource()).remove(position); }});} /**Maps Choice.remove(String) through queue*/ public void remove(final String item) { runMapping(new MapVoidAction("remove") { public void map() { ((Choice)getSource()).remove(item); }});} /**Maps Choice.removeAll() through queue*/ public void removeAll() { runMapping(new MapVoidAction("removeAll") { public void map() { ((Choice)getSource()).removeAll(); }});} /**Maps Choice.removeItemListener(ItemListener) through queue*/ public void removeItemListener(final ItemListener itemListener) { runMapping(new MapVoidAction("removeItemListener") { public void map() { ((Choice)getSource()).removeItemListener(itemListener); }});} /**Maps Choice.select(int) through queue*/ public void select(final int pos) { runMapping(new MapVoidAction("select") { public void map() { ((Choice)getSource()).select(pos); }});} /**Maps Choice.select(String) through queue*/ public void setState(final String str) { runMapping(new MapVoidAction("select") { public void map() { ((Choice)getSource()).select(str); }});} //End of mapping // //////////////////////////////////////////////////////// private int findItemIndex(String item, StringComparator comparator, int index){ int count = 0; for(int i = 0; i < getItemCount(); i++) { if(comparator.equals(getItem(i), item)) { if(count == index) { return(i); } else { count++; } } } return(-1); } private void selectItem(String item, StringComparator comparator, int index) { selectItem(findItemIndex(item, comparator, index)); } /** * Allows to find component by label. */ public static class ChoiceBySelectedItemFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs ChoiceBySelectedItemFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public ChoiceBySelectedItemFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs ChoiceBySelectedItemFinder. * @param lb a text pattern */ public ChoiceBySelectedItemFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof Choice) { if(((Choice)comp).getSelectedItem() != null) { return(comparator.equals(((Choice)comp).getSelectedItem(), label)); } } return(false); } public String getDescription() { return("Choice with label \"" + label + "\""); } } /** * Checks component type. */ public static class ChoiceFinder extends Finder { /** * Constructs ChoiceFinder. * @param sf other searching criteria. */ public ChoiceFinder(ComponentChooser sf) { super(Choice.class, sf); } /** * Constructs ChoiceFinder. */ public ChoiceFinder() { super(Choice.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JProgressBarOperator.java0000644000175000017500000004500511245712447024236 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.util.Hashtable; import javax.swing.BoundedRangeModel; import javax.swing.JProgressBar; import javax.swing.event.ChangeListener; import javax.swing.plaf.ProgressBarUI; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.Waitable; import org.netbeans.jemmy.Waiter; /** * * Operator is supposed to be used to operate with an instance of * javax.swing.JProgressBar class. * *

Timeouts used:
* JProgressBarOperator.WaitValueTimeout - used from waitValue() method
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class JProgressBarOperator extends JComponentOperator implements Timeoutable, Outputable { /** * Identifier for a "minimum" property. * @see #getDump */ public static final String MINIMUM_DPROP = "Minimum"; /** * Identifier for a "maximum" property. * @see #getDump */ public static final String MAXIMUM_DPROP = "Maximum"; /** * Identifier for a "value" property. * @see #getDump */ public static final String VALUE_DPROP = "Value"; private static long WAIT_VALUE_TIMEOUT = 60000; private Timeouts timeouts; private TestOut output; /** * Constructor. * @param b JProgressBar component. */ public JProgressBarOperator(JProgressBar b) { super(b); } /** * Constructs a JProgressBarOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JProgressBarOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JProgressBar)cont. waitSubComponent(new JProgressBarFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JProgressBarOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JProgressBarOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JProgressBarOperator(ContainerOperator cont, int index) { this((JProgressBar)waitComponent(cont, new JProgressBarFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @throws TimeoutExpiredException */ public JProgressBarOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JProgressBar in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JProgressBar instance or null if component was not found. */ public static JProgressBar findJProgressBar(Container cont, ComponentChooser chooser, int index) { return((JProgressBar)findComponent(cont, new JProgressBarFinder(chooser), index)); } /** * Searches 0'th JProgressBar in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JProgressBar instance or null if component was not found. */ public static JProgressBar findJProgressBar(Container cont, ComponentChooser chooser) { return(findJProgressBar(cont, chooser, 0)); } /** * Searches JProgressBar in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JProgressBar instance or null if component was not found. */ public static JProgressBar findJProgressBar(Container cont, int index) { return(findJProgressBar(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JProgressBar instance"), index)); } /** * Searches 0'th JProgressBar in container. * @param cont Container to search component in. * @return JProgressBar instance or null if component was not found. */ public static JProgressBar findJProgressBar(Container cont) { return(findJProgressBar(cont, 0)); } /** * Waits JProgressBar in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JProgressBar instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JProgressBar waitJProgressBar(Container cont, ComponentChooser chooser, int index) { return((JProgressBar)waitComponent(cont, new JProgressBarFinder(chooser), index)); } /** * Waits 0'th JProgressBar in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JProgressBar instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JProgressBar waitJProgressBar(Container cont, ComponentChooser chooser) { return(waitJProgressBar(cont, chooser, 0)); } /** * Waits JProgressBar in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JProgressBar instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JProgressBar waitJProgressBar(Container cont, int index) { return(waitJProgressBar(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JProgressBar instance"), index)); } /** * Waits 0'th JProgressBar in container. * @param cont Container to search component in. * @return JProgressBar instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JProgressBar waitJProgressBar(Container cont) { return(waitJProgressBar(cont, 0)); } static { Timeouts.initDefault("JProgressBarOperator.WaitValueTimeout", WAIT_VALUE_TIMEOUT); } public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; super.setTimeouts(timeouts); } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } /** * Waits for criteria defined by chooser to be reached. * @param chooser an object specifying waiting criteria. * @see #waitValue(int) * @deprecated Use waitState(ComponentChooser) instead. */ public void waitValue(final ValueChooser chooser) { output.printLine("Wait \"" + chooser.getDescription() + "\" value in progressbar\n : " + toStringSource()); output.printGolden("Wait \"" + chooser.getDescription() + "\" value in progressbar"); Waiter wt = new Waiter(new Waitable() { public Object actionProduced(Object obj) { return(chooser.checkValue(((JProgressBar)getSource()).getValue()) ? "" : null); } public String getDescription() { return("\"" + chooser.getDescription() + "\" value"); } }); wt.setTimeoutsToCloneOf(timeouts, "JProgressBarOperator.WaitValueTimeout"); wt.setOutput(output.createErrorOutput()); try { wt.waitAction(null); } catch (InterruptedException e) { throw(new JemmyException("Exception during progressbar value waiting", e)); } } /** * Waits progress bar value to be less or equal to value parameter. * Can be used for typical progress bar (when value is increasing). * @param value a value to reach. * @see Operator#waitState(ComponentChooser) */ public void waitValue(final int value) { output.printLine("Wait \"" + value + "\" value in progressbar\n : " + toStringSource()); output.printGolden("Wait \"" + value + "\" value in progressbar"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(((JProgressBar)comp).getValue() >= value); } public String getDescription() { return("greater then " + Integer.toString(value)); } }); } /** * Waits progress bar string to match value parameter. * @param value a string value. * @see Operator#waitState(ComponentChooser) */ public void waitValue(final String value) { output.printLine("Wait \"" + value + "\" string in progressbar\n : " + toStringSource()); output.printGolden("Wait \"" + value + "\" string in progressbar"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(getComparator().equals(((JProgressBar)comp).getString(), value)); } public String getDescription() { return("'" + value + "' string"); } }); } public Hashtable getDump() { Hashtable result = super.getDump(); result.put(MINIMUM_DPROP, Integer.toString(((JProgressBar)getSource()).getMinimum())); result.put(MAXIMUM_DPROP, Integer.toString(((JProgressBar)getSource()).getMaximum())); result.put(VALUE_DPROP, Integer.toString(((JProgressBar)getSource()).getValue())); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JProgressBar.addChangeListener(ChangeListener) through queue*/ public void addChangeListener(final ChangeListener changeListener) { runMapping(new MapVoidAction("addChangeListener") { public void map() { ((JProgressBar)getSource()).addChangeListener(changeListener); }});} /**Maps JProgressBar.getMaximum() through queue*/ public int getMaximum() { return(runMapping(new MapIntegerAction("getMaximum") { public int map() { return(((JProgressBar)getSource()).getMaximum()); }}));} /**Maps JProgressBar.getMinimum() through queue*/ public int getMinimum() { return(runMapping(new MapIntegerAction("getMinimum") { public int map() { return(((JProgressBar)getSource()).getMinimum()); }}));} /**Maps JProgressBar.getModel() through queue*/ public BoundedRangeModel getModel() { return((BoundedRangeModel)runMapping(new MapAction("getModel") { public Object map() { return(((JProgressBar)getSource()).getModel()); }}));} /**Maps JProgressBar.getOrientation() through queue*/ public int getOrientation() { return(runMapping(new MapIntegerAction("getOrientation") { public int map() { return(((JProgressBar)getSource()).getOrientation()); }}));} /**Maps JProgressBar.getPercentComplete() through queue*/ public double getPercentComplete() { return(runMapping(new MapDoubleAction("getPercentComplete") { public double map() { return(((JProgressBar)getSource()).getPercentComplete()); }}));} /**Maps JProgressBar.getString() through queue*/ public String getString() { return((String)runMapping(new MapAction("getString") { public Object map() { return(((JProgressBar)getSource()).getString()); }}));} /**Maps JProgressBar.getUI() through queue*/ public ProgressBarUI getUI() { return((ProgressBarUI)runMapping(new MapAction("getUI") { public Object map() { return(((JProgressBar)getSource()).getUI()); }}));} /**Maps JProgressBar.getValue() through queue*/ public int getValue() { return(runMapping(new MapIntegerAction("getValue") { public int map() { return(((JProgressBar)getSource()).getValue()); }}));} /**Maps JProgressBar.isBorderPainted() through queue*/ public boolean isBorderPainted() { return(runMapping(new MapBooleanAction("isBorderPainted") { public boolean map() { return(((JProgressBar)getSource()).isBorderPainted()); }}));} /**Maps JProgressBar.isStringPainted() through queue*/ public boolean isStringPainted() { return(runMapping(new MapBooleanAction("isStringPainted") { public boolean map() { return(((JProgressBar)getSource()).isStringPainted()); }}));} /**Maps JProgressBar.removeChangeListener(ChangeListener) through queue*/ public void removeChangeListener(final ChangeListener changeListener) { runMapping(new MapVoidAction("removeChangeListener") { public void map() { ((JProgressBar)getSource()).removeChangeListener(changeListener); }});} /**Maps JProgressBar.setBorderPainted(boolean) through queue*/ public void setBorderPainted(final boolean b) { runMapping(new MapVoidAction("setBorderPainted") { public void map() { ((JProgressBar)getSource()).setBorderPainted(b); }});} /**Maps JProgressBar.setMaximum(int) through queue*/ public void setMaximum(final int i) { runMapping(new MapVoidAction("setMaximum") { public void map() { ((JProgressBar)getSource()).setMaximum(i); }});} /**Maps JProgressBar.setMinimum(int) through queue*/ public void setMinimum(final int i) { runMapping(new MapVoidAction("setMinimum") { public void map() { ((JProgressBar)getSource()).setMinimum(i); }});} /**Maps JProgressBar.setModel(BoundedRangeModel) through queue*/ public void setModel(final BoundedRangeModel boundedRangeModel) { runMapping(new MapVoidAction("setModel") { public void map() { ((JProgressBar)getSource()).setModel(boundedRangeModel); }});} /**Maps JProgressBar.setOrientation(int) through queue*/ public void setOrientation(final int i) { runMapping(new MapVoidAction("setOrientation") { public void map() { ((JProgressBar)getSource()).setOrientation(i); }});} /**Maps JProgressBar.setString(String) through queue*/ public void setString(final String string) { runMapping(new MapVoidAction("setString") { public void map() { ((JProgressBar)getSource()).setString(string); }});} /**Maps JProgressBar.setStringPainted(boolean) through queue*/ public void setStringPainted(final boolean b) { runMapping(new MapVoidAction("setStringPainted") { public void map() { ((JProgressBar)getSource()).setStringPainted(b); }});} /**Maps JProgressBar.setUI(ProgressBarUI) through queue*/ public void setUI(final ProgressBarUI progressBarUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JProgressBar)getSource()).setUI(progressBarUI); }});} /**Maps JProgressBar.setValue(int) through queue*/ public void setValue(final int i) { runMapping(new MapVoidAction("setValue") { public void map() { ((JProgressBar)getSource()).setValue(i); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Interface to define criteria for waitValue(ValueChooser) * method. * @see #waitValue(int) * @deprecated Use waitState(ComponentChooser) instead. */ public interface ValueChooser { /** * Check if criteria jave been reached. * @param value current value. * @return true if criteria reached. */ public boolean checkValue(int value); /** * A description. * @return a description. */ public String getDescription(); } /** * Checks component type. */ public static class JProgressBarFinder extends Finder { /** * Constructs JProgressBarFinder. * @param sf other searching criteria. */ public JProgressBarFinder(ComponentChooser sf) { super(JProgressBar.class, sf); } /** * Constructs JProgressBarFinder. */ public JProgressBarFinder() { super(JProgressBar.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JButtonOperator.java0000644000175000017500000002707711245712237023266 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Container; import java.util.Hashtable; import javax.swing.JButton; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.TimeoutExpiredException; /** * *

Timeouts used:
* AbstractButtonOperator.PushButtonTimeout - time between button pressing and releasing
* ComponentOperator.WaitComponentTimeout - time to wait button displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait button enabled
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JButtonOperator extends AbstractButtonOperator{ /** * Identifier for a "default button" property. * @see #getDump */ public static final String IS_DEFAULT_DPROP = "Default button"; /** * Constructor. * @param b a component */ public JButtonOperator(JButton b) { super(b); } /** * Constructs a JButtonOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JButtonOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JButton)cont. waitSubComponent(new JButtonFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JButtonOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. */ public JButtonOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JButtonOperator(ContainerOperator cont, String text, int index) { this((JButton) waitComponent(cont, new JButtonFinder(new AbstractButtonOperator. AbstractButtonByLabelFinder(text, cont.getComparator())), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JButtonOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JButtonOperator(ContainerOperator cont, int index) { this((JButton) waitComponent(cont, new JButtonFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont container * @throws TimeoutExpiredException */ public JButtonOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JButton instance or null if component was not found. */ public static JButton findJButton(Container cont, ComponentChooser chooser, int index) { return((JButton)findAbstractButton(cont, new JButtonFinder(chooser), index)); } /** * Searches 0'th JButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JButton instance or null if component was not found. */ public static JButton findJButton(Container cont, ComponentChooser chooser) { return(findJButton(cont, chooser, 0)); } /** * Searches JButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JButton instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JButton findJButton(Container cont, String text, boolean ce, boolean ccs, int index) { return(findJButton(cont, new JButtonFinder(new AbstractButtonOperator. AbstractButtonByLabelFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Searches JButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JButton instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JButton findJButton(Container cont, String text, boolean ce, boolean ccs) { return(findJButton(cont, text, ce, ccs, 0)); } /** * Waits JButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JButton instance. * @throws TimeoutExpiredException */ public static JButton waitJButton(Container cont, ComponentChooser chooser, int index) { return((JButton)waitAbstractButton(cont, new JButtonFinder(chooser), index)); } /** * Waits 0'th JButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JButton instance. * @throws TimeoutExpiredException */ public static JButton waitJButton(Container cont, ComponentChooser chooser) { return(waitJButton(cont, chooser, 0)); } /** * Waits JButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JButton instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JButton waitJButton(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitJButton(cont, new JButtonFinder(new AbstractButtonOperator. AbstractButtonByLabelFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Waits JButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JButton instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JButton waitJButton(Container cont, String text, boolean ce, boolean ccs) { return(waitJButton(cont, text, ce, ccs, 0)); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); result.remove(AbstractButtonOperator.IS_SELECTED_DPROP); result.put(IS_DEFAULT_DPROP, ((JButton)getSource()).isDefaultButton() ? "true" : "false"); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JButton.isDefaultButton() through queue*/ public boolean isDefaultButton() { return(runMapping(new MapBooleanAction("isDefaultButton") { public boolean map() { return(((JButton)getSource()).isDefaultButton()); }}));} /**Maps JButton.isDefaultCapable() through queue*/ public boolean isDefaultCapable() { return(runMapping(new MapBooleanAction("isDefaultCapable") { public boolean map() { return(((JButton)getSource()).isDefaultCapable()); }}));} /**Maps JButton.setDefaultCapable(boolean) through queue*/ public void setDefaultCapable(final boolean b) { runMapping(new MapVoidAction("setDefaultCapable") { public void map() { ((JButton)getSource()).setDefaultCapable(b); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Prepares the button to click. */ protected void prepareToClick() { makeComponentVisible(); } /** * Checks component type. */ public static class JButtonFinder extends Finder { /** * Constructs JButtonFinder. * @param sf other searching criteria. */ public JButtonFinder(ComponentChooser sf) { super(JButton.class, sf); } /** * Constructs JButtonFinder. */ public JButtonFinder() { super(JButton.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JMenuItemOperator.java0000644000175000017500000004707611245712237023537 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.Hashtable; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.KeyStroke; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.event.MenuDragMouseEvent; import javax.swing.event.MenuDragMouseListener; import javax.swing.event.MenuKeyEvent; import javax.swing.event.MenuKeyListener; import javax.swing.plaf.MenuItemUI; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.util.EmptyVisualizer; /** * *

Timeouts used:
* JMenuItemOperator.PushMenuTimeout - time between button pressing and releasing
* ComponentOperator.WaitComponentTimeout - time to wait button displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait button enabled
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JMenuItemOperator extends AbstractButtonOperator implements Timeoutable, Outputable{ private final static long PUSH_MENU_TIMEOUT = 0; private Timeouts timeouts; private TestOut output; /** * Constructor. * @param item a component */ public JMenuItemOperator(JMenuItem item) { super(item); setTimeouts(JemmyProperties.getProperties().getTimeouts()); setOutput(JemmyProperties.getProperties().getOutput()); } /** * Constructs a JMenuItemOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JMenuItemOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JMenuItem)cont. waitSubComponent(new JMenuItemFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JMenuItemOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JMenuItemOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JMenuItemOperator(ContainerOperator cont, String text, int index) { this((JMenuItem)waitComponent(cont, new JMenuItemByLabelFinder(text, cont.getComparator()), index)); setTimeouts(cont.getTimeouts()); setOutput(cont.getOutput()); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JMenuItemOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JMenuItemOperator(ContainerOperator cont, int index) { this((JMenuItem) waitComponent(cont, new JMenuItemFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JMenuItemOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JMenuItem in container. * @param menu Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JMenuItem instance or null if component was not found. */ public static JMenuItem findJMenuItem(Container menu, ComponentChooser chooser, int index) { return((JMenuItem)findComponent(menu, new JMenuItemFinder(chooser), index)); } /** * Searches 0'th JMenuItem in container. * @param menu Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JMenuItem instance or null if component was not found. */ public static JMenuItem findJMenuItem(Container menu, ComponentChooser chooser) { return(findJMenuItem(menu, chooser, 0)); } /** * Searches JMenuItem by text. * @param menu Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JMenuItem instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JMenuItem findJMenuItem(Container menu, String text, boolean ce, boolean ccs, int index) { return(findJMenuItem(menu, new JMenuItemByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches JMenuItem by text. * @param menu Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JMenuItem instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JMenuItem findJMenuItem(Container menu, String text, boolean ce, boolean ccs) { return(findJMenuItem(menu, text, ce, ccs, 0)); } /** * Waits JMenuItem in container. * @param menu Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JMenuItem instance. * @throws TimeoutExpiredException */ public static JMenuItem waitJMenuItem(Container menu, ComponentChooser chooser, int index) { return((JMenuItem)waitComponent(menu, new JMenuItemFinder(chooser), index)); } /** * Waits 0'th JMenuItem in container. * @param menu Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JMenuItem instance. * @throws TimeoutExpiredException */ public static JMenuItem waitJMenuItem(Container menu, ComponentChooser chooser) { return(waitJMenuItem(menu, chooser, 0)); } /** * Waits JMenuItem by text. * @param menu Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JMenuItem instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JMenuItem waitJMenuItem(Container menu, String text, boolean ce, boolean ccs, int index) { return(waitJMenuItem(menu, new JMenuItemByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits JMenuItem by text. * @param menu Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JMenuItem instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JMenuItem waitJMenuItem(Container menu, String text, boolean ce, boolean ccs) { return(waitJMenuItem(menu, text, ce, ccs, 0)); } static { Timeouts.initDefault("JMenuItemOperator.PushMenuTimeout", PUSH_MENU_TIMEOUT); } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { super.setOutput(out); output = out; } public TestOut getOutput() { return(output); } public Hashtable getDump() { Hashtable result = super.getDump(); result.remove(AbstractButtonOperator.IS_SELECTED_DPROP); return(result); } /** Push this menu item. */ public void push() { setVisualizer(new EmptyVisualizer()); super.push(); } /** Push this menu item and no block further execution. */ public void pushNoBlock() { setVisualizer(new EmptyVisualizer()); super.pushNoBlock(); } //////////////////////////////////////////////////////// //Mapping // /**Maps JMenuItem.addMenuDragMouseListener(MenuDragMouseListener) through queue*/ public void addMenuDragMouseListener(final MenuDragMouseListener menuDragMouseListener) { runMapping(new MapVoidAction("addMenuDragMouseListener") { public void map() { ((JMenuItem)getSource()).addMenuDragMouseListener(menuDragMouseListener); }});} /**Maps JMenuItem.addMenuKeyListener(MenuKeyListener) through queue*/ public void addMenuKeyListener(final MenuKeyListener menuKeyListener) { runMapping(new MapVoidAction("addMenuKeyListener") { public void map() { ((JMenuItem)getSource()).addMenuKeyListener(menuKeyListener); }});} /**Maps JMenuItem.getAccelerator() through queue*/ public KeyStroke getAccelerator() { return((KeyStroke)runMapping(new MapAction("getAccelerator") { public Object map() { return(((JMenuItem)getSource()).getAccelerator()); }}));} /**Maps JMenuItem.getComponent() through queue*/ public Component getComponent() { return((Component)runMapping(new MapAction("getComponent") { public Object map() { return(((JMenuItem)getSource()).getComponent()); }}));} /**Maps JMenuItem.getSubElements() through queue*/ public MenuElement[] getSubElements() { return((MenuElement[])runMapping(new MapAction("getSubElements") { public Object map() { return(((JMenuItem)getSource()).getSubElements()); }}));} /**Maps JMenuItem.isArmed() through queue*/ public boolean isArmed() { return(runMapping(new MapBooleanAction("isArmed") { public boolean map() { return(((JMenuItem)getSource()).isArmed()); }}));} /**Maps JMenuItem.menuSelectionChanged(boolean) through queue*/ public void menuSelectionChanged(final boolean b) { runMapping(new MapVoidAction("menuSelectionChanged") { public void map() { ((JMenuItem)getSource()).menuSelectionChanged(b); }});} /**Maps JMenuItem.processKeyEvent(KeyEvent, MenuElement[], MenuSelectionManager) through queue*/ public void processKeyEvent(final KeyEvent keyEvent, final MenuElement[] menuElement, final MenuSelectionManager menuSelectionManager) { runMapping(new MapVoidAction("processKeyEvent") { public void map() { ((JMenuItem)getSource()).processKeyEvent(keyEvent, menuElement, menuSelectionManager); }});} /**Maps JMenuItem.processMenuDragMouseEvent(MenuDragMouseEvent) through queue*/ public void processMenuDragMouseEvent(final MenuDragMouseEvent menuDragMouseEvent) { runMapping(new MapVoidAction("processMenuDragMouseEvent") { public void map() { ((JMenuItem)getSource()).processMenuDragMouseEvent(menuDragMouseEvent); }});} /**Maps JMenuItem.processMenuKeyEvent(MenuKeyEvent) through queue*/ public void processMenuKeyEvent(final MenuKeyEvent menuKeyEvent) { runMapping(new MapVoidAction("processMenuKeyEvent") { public void map() { ((JMenuItem)getSource()).processMenuKeyEvent(menuKeyEvent); }});} /**Maps JMenuItem.processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager) through queue*/ public void processMouseEvent(final MouseEvent mouseEvent, final MenuElement[] menuElement, final MenuSelectionManager menuSelectionManager) { runMapping(new MapVoidAction("processMouseEvent") { public void map() { ((JMenuItem)getSource()).processMouseEvent(mouseEvent, menuElement, menuSelectionManager); }});} /**Maps JMenuItem.removeMenuDragMouseListener(MenuDragMouseListener) through queue*/ public void removeMenuDragMouseListener(final MenuDragMouseListener menuDragMouseListener) { runMapping(new MapVoidAction("removeMenuDragMouseListener") { public void map() { ((JMenuItem)getSource()).removeMenuDragMouseListener(menuDragMouseListener); }});} /**Maps JMenuItem.removeMenuKeyListener(MenuKeyListener) through queue*/ public void removeMenuKeyListener(final MenuKeyListener menuKeyListener) { runMapping(new MapVoidAction("removeMenuKeyListener") { public void map() { ((JMenuItem)getSource()).removeMenuKeyListener(menuKeyListener); }});} /**Maps JMenuItem.setAccelerator(KeyStroke) through queue*/ public void setAccelerator(final KeyStroke keyStroke) { runMapping(new MapVoidAction("setAccelerator") { public void map() { ((JMenuItem)getSource()).setAccelerator(keyStroke); }});} /**Maps JMenuItem.setArmed(boolean) through queue*/ public void setArmed(final boolean b) { runMapping(new MapVoidAction("setArmed") { public void map() { ((JMenuItem)getSource()).setArmed(b); }});} /**Maps JMenuItem.setUI(MenuItemUI) through queue*/ public void setUI(final MenuItemUI menuItemUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JMenuItem)getSource()).setUI(menuItemUI); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Prepares the button to click. */ protected void prepareToClick() { output.printLine("Push menu item\n :" + toStringSource()); output.printGolden("Push menu item"); Timeouts times = timeouts.cloneThis(); times.setTimeout("AbstractButtonOperator.PushButtonTimeout", timeouts.getTimeout("JMenuItemOperator.PushMenuTimeout")); super.setTimeouts(times); super.setOutput(output.createErrorOutput()); } static JMenuItemOperator[] getMenuItems(Object[] elements, Operator env) { int size = 0; for(int i = 0; i < elements.length; i++) { if(elements[i] instanceof JMenuItem) { size++; } } JMenuItemOperator[] result = new JMenuItemOperator[size]; int index = 0; for(int i = 0; i < elements.length; i++) { if(elements[i] instanceof JMenuItem) { result[index] = new JMenuItemOperator((JMenuItem)elements[i]); result[index].copyEnvironment(env); index++; } } return(result); } static JMenuItemOperator[] getMenuItems(MenuElement parent, Operator env) { return(getMenuItems(parent.getSubElements(), env)); } static JMenuItemOperator[] getMenuItems(JMenu parent, Operator env) { return(getMenuItems(parent.getMenuComponents(), env)); } static ComponentChooser[] createChoosers(String[] names, StringComparator comparator) { ComponentChooser[] choosers = new ComponentChooser[names.length]; for(int i = 0; i < choosers.length; i++) { choosers[i] = new JMenuItemOperator.JMenuItemByLabelFinder(names[i], comparator); } return(choosers); } /** * Allows to find component by text. */ public static class JMenuItemByLabelFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs JMenuItemByLabelFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public JMenuItemByLabelFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs JMenuItemByLabelFinder. * @param lb a text pattern */ public JMenuItemByLabelFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JMenuItem) { if(((JMenuItem)comp).getText() != null) { return(comparator.equals(((JMenuItem)comp).getText(), label)); } } return(false); } public String getDescription() { return("JMenuItem with text \"" + label + "\""); } } /** * Checks component type. */ public static class JMenuItemFinder extends Finder { /** * Constructs JMenuItemFinder. * @param sf other searching criteria. */ public JMenuItemFinder(ComponentChooser sf) { super(JMenuItem.class, sf); } /** * Constructs JMenuItemFinder. */ public JMenuItemFinder() { super(JMenuItem.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JTreeOperator.java0000644000175000017500000026612011245712447022707 0ustar tonytony/* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.util.Enumeration; import java.util.Hashtable; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionListener; import javax.swing.event.TreeWillExpandListener; import javax.swing.plaf.TreeUI; import javax.swing.tree.ExpandVetoException; import javax.swing.tree.TreeCellEditor; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyInputException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.Waitable; import org.netbeans.jemmy.Waiter; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.TreeDriver; import org.netbeans.jemmy.util.EmptyVisualizer; /** *

Timeouts used:
* JTreeOperator.WaitNodeExpandedTimeout - time to wait node expanded
* JTreeOperator.WaitNodeCollapsedTimeout - time to wait node collapsed
* JTreeOperator.WaitAfterNodeExpandedTimeout - time to to sleep after node expanded
* JTreeOperator.WaitNextNodeTimeout - time to wait next node displayed
* JTreeOperator.WaitNodeVisibleTimeout - time to wait node visible
* JTreeOperator.BeforeEditTimeout - time to sleep before edit click
* JTreeOperator.WaitEditingTimeout - time to wait node editing
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.WaitStateTimeout - time to wait for path to be expanded, collapsed, selected, * time to wait for a text in a row
* WindowWaiter.WaitWindowTimeout - time to wait popup window displayed
* JScrollBarOperator.WholeScrollTimeout - time for the whole scrolling
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JTreeOperator extends JComponentOperator implements Timeoutable, Outputable{ /** * Identifier for a "root" property. * @see #getDump */ public static final String ROOT_DPROP = "Root"; /** * Identifier for a "node" properties. * @see #getDump */ public static final String NODE_PREFIX_DPROP = "Node"; /** * Identifier for a "first selected" property. * @see #getDump */ public static final String SELECTION_FIRST_DPROP = "First selected"; /** * Identifier for a "last selected" property. * @see #getDump */ public static final String SELECTION_LAST_DPROP = "Last selected"; private final static long WAIT_NODE_EXPANDED_TIMEOUT = 60000; private final static long WAIT_NODE_COLLAPSED_TIMEOUT = 60000; private final static long WAIT_AFTER_NODE_EXPANDED_TIMEOUT = 0; private final static long WAIT_NEXT_NODE_TIMEOUT = 60000; private final static long WAIT_NODE_VISIBLE_TIMEOUT = 60000; private final static long BEFORE_EDIT_TIMEOUT = 1000; private final static long WAIT_EDITING_TIMEOUT = 60000; private TestOut output; private Timeouts timeouts; private TreeDriver driver; /** * Constructor. * @param b a component */ public JTreeOperator(JTree b) { super(b); driver = DriverManager.getTreeDriver(getClass()); } /** * Constructs a JTreeOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JTreeOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JTree)cont. waitSubComponent(new JTreeFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JTreeOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JTreeOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of a row which is currently selected. * @param row a row index to check text in. If equals to -1, selected row is checked. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTreeOperator(ContainerOperator cont, String text, int row, int index) { this((JTree)waitComponent(cont, new JTreeByItemFinder(text, row, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of a row which is currently selected. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTreeOperator(ContainerOperator cont, String text, int index) { this(cont, text, -1, index); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of a row which is currently selected. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTreeOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JTreeOperator(ContainerOperator cont, int index) { this((JTree) waitComponent(cont, new JTreeFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JTreeOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JTree in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JTree instance or null if component was not found. */ public static JTree findJTree(Container cont, ComponentChooser chooser, int index) { return((JTree)findComponent(cont, new JTreeFinder(chooser), index)); } /** * Searches 0'th JTree in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JTree instance or null if component was not found. */ public static JTree findJTree(Container cont, ComponentChooser chooser) { return(findJTree(cont, chooser, 0)); } /** * Searches JTree by item. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param rowIndex Index of row to compare text. If -1, selected row is checked. * @param index Ordinal component index. * @return JTree instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTree findJTree(Container cont, String text, boolean ce, boolean ccs, int rowIndex, int index) { return(findJTree(cont, new JTreeByItemFinder(text, rowIndex, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches JTree by item. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param rowIndex Index of row to compare text. If -1, selected row is checked. * @return JTree instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTree findJTree(Container cont, String text, boolean ce, boolean ccs, int rowIndex) { return(findJTree(cont, text, ce, ccs, rowIndex, 0)); } /** * Waits JTree in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JTree instance or null if component was not found. * @throws TimeoutExpiredException */ public static JTree waitJTree(Container cont, ComponentChooser chooser, int index) { return((JTree)waitComponent(cont, new JTreeFinder(chooser), index)); } /** * Waits 0'th JTree in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JTree instance or null if component was not found. * @throws TimeoutExpiredException */ public static JTree waitJTree(Container cont, ComponentChooser chooser) { return(waitJTree(cont, chooser, 0)); } /** * Waits JTree by item. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param rowIndex Index of row to compare text. If -1, selected row is checked. * @param index Ordinal component index. * @return JTree instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JTree waitJTree(Container cont, String text, boolean ce, boolean ccs, int rowIndex, int index) { return(waitJTree(cont, new JTreeByItemFinder(text, rowIndex, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits JTree by item. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param rowIndex Index of row to compare text. If -1, selected row is checked. * @return JTree instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JTree waitJTree(Container cont, String text, boolean ce, boolean ccs, int rowIndex) { return(waitJTree(cont, text, ce, ccs, rowIndex, 0)); } static { Timeouts.initDefault("JTreeOperator.WaitNodeExpandedTimeout", WAIT_NODE_EXPANDED_TIMEOUT); Timeouts.initDefault("JTreeOperator.WaitNodeCollapsedTimeout", WAIT_NODE_COLLAPSED_TIMEOUT); Timeouts.initDefault("JTreeOperator.WaitAfterNodeExpandedTimeout", WAIT_AFTER_NODE_EXPANDED_TIMEOUT); Timeouts.initDefault("JTreeOperator.WaitNextNodeTimeout", WAIT_NEXT_NODE_TIMEOUT); Timeouts.initDefault("JTreeOperator.WaitNodeVisibleTimeout", WAIT_NODE_VISIBLE_TIMEOUT); Timeouts.initDefault("JTreeOperator.BeforeEditTimeout", BEFORE_EDIT_TIMEOUT); Timeouts.initDefault("JTreeOperator.WaitEditingTimeout", WAIT_EDITING_TIMEOUT); } public void setTimeouts(Timeouts times) { this.timeouts = times; super.setTimeouts(timeouts); } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (TreeDriver)DriverManager. getDriver(DriverManager.TREE_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Expands path. * @param path a path to be expanded. * @throws TimeoutExpiredException */ public void doExpandPath(TreePath path) { if(path != null) { output.printLine("Expanding \"" + path.getPathComponent(path.getPathCount() - 1).toString() + "\" node"); output.printGolden("Expanding \"" + path.getPathComponent(path.getPathCount() - 1).toString() + "\" node"); driver.expandItem(this, getRowForPath(path)); waitExpanded(path); } else { throw(new NoSuchPathException()); } } /** * Expands path on row. * @param row a row index to be expanded. * @throws TimeoutExpiredException */ public void doExpandRow(int row) { output.printLine("Expanding " + Integer.toString(row) + " row"); output.printGolden("Expanding " + Integer.toString(row) + " row"); driver.expandItem(this, row); waitExpanded(row); } /** * Ensures that the node identified by path is currently viewable. * @param path a path to be made visible. * @throws TimeoutExpiredException */ public void doMakeVisible(TreePath path) { if(path != null) { output.printLine("Making \"" + path.toString() + "\" path visible"); output.printGolden("Making path visible"); makeVisible(path); waitVisible(path); } else { throw(new NoSuchPathException()); } } /** * Returns number of child. * @param node a node to count children of. * @return a number of children. */ public int getChildCount(final Object node) { return runMapping(new MapIntegerAction("getChildCount") { public int map() { return ((JTree)getSource()).getModel().getChildCount(node); } }); } /** * Returns node children. * @param node a node to get children of. * @return an array of node children. */ public Object[] getChildren(final Object node) { return (Object[]) runMapping(new MapAction("getChildren") { public Object map() { TreeModel md = ((JTree) getSource()).getModel(); Object[] result = new Object[md.getChildCount(node)]; for (int i = 0; i < md.getChildCount(node); i++) { result[i] = md.getChild(node, i); } return result; } }); } /** * Returns node child. * @param node a node to get a child of. * @param index a child index. * @return a node child. */ public Object getChild(final Object node, final int index) { return runMapping(new MapAction("getChild") { public Object map() { return ((JTree)getSource()).getModel().getChild(node, index); } }); } /** * Returns number of child. * @param path a path indicating a node to count children of. * @return a number of children. */ public int getChildCount(TreePath path) { if(path != null) { return(getChildCount(path. getLastPathComponent())); } else { throw(new NoSuchPathException()); } } /** * Constructs new path from a path and index's subnode of it last node. * @param path a path indicating a node to get a child of. * @param index a child node index. * @return a number of children. */ public TreePath getChildPath(TreePath path, int index) { if(path != null) { return(path. pathByAddingChild(getChild(path. getLastPathComponent(), index))); } else { throw(new NoSuchPathException()); } } /** * Constructs new paths from a path and all subnodes of it last node. * @param path a path indicating a node to get children of. * @return a number of children. */ public TreePath[] getChildPaths(TreePath path) { if(path != null) { Object[] children = getChildren(path. getLastPathComponent()); TreePath[] result = new TreePath[children.length]; for(int i = 0; i < children.length; i++) { result[i] = path. pathByAddingChild(children[i]); } return(result); } else { throw(new NoSuchPathException()); } } /** * Returns the root of the tree. * @return tree root. * @throws TimeoutExpiredException */ public Object getRoot() { Waiter rootWaiter = new Waiter(new Waitable() { public Object actionProduced(Object obj) { Object root = ((TreeModel)getModel()).getRoot(); if(root == null || root.toString() == null || root.toString().equals("null")) { return(null); } else { return(root); } } public String getDescription() { return("Wait root node"); } }); rootWaiter.setTimeoutsToCloneOf(timeouts, "JTreeOperator.WaitNodeVisibleTimeout"); rootWaiter.setOutput(output.createErrorOutput()); try { return(rootWaiter.waitAction(null)); } catch(InterruptedException e) { output.printStackTrace(e); return(null); } } /** * Searches path in tree. * @param chooser TreePathChooser implementation. * @return a path fitting the criteria. * @see TreePathChooser * @see #findPath * @throws TimeoutExpiredException */ public TreePath findPath(TreePathChooser chooser) { output.printLine("Search for a tree path " + chooser.getDescription()); output.printGolden("Search for a tree path"); TreePath rootPath = new TreePath(getRoot()); if(chooser.checkPath(rootPath, 0)) { return(rootPath); } Waiter loadedWaiter = new Waiter(new Waitable() { // fields used in getDescription() method TreePath currentPath; String requestedPath; public Object actionProduced(Object obj) { TreePathChooser chsr = (TreePathChooser)((Object[])obj)[0]; requestedPath = chsr.getDescription(); TreePath path = (TreePath)((Object[])obj)[1]; currentPath = path; Object[] result = new Object[2]; Object[] children = getChildren(path.getLastPathComponent()); for(int j = 0; j < children.length; j++) { result[0] = path.pathByAddingChild(children[j]); if(chsr.checkPath((TreePath)result[0], j)) { result[1] = Boolean.TRUE; return(result); } if(chsr.hasAsParent((TreePath)result[0], j)) { result[1] = Boolean.FALSE; return(result); } } return(null); } public String getDescription() { return "Wait next node loaded under parent "+currentPath+ " when requested was "+requestedPath; } }); loadedWaiter.setTimeoutsToCloneOf(timeouts, "JTreeOperator.WaitNextNodeTimeout"); loadedWaiter.setOutput(output.createErrorOutput()); return(findPathPrimitive(rootPath, chooser, loadedWaiter)); } /** * Searches index'th row by row chooser. * @param chooser a path searching criteria. * @param index a child index. * @return Row index or -1 if search was insuccessful. * @see JTreeOperator.TreeRowChooser */ public int findRow(TreeRowChooser chooser, int index) { int count = 0; for(int i = 0; i < getRowCount(); i++) { if(chooser.checkRow(this, i)) { if(count == index) { return(i); } else { count++; } } } return(-1); } /** * Searches a row by row chooser. * @param chooser a path searching criteria. * @return Row index or -1 if search was insuccessful. * @see JTreeOperator.TreeRowChooser */ public int findRow(TreeRowChooser chooser) { return(findRow(chooser, 0)); } /** * Searches index'th row by substring. * @param item Substring. * @param comparator a string comparision algorithm * @param index an ordinal row index between ones matching the criteria * @return Row index or -1 if search was insuccessful. */ public int findRow(String item, StringComparator comparator, int index){ return(findRow(new BySubStringTreeRowChooser(item, comparator), index)); } /** * Searches index'th row by substring. * @param item Substring. * @param ce Compare exactly * @param cc Compare case sensitivelly. * @param index an ordinal row index between ones matching the criteria * @return Row index or -1 if search was insuccessful. * @deprecated Use findRow(String, int) or findRow(String, StringComparator, int) */ public int findRow(String item, boolean ce, boolean cc, int index){ return(findRow(item, new DefaultStringComparator(ce, cc), index)); } /** * Searches index'th row by substring. * Uses StringComparator assigned to this object. * @param item Substring. * @param index an ordinal row index between ones matching the criteria * @return Row index or -1 if search was insuccessful. */ public int findRow(String item, int index){ return(findRow(item, getComparator(), index)); } /** * Searches a row by substring. * @param item Substring. * @param comparator a string comparision algorithm * @return Row index or -1 if search was insuccessful. */ public int findRow(String item, StringComparator comparator){ return(findRow(item, comparator, 0)); } /** * Searches a row by substring. * @param item Substring. * @param ce Compare exactly * @param cc Compare case sensitivelly. * @return Row index or -1 if search was insuccessful. * @deprecated Use findRow(String) or findRow(String, StringComparator) */ public int findRow(String item, boolean ce, boolean cc) { return(findRow(item, ce, cc, 0)); } /** * Searches a row by substring. * Uses StringComparator assigned to this object. * @param item Substring. * @return Row index or -1 if search was insuccessful. */ public int findRow(String item){ return(findRow(item, getComparator(), 0)); } /** * Searches index'th row by rendered component. * @param chooser Component checking object. * @param index an ordinal row index between ones matching the criteria * @return Row index or -1 if search was insuccessful. */ public int findRow(ComponentChooser chooser, int index) { return(findRow(new ByRenderedComponentTreeRowChooser(chooser), index)); } /** * Searches a row by rendered component. * @param chooser Component checking object. * @return Row index or -1 if search was insuccessful. */ public int findRow(ComponentChooser chooser) { return(findRow(chooser, 0)); } /** * Searches path in tree. * Can be used to find one of the nodes with the same text. * Example:
*
     * root
     * +-+node
     * | +--subnode
     * +-+node
     * | +--subnode
     * | +--subnode
     * ...
     * String[] names = {"node", "subnode"};
* int[] indexes = {1, 0};
*
* TreePath path = findPath(names, indexes, true, true);
* "path" will points to the second (from the top) "subnode" node. * @param names Node texts array. * @param indexes Nodes indexes. * @param comparator a string comparision algorithm * @return a tree path matching the criteria * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see #findPath * @throws TimeoutExpiredException */ public TreePath findPath(String[] names, int[] indexes, StringComparator comparator) { return(findPath(new StringArrayPathChooser(names, indexes, comparator))); } /** * Searches path in tree. * Can be used to find one of the nodes with the same text. * Example:
*
     * root
     * +-+node
     * | +--subnode
     * +-+node
     * | +--subnode
     * | +--subnode
     * ...
     * String[] names = {"node", "subnode"};
* int[] indexes = {1, 0};
*
* TreePath path = findPath(names, indexes, true, true);
* "path" will points to the second (from the top) "subnode" node. * @param names Node texts array. * @param indexes Nodes indexes. * @param ce Compare exactly. * @param ccs Compare case sensitively. * @return a tree path matching the criteria * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see #findPath * @throws TimeoutExpiredException * @deprecated Use findPath(String[], int[]) or findCellRow(String[], int[], StringComparator) */ public TreePath findPath(String[] names, int[] indexes, boolean ce, boolean ccs) { return(findPath(names, indexes, new DefaultStringComparator(ce, ccs))); } /** * Searches path in tree. * Uses StringComparator assigned to this object. * @param names Node texts array. * @param indexes Nodes indexes. * @return a tree path matching the criteria * @see #findPath * @throws TimeoutExpiredException */ public TreePath findPath(String[] names, int[] indexes) { return(findPath(names, indexes, getComparator())); } /** * Searches path in tree. * @param names Node texts array. * @param comparator a string comparision algorithm * @return a tree path matching the criteria * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see #findPath * @throws TimeoutExpiredException */ public TreePath findPath(String[] names, StringComparator comparator) { int[] indexes = new int[0]; return(findPath(names, indexes, comparator)); } /** * Searches path in tree. * @param names Node texts array. * @param ce Compare exactly. * @param ccs Compare case sensitively. * @return a tree path matching the criteria * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see #findPath * @throws TimeoutExpiredException * @deprecated Use findPath(String[]) or findCellRow(String[], StringComparator) */ public TreePath findPath(String[] names, boolean ce, boolean ccs) { int[] indexes = new int[0]; return(findPath(names, indexes, ce, ccs)); } /** * Searches path in tree. * Uses StringComparator assigned to this object. * @param names Node texts array. * @return a tree path matching the criteria * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see #findPath * @throws TimeoutExpiredException */ public TreePath findPath(String[] names) { int[] indexes = new int[0]; return(findPath(names, indexes, getComparator())); } /** * Searches path in tree. * @param path String representing tree path. * Path components should be devided by "delim" parameter. * @param indexes String representing indexes to search path components. * Indexes should be devided by "delim" parameter. * @param delim Path components delimiter. * @param comparator a string comparision algorithm * @return a tree path matching the criteria * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see #findPath * @throws TimeoutExpiredException */ public TreePath findPath(String path, String indexes, String delim, StringComparator comparator) { String[] indexStrings = parseString(indexes, delim); int[] indInts = new int[indexStrings.length]; for(int i = 0; i < indexStrings.length; i++) { indInts[i] = Integer.parseInt(indexStrings[i]); } return(findPath(parseString(path, delim), indInts, comparator)); } /** * Searches path in tree. * @param path String representing tree path. * Path components should be devided by "delim" parameter. * @param indexes String representing indexes to search path components. * Indexes should be devided by "delim" parameter. * @param delim Path components delimiter. * @param ce Compare exactly. * @param ccs Compare case sensitively. * @return a tree path matching the criteria * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see #findPath * @throws TimeoutExpiredException * @deprecated Use findPath(String, String, String) or findCellRow(String, String, String, StringComparator) */ public TreePath findPath(String path, String indexes, String delim, boolean ce, boolean ccs) { return(findPath(path, indexes, delim, new DefaultStringComparator(ce, ccs))); } /** * Searches path in tree. * Uses StringComparator assigned to this object. * @param path String representing tree path. * Path components should be devided by "delim" parameter. * @param indexes String representing indexes to search path components. * Indexes should be devided by "delim" parameter. * @param delim Path components delimiter. * @return a tree path matching the criteria * @see #findPath * @throws TimeoutExpiredException */ public TreePath findPath(String path, String indexes, String delim) { return(findPath(path, indexes, delim, getComparator())); } /** * Searches path in tree. * @param path String representing tree path. * Path components should be devided by "delim" parameter. * @param delim Path components delimiter. * @param comparator a string comparision algorithm * @return a tree path matching the criteria * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see #findPath * @throws TimeoutExpiredException */ public TreePath findPath(String path, String delim, StringComparator comparator) { return(findPath(parseString(path, delim), comparator)); } /** * Searches path in tree. * @param path String representing tree path. * @param comparator a string comparision algorithm * @return a tree path matching the criteria * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see #findPath * @throws TimeoutExpiredException */ public TreePath findPath(String path, StringComparator comparator) { return(findPath(parseString(path), comparator)); } /** * Searches path in tree. * @param path String representing tree path. * Path components should be devided by "delim" parameter. * @param delim Path components delimiter. * @param ce Compare exactly. * @param ccs Compare case sensitively. * @return a tree path matching the criteria * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see #findPath * @throws TimeoutExpiredException * @deprecated Use findPath(String, String) or findCellRow(String, String, StringComparator) */ public TreePath findPath(String path, String delim, boolean ce, boolean ccs) { return(findPath(parseString(path, delim), ce, ccs)); } /** * Searches path in tree. * Uses StringComparator assigned to this object. * @param path String representing tree path. * Path components should be devided by "delim" parameter. * @param delim Path components delimiter. * @return a tree path matching the criteria * @see #findPath * @throws TimeoutExpiredException */ public TreePath findPath(String path, String delim) { return(findPath(parseString(path, delim))); } /** * Searches path in tree. * Uses StringComparator assigned to this object. * Uses PathParser assigned to this object. * @param path String representing tree path. * @return a tree path matching the criteria * @see #findPath * @throws TimeoutExpiredException */ public TreePath findPath(String path) { return(findPath(parseString(path))); } /** * Ensures that the node identified by the specified path is collapsed and viewable. * @param path a path to collapse. * @throws TimeoutExpiredException */ public void doCollapsePath(TreePath path) { if(path != null) { output.printLine("Collapsing \"" + path.toString() + "\" path"); output.printGolden("Collapsing path"); driver.collapseItem(this, getRowForPath(path)); if(getVerification()) { waitCollapsed(path); } } else { throw(new NoSuchPathException()); } } /** * Ensures that the node in the specified row is collapsed. * @param row a row index to collapse. * @throws TimeoutExpiredException */ public void doCollapseRow(int row) { output.printLine("Collapsing \"" + Integer.toString(row) + "\" row"); output.printGolden("Collapsing path"); driver.collapseItem(this, row); if(getVerification()) { waitCollapsed(row); } } /** * Selects the path. * @param path a path to select. */ public void selectPath(final TreePath path) { if(path != null) { output.printLine("Selecting \"" + path.toString() + "\" path"); output.printGolden("Selecting path"); scrollToPath(path); getQueueTool().invokeSmoothly(new QueueTool.QueueAction("Path selecting") { public Object launch() { driver.selectItem(JTreeOperator.this, getRowForPath(path)); return(null); } }); if(getVerification()) { waitSelected(path); } } else { throw(new NoSuchPathException()); } } /** * Selects the node in the specified row. * @param row an index of row to select. */ public void selectRow(int row) { output.printLine("Collapsing \"" + Integer.toString(row) + "\" row"); output.printGolden("Collapsing path"); driver.selectItem(this, row); if(getVerification()) { waitSelected(row); } } /** * Selects some pathes. * If verification mode is on, checks that right paths have been selected. * @param paths a paths to select. */ public void selectPaths(TreePath[] paths) { output.printLine("Selecting paths:"); int[] rows = new int[paths.length]; for(int i = 0; i < paths.length; i++) { output.printLine(" " + paths[i].toString()); rows[i] = getRowForPath(paths[i]); } output.printGolden("Selecting paths"); driver.selectItems(this, rows); if(getVerification()) { waitSelected(paths); } } /** * Retuns points which can be used to click on path. * @param path a tree path to click on. * @return a Point in component's coordinate system. */ public Point getPointToClick(TreePath path) { if(path != null) { Rectangle rect = getPathBounds(path); if(rect != null) { return(new Point((int)(rect.getX() + rect.getWidth() / 2), (int)(rect.getY() + rect.getHeight() / 2))); } else { throw(new NoSuchPathException(path)); } } else { throw(new NoSuchPathException()); } } /** * Retuns points which can be used to click on path. * @param row a row index to click on. * @return a Point in component's coordinate system. */ public Point getPointToClick(int row) { Rectangle rect = getRowBounds(row); if(rect != null) { return(new Point((int)(rect.getX() + rect.getWidth() / 2), (int)(rect.getY() + rect.getHeight() / 2))); } else { throw(new NoSuchPathException(row)); } } /** * Clicks on the node. * @param path a path to click on. * @param clickCount a number of clicks * @param mouseButton InputEvent.BUTTON1/2/3_MASK value * @param modifiers Combination of InputEvent.*_MASK values * @throws TimeoutExpiredException */ public void clickOnPath(TreePath path, int clickCount, int mouseButton, int modifiers) { if(path != null) { output.printLine("Click on \"" + path.toString() + "\" path"); output.printGolden("Click on path"); makeComponentVisible(); if(path.getParentPath() != null) { expandPath(path.getParentPath()); } makeVisible(path); scrollToPath(path); Point point = getPointToClick(path); clickMouse((int)point.getX(), (int)point.getY(), clickCount, mouseButton, modifiers); } else { throw(new NoSuchPathException()); } } /** * Clicks on the node. * @param path a path to click on. * @param clickCount a number of clicks * @param mouseButton InputEvent.BUTTON1/2/3_MASK value * @throws TimeoutExpiredException */ public void clickOnPath(TreePath path, int clickCount, int mouseButton) { clickOnPath(path, clickCount, mouseButton, 0); } /** * Clicks on the node. * @param path a path to click on. * @param clickCount a number of clicks * @throws TimeoutExpiredException */ public void clickOnPath(TreePath path, int clickCount) { clickOnPath(path, clickCount, getDefaultMouseButton()); } /** * Clicks on the node. * @param path a path to click on. * @throws TimeoutExpiredException */ public void clickOnPath(TreePath path) { clickOnPath(path, 1); } /** * Calls popup on the specified pathes. * @param paths an array of paths to select before invoking popup on one of them * @param mouseButton a mouse button tused to call popup. * @return an opened popup menu. * @throws TimeoutExpiredException */ public JPopupMenu callPopupOnPaths(TreePath[] paths, int mouseButton) { if(paths.length == 1) { output.printLine("Call popup on \"" + paths[0].toString() + "\" path"); output.printGolden("Call popup on path"); } else { output.printLine("Call popup on some pathes:"); for(int i = 0; i < paths.length; i++) { output.printLine(" " + paths[i].toString()); } output.printGolden("Call popup on paths"); } makeComponentVisible(); for(int i = 0; i < paths.length; i++) { if(paths[i].getParentPath() != null) { expandPath(paths[i].getParentPath()); } } selectPaths(paths); scrollToPath(paths[paths.length - 1]); Point point = getPointToClick(paths[paths.length - 1]); return(JPopupMenuOperator.callPopup(this, (int)point.getX(), (int)point.getY(), mouseButton)); } /** * Calls popup on the specified pathes. * @param paths an array of paths to select before invoking popup on one of them * @return an opened popup menu. * @throws TimeoutExpiredException */ public JPopupMenu callPopupOnPaths(TreePath[] paths) { return(callPopupOnPaths(paths, getPopupMouseButton())); } /** * Calls popup on the specified path. * @param path a path to invoking popup on. * @param mouseButton a mouse button tused to call popup. * @return an opened popup menu. * @throws TimeoutExpiredException */ public JPopupMenu callPopupOnPath(TreePath path, int mouseButton) { if(path != null) { TreePath[] paths = {path}; return(callPopupOnPaths(paths, mouseButton)); } else { throw(new NoSuchPathException()); } } /** * Calls popup on the specified path. * @param path a path to invoking popup on. * @return an opened popup menu. * @throws TimeoutExpiredException */ public JPopupMenu callPopupOnPath(TreePath path) { return(callPopupOnPath(path, getPopupMouseButton())); } /** * Scrolls to a path if the tree is on a JScrollPane component. * @param path a tree path to scroll to. */ public void scrollToPath(TreePath path) { if(path != null) { output.printTrace("Scroll JTree to path \"" + path.toString() + "\"\n : " + toStringSource()); output.printGolden("Scroll JTree to path \"" + path.toString() + "\""); makeComponentVisible(); //try to find JScrollPane under. JScrollPane scroll = (JScrollPane)getContainer(new JScrollPaneOperator. JScrollPaneFinder(ComponentSearcher. getTrueChooser("JScrollPane"))); if(scroll == null) { return; } JScrollPaneOperator scroller = new JScrollPaneOperator(scroll); scroller.copyEnvironment(this); scroller.setVisualizer(new EmptyVisualizer()); Rectangle rect = getPathBounds(path); if(rect != null) { scroller.scrollToComponentRectangle(getSource(), (int)rect.getX(), (int)rect.getY(), (int)rect.getWidth(), (int)rect.getHeight()); } else { throw(new NoSuchPathException(path)); } } else { throw(new NoSuchPathException()); } } /** * Scrolls to a row if the tree is on a JScrollPane component. * @param row a row index to scroll to. */ public void scrollToRow(int row) { scrollToPath(getPathForRow(row)); } /** * Turns path to the editing mode. * @param path a tree path to click on. * @throws TimeoutExpiredException */ public void clickForEdit(TreePath path) { driver.startEditing(this, getRowForPath(path), timeouts.create("JTreeOperator.WaitEditingTimeout")); } /** * Ask renderer for component to be displayed. * @param path a path indicating the rendered node. * @param isSelected True if the specified cell is selected. * @param isExpanded True if the specified cell is expanded. * @param cellHasFocus True if the specified cell has the focus. * @return Component to be displayed. */ public Component getRenderedComponent(TreePath path, boolean isSelected, boolean isExpanded, boolean cellHasFocus) { if(path != null) { return(getCellRenderer(). getTreeCellRendererComponent((JTree)getSource(), path.getLastPathComponent(), isSelected, isExpanded, getModel().isLeaf(path.getLastPathComponent()), getRowForPath(path), cellHasFocus)); } else { throw(new NoSuchPathException()); } } /** * Ask renderer for component to be displayed. * Uses isPathSelected(TreePath) to determine whether path is selected. * Uses isExpanded(TreePath) to determine whether path is expanded. * @param path a path indicating the rendered node. * @return Component to be displayed. */ public Component getRenderedComponent(TreePath path) { return(getRenderedComponent(path, isPathSelected(path), isExpanded(path), false)); } /** * Changes text of last path component. * @param path a path indicating the node to change value for. * @param newNodeText a new node value * @deprecated Use changePathObject(TreePath, Object) instead. * @see #changePathObject(TreePath, Object) * @throws TimeoutExpiredException */ public void changePathText(TreePath path, String newNodeText) { changePathObject(path, newNodeText); } /** * Changes last path component using getCellEditor() editor. * @param path a path indicating the node to change value for. * @param newValue a new node value * @throws TimeoutExpiredException */ public void changePathObject(TreePath path, Object newValue){ scrollToPath(path); driver.editItem(this, getRowForPath(path), newValue, timeouts.create("JTreeOperator.WaitEditingTimeout")); } /** * Waits path to be expanded. * @param path a path to wait expanded. */ public void waitExpanded(final TreePath path) { if(path != null) { getOutput().printLine("Wait \"" + path.toString() + "\" path to be expanded in component \n : "+ toStringSource()); getOutput().printGolden("Wait \"" + path.toString() + "\" path to be expanded"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(isExpanded(path)); } public String getDescription() { return("Has \"" + path.toString() + "\" path expanded"); } }); } else { throw(new NoSuchPathException()); } } /** * Waits row to be expanded. * @param row a row index to wait expanded. */ public void waitExpanded(final int row) { getOutput().printLine("Wait " + Integer.toString(row) + "'th row to be expanded in component \n : "+ toStringSource()); getOutput().printGolden("Wait " + Integer.toString(row) + "'th row to be expanded"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(isExpanded(row)); } public String getDescription() { return("Has " + Integer.toString(row) + "'th row expanded"); } }); } /** * Waits path to be collapsed. * @param path a path to wait collapsed. */ public void waitCollapsed(final TreePath path) { if(path != null) { getOutput().printLine("Wait \"" + path.toString() + "\" path to be collapsed in component \n : "+ toStringSource()); getOutput().printGolden("Wait \"" + path.toString() + "\" path to be collapsed"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(isCollapsed(path)); } public String getDescription() { return("Has \"" + path.toString() + "\" path collapsed"); } }); } else { throw(new NoSuchPathException()); } } /** * Waits row to be collapsed. * @param row a row index to wait collapsed. */ public void waitCollapsed(final int row) { getOutput().printLine("Wait " + Integer.toString(row) + "'th row to be collapsed in component \n : "+ toStringSource()); getOutput().printGolden("Wait " + Integer.toString(row) + "'th row to be collapsed"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(isCollapsed(row)); } public String getDescription() { return("Has " + Integer.toString(row) + "'th row collapsed"); } }); } /** * Waits path to be visible. * @param path a path to wait visible. */ public void waitVisible(final TreePath path) { if(path != null) { getOutput().printLine("Wait \"" + path.toString() + "\" path to be visible in component \n : "+ toStringSource()); getOutput().printGolden("Wait \"" + path.toString() + "\" path to be visible"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(isVisible(path)); } public String getDescription() { return("Has \"" + path.toString() + "\" path visible"); } }); } else { throw(new NoSuchPathException()); } } /** * Waits some paths to be selected. * @param paths an array of paths to be selected. */ public void waitSelected(final TreePath[] paths) { getOutput().printLine("Wait right selection in component \n : "+ toStringSource()); getOutput().printGolden("Wait right selection"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { TreePath[] rpaths = getSelectionModel().getSelectionPaths(); if(rpaths != null) { for(int i = 0; i < rpaths.length; i++) { if(!rpaths[i].equals(paths[i])) { return(false); } } return(true); } else { return(false); } } public String getDescription() { return("Has right selection"); } }); } /** * Waits path to be selected. * @param path a tree path to be selected. */ public void waitSelected(final TreePath path) { waitSelected(new TreePath[] {path}); } /** * Waits rows to be selected. * @param rows an indices of rows to be selected. */ public void waitSelected(int[] rows) { TreePath[] paths = new TreePath[rows.length]; for(int i = 0; i < rows.length; i++) { paths[i] = getPathForRow(rows[i]); } waitSelected(paths); } /** * Waits row to be selected. * @param row an index of a row to be selected. */ public void waitSelected(int row) { waitSelected(new int[] {row}); } /** * Wat for text in certain row. * @param rowText Text to be compared with row text be getComparator() comparator. * @param row Row index. If -1, selected one is checked. */ public void waitRow(String rowText, int row) { getOutput().printLine("Wait \"" + rowText + "\" text in " + Integer.toString(row) + "'th line in component \n : "+ toStringSource()); getOutput().printGolden("Wait \"" + rowText + " \" text in " + Integer.toString(row) + "'th line"); waitState(new JTreeByItemFinder(rowText, row, getComparator())); } public Object chooseSubnode(Object parent, String text, int index, StringComparator comparator) { int count = -1; Object node; for(int i = 0; i < getChildCount(parent); i++) { try { node = getChild(parent, i); } catch (JemmyException e) { if(e.getInnerThrowable() instanceof IndexOutOfBoundsException) { // tree probably re-generated because we haven't found child with specified index return null; } else { throw e; } } if(comparator.equals(node.toString(), text)) { count++; if(count == index) { return(node); } } } return(null); } public Object chooseSubnode(Object parent, String text, StringComparator comparator) { return(chooseSubnode(parent, text, 0, comparator)); } public Object chooseSubnode(Object parent, String text, int index) { return(chooseSubnode(parent, text, index, getComparator())); } public Object chooseSubnode(Object parent, String text) { return(chooseSubnode(parent, text, 0, getComparator())); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); Object root = ((JTree)getSource()).getModel().getRoot(); if(root.toString() != null) { // only if root is not hidden result.put(ROOT_DPROP, root.toString()); } addChildrenToDump(result, NODE_PREFIX_DPROP, root, new TreePath(root)); int minSelection = ((JTree)getSource()).getMinSelectionRow(); if( minSelection >= 0) { Object minObject = ((JTree)getSource()). getPathForRow(minSelection). getLastPathComponent(); result.put(SELECTION_FIRST_DPROP, minObject.toString()); int maxSelection = ((JTree)getSource()).getMaxSelectionRow(); if(maxSelection > minSelection) { Object maxObject = ((JTree)getSource()). getPathForRow(maxSelection). getLastPathComponent(); result.put(SELECTION_LAST_DPROP, maxObject.toString()); } } return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JTree.addSelectionInterval(int, int) through queue*/ public void addSelectionInterval(final int i, final int i1) { runMapping(new MapVoidAction("addSelectionInterval") { public void map() { ((JTree)getSource()).addSelectionInterval(i, i1); }});} /**Maps JTree.addSelectionPath(TreePath) through queue*/ public void addSelectionPath(final TreePath treePath) { runMapping(new MapVoidAction("addSelectionPath") { public void map() { ((JTree)getSource()).addSelectionPath(treePath); }});} /**Maps JTree.addSelectionPaths(TreePath[]) through queue*/ public void addSelectionPaths(final TreePath[] treePath) { runMapping(new MapVoidAction("addSelectionPaths") { public void map() { ((JTree)getSource()).addSelectionPaths(treePath); }});} /**Maps JTree.addSelectionRow(int) through queue*/ public void addSelectionRow(final int i) { runMapping(new MapVoidAction("addSelectionRow") { public void map() { ((JTree)getSource()).addSelectionRow(i); }});} /**Maps JTree.addSelectionRows(int[]) through queue*/ public void addSelectionRows(final int[] i) { runMapping(new MapVoidAction("addSelectionRows") { public void map() { ((JTree)getSource()).addSelectionRows(i); }});} /**Maps JTree.addTreeExpansionListener(TreeExpansionListener) through queue*/ public void addTreeExpansionListener(final TreeExpansionListener treeExpansionListener) { runMapping(new MapVoidAction("addTreeExpansionListener") { public void map() { ((JTree)getSource()).addTreeExpansionListener(treeExpansionListener); }});} /**Maps JTree.addTreeSelectionListener(TreeSelectionListener) through queue*/ public void addTreeSelectionListener(final TreeSelectionListener treeSelectionListener) { runMapping(new MapVoidAction("addTreeSelectionListener") { public void map() { ((JTree)getSource()).addTreeSelectionListener(treeSelectionListener); }});} /**Maps JTree.addTreeWillExpandListener(TreeWillExpandListener) through queue*/ public void addTreeWillExpandListener(final TreeWillExpandListener treeWillExpandListener) { runMapping(new MapVoidAction("addTreeWillExpandListener") { public void map() { ((JTree)getSource()).addTreeWillExpandListener(treeWillExpandListener); }});} /**Maps JTree.cancelEditing() through queue*/ public void cancelEditing() { runMapping(new MapVoidAction("cancelEditing") { public void map() { ((JTree)getSource()).cancelEditing(); }});} /**Maps JTree.clearSelection() through queue*/ public void clearSelection() { runMapping(new MapVoidAction("clearSelection") { public void map() { ((JTree)getSource()).clearSelection(); }});} /**Maps JTree.collapsePath(TreePath) through queue*/ public void collapsePath(final TreePath treePath) { runMapping(new MapVoidAction("collapsePath") { public void map() { ((JTree)getSource()).collapsePath(treePath); }});} /**Maps JTree.collapseRow(int) through queue*/ public void collapseRow(final int i) { runMapping(new MapVoidAction("collapseRow") { public void map() { ((JTree)getSource()).collapseRow(i); }});} /**Maps JTree.convertValueToText(Object, boolean, boolean, boolean, int, boolean) through queue*/ public String convertValueToText(final Object object, final boolean b, final boolean b1, final boolean b2, final int i, final boolean b3) { return((String)runMapping(new MapAction("convertValueToText") { public Object map() { return(((JTree)getSource()).convertValueToText(object, b, b1, b2, i, b3)); }}));} /**Maps JTree.expandPath(TreePath) through queue*/ public void expandPath(final TreePath treePath) { runMapping(new MapVoidAction("expandPath") { public void map() { ((JTree)getSource()).expandPath(treePath); }});} /**Maps JTree.expandRow(int) through queue*/ public void expandRow(final int i) { runMapping(new MapVoidAction("expandRow") { public void map() { ((JTree)getSource()).expandRow(i); }});} /**Maps JTree.fireTreeCollapsed(TreePath) through queue*/ public void fireTreeCollapsed(final TreePath treePath) { runMapping(new MapVoidAction("fireTreeCollapsed") { public void map() { ((JTree)getSource()).fireTreeCollapsed(treePath); }});} /**Maps JTree.fireTreeExpanded(TreePath) through queue*/ public void fireTreeExpanded(final TreePath treePath) { runMapping(new MapVoidAction("fireTreeExpanded") { public void map() { ((JTree)getSource()).fireTreeExpanded(treePath); }});} /**Maps JTree.fireTreeWillCollapse(TreePath) through queue*/ public void fireTreeWillCollapse(final TreePath treePath) { runMapping(new MapVoidAction("fireTreeWillCollapse") { public void map() throws ExpandVetoException { ((JTree)getSource()).fireTreeWillCollapse(treePath); }});} /**Maps JTree.fireTreeWillExpand(TreePath) through queue*/ public void fireTreeWillExpand(final TreePath treePath) { runMapping(new MapVoidAction("fireTreeWillExpand") { public void map() throws ExpandVetoException { ((JTree)getSource()).fireTreeWillExpand(treePath); }});} /**Maps JTree.getCellEditor() through queue*/ public TreeCellEditor getCellEditor() { return((TreeCellEditor)runMapping(new MapAction("getCellEditor") { public Object map() { return(((JTree)getSource()).getCellEditor()); }}));} /**Maps JTree.getCellRenderer() through queue*/ public TreeCellRenderer getCellRenderer() { return((TreeCellRenderer)runMapping(new MapAction("getCellRenderer") { public Object map() { return(((JTree)getSource()).getCellRenderer()); }}));} /**Maps JTree.getClosestPathForLocation(int, int) through queue*/ public TreePath getClosestPathForLocation(final int i, final int i1) { return((TreePath)runMapping(new MapAction("getClosestPathForLocation") { public Object map() { return(((JTree)getSource()).getClosestPathForLocation(i, i1)); }}));} /**Maps JTree.getClosestRowForLocation(int, int) through queue*/ public int getClosestRowForLocation(final int i, final int i1) { return(runMapping(new MapIntegerAction("getClosestRowForLocation") { public int map() { return(((JTree)getSource()).getClosestRowForLocation(i, i1)); }}));} /**Maps JTree.getEditingPath() through queue*/ public TreePath getEditingPath() { return((TreePath)runMapping(new MapAction("getEditingPath") { public Object map() { return(((JTree)getSource()).getEditingPath()); }}));} /**Maps JTree.getExpandedDescendants(TreePath) through queue*/ public Enumeration getExpandedDescendants(final TreePath treePath) { return((Enumeration)runMapping(new MapAction("getExpandedDescendants") { public Object map() { return(((JTree)getSource()).getExpandedDescendants(treePath)); }}));} /**Maps JTree.getInvokesStopCellEditing() through queue*/ public boolean getInvokesStopCellEditing() { return(runMapping(new MapBooleanAction("getInvokesStopCellEditing") { public boolean map() { return(((JTree)getSource()).getInvokesStopCellEditing()); }}));} /**Maps JTree.getLastSelectedPathComponent() through queue*/ public Object getLastSelectedPathComponent() { return((Object)runMapping(new MapAction("getLastSelectedPathComponent") { public Object map() { return(((JTree)getSource()).getLastSelectedPathComponent()); }}));} /**Maps JTree.getLeadSelectionPath() through queue*/ public TreePath getLeadSelectionPath() { return((TreePath)runMapping(new MapAction("getLeadSelectionPath") { public Object map() { return(((JTree)getSource()).getLeadSelectionPath()); }}));} /**Maps JTree.getLeadSelectionRow() through queue*/ public int getLeadSelectionRow() { return(runMapping(new MapIntegerAction("getLeadSelectionRow") { public int map() { return(((JTree)getSource()).getLeadSelectionRow()); }}));} /**Maps JTree.getMaxSelectionRow() through queue*/ public int getMaxSelectionRow() { return(runMapping(new MapIntegerAction("getMaxSelectionRow") { public int map() { return(((JTree)getSource()).getMaxSelectionRow()); }}));} /**Maps JTree.getMinSelectionRow() through queue*/ public int getMinSelectionRow() { return(runMapping(new MapIntegerAction("getMinSelectionRow") { public int map() { return(((JTree)getSource()).getMinSelectionRow()); }}));} /**Maps JTree.getModel() through queue*/ public TreeModel getModel() { return((TreeModel)runMapping(new MapAction("getModel") { public Object map() { return(((JTree)getSource()).getModel()); }}));} /**Maps JTree.getPathBounds(TreePath) through queue*/ public Rectangle getPathBounds(final TreePath treePath) { return((Rectangle)runMapping(new MapAction("getPathBounds") { public Object map() { return(((JTree)getSource()).getPathBounds(treePath)); }}));} /**Maps JTree.getPathForLocation(int, int) through queue*/ public TreePath getPathForLocation(final int i, final int i1) { return((TreePath)runMapping(new MapAction("getPathForLocation") { public Object map() { return(((JTree)getSource()).getPathForLocation(i, i1)); }}));} /**Maps JTree.getPathForRow(int) through queue*/ public TreePath getPathForRow(final int i) { return((TreePath)runMapping(new MapAction("getPathForRow") { public Object map() { return(((JTree)getSource()).getPathForRow(i)); }}));} /**Maps JTree.getPreferredScrollableViewportSize() through queue*/ public Dimension getPreferredScrollableViewportSize() { return((Dimension)runMapping(new MapAction("getPreferredScrollableViewportSize") { public Object map() { return(((JTree)getSource()).getPreferredScrollableViewportSize()); }}));} /**Maps JTree.getRowBounds(int) through queue*/ public Rectangle getRowBounds(final int i) { return((Rectangle)runMapping(new MapAction("getRowBounds") { public Object map() { return(((JTree)getSource()).getRowBounds(i)); }}));} /**Maps JTree.getRowCount() through queue*/ public int getRowCount() { return(runMapping(new MapIntegerAction("getRowCount") { public int map() { return(((JTree)getSource()).getRowCount()); }}));} /**Maps JTree.getRowForLocation(int, int) through queue*/ public int getRowForLocation(final int i, final int i1) { return(runMapping(new MapIntegerAction("getRowForLocation") { public int map() { return(((JTree)getSource()).getRowForLocation(i, i1)); }}));} /**Maps JTree.getRowForPath(TreePath) through queue*/ public int getRowForPath(final TreePath treePath) { return(runMapping(new MapIntegerAction("getRowForPath") { public int map() { return(((JTree)getSource()).getRowForPath(treePath)); }}));} /**Maps JTree.getRowHeight() through queue*/ public int getRowHeight() { return(runMapping(new MapIntegerAction("getRowHeight") { public int map() { return(((JTree)getSource()).getRowHeight()); }}));} /**Maps JTree.getScrollableBlockIncrement(Rectangle, int, int) through queue*/ public int getScrollableBlockIncrement(final Rectangle rectangle, final int i, final int i1) { return(runMapping(new MapIntegerAction("getScrollableBlockIncrement") { public int map() { return(((JTree)getSource()).getScrollableBlockIncrement(rectangle, i, i1)); }}));} /**Maps JTree.getScrollableTracksViewportHeight() through queue*/ public boolean getScrollableTracksViewportHeight() { return(runMapping(new MapBooleanAction("getScrollableTracksViewportHeight") { public boolean map() { return(((JTree)getSource()).getScrollableTracksViewportHeight()); }}));} /**Maps JTree.getScrollableTracksViewportWidth() through queue*/ public boolean getScrollableTracksViewportWidth() { return(runMapping(new MapBooleanAction("getScrollableTracksViewportWidth") { public boolean map() { return(((JTree)getSource()).getScrollableTracksViewportWidth()); }}));} /**Maps JTree.getScrollableUnitIncrement(Rectangle, int, int) through queue*/ public int getScrollableUnitIncrement(final Rectangle rectangle, final int i, final int i1) { return(runMapping(new MapIntegerAction("getScrollableUnitIncrement") { public int map() { return(((JTree)getSource()).getScrollableUnitIncrement(rectangle, i, i1)); }}));} /**Maps JTree.getScrollsOnExpand() through queue*/ public boolean getScrollsOnExpand() { return(runMapping(new MapBooleanAction("getScrollsOnExpand") { public boolean map() { return(((JTree)getSource()).getScrollsOnExpand()); }}));} /**Maps JTree.getSelectionCount() through queue*/ public int getSelectionCount() { return(runMapping(new MapIntegerAction("getSelectionCount") { public int map() { return(((JTree)getSource()).getSelectionCount()); }}));} /**Maps JTree.getSelectionModel() through queue*/ public TreeSelectionModel getSelectionModel() { return((TreeSelectionModel)runMapping(new MapAction("getSelectionModel") { public Object map() { return(((JTree)getSource()).getSelectionModel()); }}));} /**Maps JTree.getSelectionPath() through queue*/ public TreePath getSelectionPath() { return((TreePath)runMapping(new MapAction("getSelectionPath") { public Object map() { return(((JTree)getSource()).getSelectionPath()); }}));} /**Maps JTree.getSelectionPaths() through queue*/ public TreePath[] getSelectionPaths() { return((TreePath[])runMapping(new MapAction("getSelectionPaths") { public Object map() { return(((JTree)getSource()).getSelectionPaths()); }}));} /**Maps JTree.getSelectionRows() through queue*/ public int[] getSelectionRows() { return((int[])runMapping(new MapAction("getSelectionRows") { public Object map() { return(((JTree)getSource()).getSelectionRows()); }}));} /**Maps JTree.getShowsRootHandles() through queue*/ public boolean getShowsRootHandles() { return(runMapping(new MapBooleanAction("getShowsRootHandles") { public boolean map() { return(((JTree)getSource()).getShowsRootHandles()); }}));} /**Maps JTree.getUI() through queue*/ public TreeUI getUI() { return((TreeUI)runMapping(new MapAction("getUI") { public Object map() { return(((JTree)getSource()).getUI()); }}));} /**Maps JTree.getVisibleRowCount() through queue*/ public int getVisibleRowCount() { return(runMapping(new MapIntegerAction("getVisibleRowCount") { public int map() { return(((JTree)getSource()).getVisibleRowCount()); }}));} /**Maps JTree.hasBeenExpanded(TreePath) through queue*/ public boolean hasBeenExpanded(final TreePath treePath) { return(runMapping(new MapBooleanAction("hasBeenExpanded") { public boolean map() { return(((JTree)getSource()).hasBeenExpanded(treePath)); }}));} /**Maps JTree.isCollapsed(int) through queue*/ public boolean isCollapsed(final int i) { return(runMapping(new MapBooleanAction("isCollapsed") { public boolean map() { return(((JTree)getSource()).isCollapsed(i)); }}));} /**Maps JTree.isCollapsed(TreePath) through queue*/ public boolean isCollapsed(final TreePath treePath) { return(runMapping(new MapBooleanAction("isCollapsed") { public boolean map() { return(((JTree)getSource()).isCollapsed(treePath)); }}));} /**Maps JTree.isEditable() through queue*/ public boolean isEditable() { return(runMapping(new MapBooleanAction("isEditable") { public boolean map() { return(((JTree)getSource()).isEditable()); }}));} /**Maps JTree.isEditing() through queue*/ public boolean isEditing() { return(runMapping(new MapBooleanAction("isEditing") { public boolean map() { return(((JTree)getSource()).isEditing()); }}));} /**Maps JTree.isExpanded(int) through queue*/ public boolean isExpanded(final int i) { return(runMapping(new MapBooleanAction("isExpanded") { public boolean map() { return(((JTree)getSource()).isExpanded(i)); }}));} /**Maps JTree.isExpanded(TreePath) through queue*/ public boolean isExpanded(final TreePath treePath) { return(runMapping(new MapBooleanAction("isExpanded") { public boolean map() { return(((JTree)getSource()).isExpanded(treePath)); }}));} /**Maps JTree.isFixedRowHeight() through queue*/ public boolean isFixedRowHeight() { return(runMapping(new MapBooleanAction("isFixedRowHeight") { public boolean map() { return(((JTree)getSource()).isFixedRowHeight()); }}));} /**Maps JTree.isLargeModel() through queue*/ public boolean isLargeModel() { return(runMapping(new MapBooleanAction("isLargeModel") { public boolean map() { return(((JTree)getSource()).isLargeModel()); }}));} /**Maps JTree.isPathEditable(TreePath) through queue*/ public boolean isPathEditable(final TreePath treePath) { return(runMapping(new MapBooleanAction("isPathEditable") { public boolean map() { return(((JTree)getSource()).isPathEditable(treePath)); }}));} /**Maps JTree.isPathSelected(TreePath) through queue*/ public boolean isPathSelected(final TreePath treePath) { return(runMapping(new MapBooleanAction("isPathSelected") { public boolean map() { return(((JTree)getSource()).isPathSelected(treePath)); }}));} /**Maps JTree.isRootVisible() through queue*/ public boolean isRootVisible() { return(runMapping(new MapBooleanAction("isRootVisible") { public boolean map() { return(((JTree)getSource()).isRootVisible()); }}));} /**Maps JTree.isRowSelected(int) through queue*/ public boolean isRowSelected(final int i) { return(runMapping(new MapBooleanAction("isRowSelected") { public boolean map() { return(((JTree)getSource()).isRowSelected(i)); }}));} /**Maps JTree.isSelectionEmpty() through queue*/ public boolean isSelectionEmpty() { return(runMapping(new MapBooleanAction("isSelectionEmpty") { public boolean map() { return(((JTree)getSource()).isSelectionEmpty()); }}));} /**Maps JTree.isVisible(TreePath) through queue*/ public boolean isVisible(final TreePath treePath) { return(runMapping(new MapBooleanAction("isVisible") { public boolean map() { return(((JTree)getSource()).isVisible(treePath)); }}));} /**Maps JTree.makeVisible(TreePath) through queue*/ public void makeVisible(final TreePath treePath) { runMapping(new MapVoidAction("makeVisible") { public void map() { ((JTree)getSource()).makeVisible(treePath); }});} /**Maps JTree.removeSelectionInterval(int, int) through queue*/ public void removeSelectionInterval(final int i, final int i1) { runMapping(new MapVoidAction("removeSelectionInterval") { public void map() { ((JTree)getSource()).removeSelectionInterval(i, i1); }});} /**Maps JTree.removeSelectionPath(TreePath) through queue*/ public void removeSelectionPath(final TreePath treePath) { runMapping(new MapVoidAction("removeSelectionPath") { public void map() { ((JTree)getSource()).removeSelectionPath(treePath); }});} /**Maps JTree.removeSelectionPaths(TreePath[]) through queue*/ public void removeSelectionPaths(final TreePath[] treePath) { runMapping(new MapVoidAction("removeSelectionPaths") { public void map() { ((JTree)getSource()).removeSelectionPaths(treePath); }});} /**Maps JTree.removeSelectionRow(int) through queue*/ public void removeSelectionRow(final int i) { runMapping(new MapVoidAction("removeSelectionRow") { public void map() { ((JTree)getSource()).removeSelectionRow(i); }});} /**Maps JTree.removeSelectionRows(int[]) through queue*/ public void removeSelectionRows(final int[] i) { runMapping(new MapVoidAction("removeSelectionRows") { public void map() { ((JTree)getSource()).removeSelectionRows(i); }});} /**Maps JTree.removeTreeExpansionListener(TreeExpansionListener) through queue*/ public void removeTreeExpansionListener(final TreeExpansionListener treeExpansionListener) { runMapping(new MapVoidAction("removeTreeExpansionListener") { public void map() { ((JTree)getSource()).removeTreeExpansionListener(treeExpansionListener); }});} /**Maps JTree.removeTreeSelectionListener(TreeSelectionListener) through queue*/ public void removeTreeSelectionListener(final TreeSelectionListener treeSelectionListener) { runMapping(new MapVoidAction("removeTreeSelectionListener") { public void map() { ((JTree)getSource()).removeTreeSelectionListener(treeSelectionListener); }});} /**Maps JTree.removeTreeWillExpandListener(TreeWillExpandListener) through queue*/ public void removeTreeWillExpandListener(final TreeWillExpandListener treeWillExpandListener) { runMapping(new MapVoidAction("removeTreeWillExpandListener") { public void map() { ((JTree)getSource()).removeTreeWillExpandListener(treeWillExpandListener); }});} /**Maps JTree.scrollPathToVisible(TreePath) through queue*/ public void scrollPathToVisible(final TreePath treePath) { runMapping(new MapVoidAction("scrollPathToVisible") { public void map() { ((JTree)getSource()).scrollPathToVisible(treePath); }});} /**Maps JTree.scrollRowToVisible(int) through queue*/ public void scrollRowToVisible(final int i) { runMapping(new MapVoidAction("scrollRowToVisible") { public void map() { ((JTree)getSource()).scrollRowToVisible(i); }});} /**Maps JTree.setCellEditor(TreeCellEditor) through queue*/ public void setCellEditor(final TreeCellEditor treeCellEditor) { runMapping(new MapVoidAction("setCellEditor") { public void map() { ((JTree)getSource()).setCellEditor(treeCellEditor); }});} /**Maps JTree.setCellRenderer(TreeCellRenderer) through queue*/ public void setCellRenderer(final TreeCellRenderer treeCellRenderer) { runMapping(new MapVoidAction("setCellRenderer") { public void map() { ((JTree)getSource()).setCellRenderer(treeCellRenderer); }});} /**Maps JTree.setEditable(boolean) through queue*/ public void setEditable(final boolean b) { runMapping(new MapVoidAction("setEditable") { public void map() { ((JTree)getSource()).setEditable(b); }});} /**Maps JTree.setInvokesStopCellEditing(boolean) through queue*/ public void setInvokesStopCellEditing(final boolean b) { runMapping(new MapVoidAction("setInvokesStopCellEditing") { public void map() { ((JTree)getSource()).setInvokesStopCellEditing(b); }});} /**Maps JTree.setLargeModel(boolean) through queue*/ public void setLargeModel(final boolean b) { runMapping(new MapVoidAction("setLargeModel") { public void map() { ((JTree)getSource()).setLargeModel(b); }});} /**Maps JTree.setModel(TreeModel) through queue*/ public void setModel(final TreeModel treeModel) { runMapping(new MapVoidAction("setModel") { public void map() { ((JTree)getSource()).setModel(treeModel); }});} /**Maps JTree.setRootVisible(boolean) through queue*/ public void setRootVisible(final boolean b) { runMapping(new MapVoidAction("setRootVisible") { public void map() { ((JTree)getSource()).setRootVisible(b); }});} /**Maps JTree.setRowHeight(int) through queue*/ public void setRowHeight(final int i) { runMapping(new MapVoidAction("setRowHeight") { public void map() { ((JTree)getSource()).setRowHeight(i); }});} /**Maps JTree.setScrollsOnExpand(boolean) through queue*/ public void setScrollsOnExpand(final boolean b) { runMapping(new MapVoidAction("setScrollsOnExpand") { public void map() { ((JTree)getSource()).setScrollsOnExpand(b); }});} /**Maps JTree.setSelectionInterval(int, int) through queue*/ public void setSelectionInterval(final int i, final int i1) { runMapping(new MapVoidAction("setSelectionInterval") { public void map() { ((JTree)getSource()).setSelectionInterval(i, i1); }});} /**Maps JTree.setSelectionModel(TreeSelectionModel) through queue*/ public void setSelectionModel(final TreeSelectionModel treeSelectionModel) { runMapping(new MapVoidAction("setSelectionModel") { public void map() { ((JTree)getSource()).setSelectionModel(treeSelectionModel); }});} /**Maps JTree.setSelectionPath(TreePath) through queue*/ public void setSelectionPath(final TreePath treePath) { runMapping(new MapVoidAction("setSelectionPath") { public void map() { ((JTree)getSource()).setSelectionPath(treePath); }});} /**Maps JTree.setSelectionPaths(TreePath[]) through queue*/ public void setSelectionPaths(final TreePath[] treePath) { runMapping(new MapVoidAction("setSelectionPaths") { public void map() { ((JTree)getSource()).setSelectionPaths(treePath); }});} /**Maps JTree.setSelectionRow(int) through queue*/ public void setSelectionRow(final int i) { runMapping(new MapVoidAction("setSelectionRow") { public void map() { ((JTree)getSource()).setSelectionRow(i); }});} /**Maps JTree.setSelectionRows(int[]) through queue*/ public void setSelectionRows(final int[] i) { runMapping(new MapVoidAction("setSelectionRows") { public void map() { ((JTree)getSource()).setSelectionRows(i); }});} /**Maps JTree.setShowsRootHandles(boolean) through queue*/ public void setShowsRootHandles(final boolean b) { runMapping(new MapVoidAction("setShowsRootHandles") { public void map() { ((JTree)getSource()).setShowsRootHandles(b); }});} /**Maps JTree.setUI(TreeUI) through queue*/ public void setUI(final TreeUI treeUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JTree)getSource()).setUI(treeUI); }});} /**Maps JTree.setVisibleRowCount(int) through queue*/ public void setVisibleRowCount(final int i) { runMapping(new MapVoidAction("setVisibleRowCount") { public void map() { ((JTree)getSource()).setVisibleRowCount(i); }});} /**Maps JTree.startEditingAtPath(TreePath) through queue*/ public void startEditingAtPath(final TreePath treePath) { runMapping(new MapVoidAction("startEditingAtPath") { public void map() { ((JTree)getSource()).startEditingAtPath(treePath); }});} /**Maps JTree.stopEditing() through queue*/ public boolean stopEditing() { return(runMapping(new MapBooleanAction("stopEditing") { public boolean map() { return(((JTree)getSource()).stopEditing()); }}));} /**Maps JTree.treeDidChange() through queue*/ public void treeDidChange() { runMapping(new MapVoidAction("treeDidChange") { public void map() { ((JTree)getSource()).treeDidChange(); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Iterface to choose tree row. Defines criteria to distinguish row. */ public interface TreeRowChooser { /** * Should be true if row is good. * @param oper Operator used to search item. * @param row Row be checked. * @return true if the row fits the criteria */ public boolean checkRow(JTreeOperator oper, int row); /** * Row description. * @return a criteria description. */ public String getDescription(); } private TreePath findPathPrimitive(TreePath path, TreePathChooser chooser, Waiter loadedWaiter) { if(!isExpanded(path)) { if(!isPathSelected(path)) { clickOnPath(path); } expandPath(path); } Object[] waitParam = {chooser, path}; Object[] waitResult = null; try { waitResult = (Object[])loadedWaiter.waitAction(waitParam); } catch(InterruptedException e) { output.printStackTrace(e); return(null); } TreePath nextPath = (TreePath)waitResult[0]; boolean found = ((Boolean)waitResult[1]).booleanValue(); if(found) { return(nextPath); } else { return(findPathPrimitive(nextPath, chooser, loadedWaiter)); } } private String[] addChildrenToDump(Hashtable table, String title, Object node, TreePath path) { if(((JTree)getSource()).isExpanded(path)) { Object[] subNodes = getChildren(node); String[] names = addToDump(table, title, subNodes); for(int i = 0; i < subNodes.length; i++) { addChildrenToDump(table, names[i], subNodes[i], path.pathByAddingChild(subNodes[i])); } return(names); } else { return(new String[0]); } } private static String pathToString(String[] path) { String desc = ""; for(int i = 0; i < path.length; i++) { desc = desc + path[i] + ", "; } if(desc.length() > 0) { desc = desc.substring(0, desc.length() - 2); } return("[ " + desc + " ]"); } /** * Can be throught during item selecting if list does not have * item requested. */ public class NoSuchPathException extends JemmyInputException { /** * Constructor. */ public NoSuchPathException() { super("Unknown/null/invalid tree path.", null); } /** * Constructor. * @param path a nonexistent path. */ public NoSuchPathException(String[] path) { super("No such path as \"" + pathToString(path) + "\"", getSource()); } /** * Constructor. * @param index a nonexistent line index. */ public NoSuchPathException(int index) { super("Tree does not contain " + index + "'th line", getSource()); } /** * Constructor. * @param path a nonexistent path. */ public NoSuchPathException(TreePath path) { super("No such path as \"" + path.toString() + "\"", getSource()); } } /** * Specifies criteria for path searching. */ public interface TreePathChooser { /** * Checks if the path fits the criteria. * @param path TreePath to check. * @param indexInParent Index of the "path" in path's parent. * @return true if the path fits the criteria */ public boolean checkPath(TreePath path, int indexInParent); /** * Checks if the path has another path as a parent. * @param path TreePath to check. * @param indexInParent Index of the "path" in path's parent. * @return true if path looked for is a child/grandchild of a path passed as a parameter. */ public boolean hasAsParent(TreePath path, int indexInParent); /** * Returns the description. * @return a description. */ public String getDescription(); } /** * Specifies searching criteria basing on nodes' text. */ class StringArrayPathChooser implements TreePathChooser { String[] arr; int[] indices; StringComparator comparator; /** * Constructs StringArrayPathChooser. * @param arr a node text array. First element defines a text of a first node * under a tree root, second element - a children of the first node, ... * @param indices indexes of nodes in nodes' parents. * @param comparator String comparision criteria. */ StringArrayPathChooser(String[] arr, int[] indices, StringComparator comparator) { this.arr = arr; this.comparator = comparator; this.indices = indices; } public boolean checkPath(TreePath path, int indexInParent) { return(path.getPathCount() - 1 == arr.length && hasAsParent(path, indexInParent)); } public boolean hasAsParent(TreePath path, int indexInParent) { Object[] comps = path.getPath(); Object node; for(int i = 1; i < comps.length; i++) { if(arr.length < path.getPathCount() - 1) { return(false); } /* if(!comparator.equals(comps[i].toString(), arr[i - 1])) { return(false); } */ if(indices.length >= path.getPathCount() - 1) { node = chooseSubnode(comps[i-1], arr[i - 1], indices[i - 1], comparator); } else { node = chooseSubnode(comps[i-1], arr[i - 1], comparator); } if(node != comps[i]) { return(false); } } return(true); } public String getDescription() { return(pathToString(arr)); } } private class BySubStringTreeRowChooser implements TreeRowChooser { String subString; StringComparator comparator; public BySubStringTreeRowChooser(String subString, StringComparator comparator) { this.subString = subString; this.comparator = comparator; } public boolean checkRow(JTreeOperator oper, int row) { return(comparator.equals(oper.getPathForRow(row).getLastPathComponent().toString(), subString)); } public String getDescription() { return("Row containing \"" + subString + "\" string"); } } private class ByRenderedComponentTreeRowChooser implements TreeRowChooser { ComponentChooser chooser; public ByRenderedComponentTreeRowChooser(ComponentChooser chooser) { this.chooser = chooser; } public boolean checkRow(JTreeOperator oper, int row) { return(chooser.checkComponent(oper.getRenderedComponent(oper.getPathForRow(row)))); } public String getDescription() { return(chooser.getDescription()); } } /** * Checks component type. */ public static class JTreeFinder extends Finder { /** * Constructs JTreeFinder. * @param sf other searching criteria. */ public JTreeFinder(ComponentChooser sf) { super(JTree.class, sf); } /** * Constructs JTreeFinder. */ public JTreeFinder() { super(JTree.class); } } /** * Allows to find component by node text. */ public static class JTreeByItemFinder implements ComponentChooser { String label; int rowIndex; StringComparator comparator; /** * Constructs JTreeByItemFinder. * @param lb a text pattern * @param ii row index to check. If equal to -1, selected row is checked. * @param comparator specifies string comparision algorithm. */ public JTreeByItemFinder(String lb, int ii, StringComparator comparator) { label = lb; rowIndex = ii; this.comparator = comparator; } /** * Constructs JTreeByItemFinder. * @param lb a text pattern * @param ii row index to check. If equal to -1, selected row is checked. */ public JTreeByItemFinder(String lb, int ii) { this(lb, ii, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JTree) { if(label == null) { return(true); } if(((JTree)comp).getRowCount() > rowIndex) { int ii = rowIndex; if(ii == -1) { int[] rows = ((JTree)comp).getSelectionRows(); if(rows != null && rows.length > 0) { ii = rows[0]; } else { return(false); } } TreePath path = ((JTree)comp).getPathForRow(ii); if(path != null) { return(comparator.equals(path.getPathComponent(path.getPathCount() - 1).toString(), label)); } } } return(false); } public String getDescription() { return("JTree with text \"" + label + "\" in " + (new Integer(rowIndex)).toString() + "'th row"); } } } Jemmy2/src/org/netbeans/jemmy/operators/JFrameOperator.java0000644000175000017500000003335511245712237023041 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import javax.accessibility.AccessibleContext; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JMenuBar; import javax.swing.JRootPane; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.FrameWaiter; import org.netbeans.jemmy.JemmyProperties; /** *

Timeouts used:
* FrameWaiter.WaitFrameTimeout - time to wait frame displayed
* FrameWaiter.AfterFrameTimeout - time to sleep after frame has been dispayed
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JFrameOperator extends FrameOperator { /** * Constructor. * @param w window */ public JFrameOperator(JFrame w) { super(w); } /** * Constructs a JFrameOperator object. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @param env an operator to copy environment from. */ public JFrameOperator(ComponentChooser chooser, int index, Operator env) { this((JFrame)waitFrame(new JFrameFinder(chooser), index, env.getTimeouts(), env.getOutput())); copyEnvironment(env); } /** * Constructs a JFrameOperator object. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JFrameOperator(ComponentChooser chooser, int index) { this(chooser, index, Operator.getEnvironmentOperator()); } /** * Constructs a JFrameOperator object. * @param chooser a component chooser specifying searching criteria. */ public JFrameOperator(ComponentChooser chooser) { this(chooser, 0); } /** * Constructor. * Waits for the frame with "title" subtitle. * Constructor can be used in complicated cases when * output or timeouts should differ from default. * @param title a window title * @param index Ordinal component index. * @param env an operator to copy environment from. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public JFrameOperator(String title, int index, Operator env) { this(new JFrameFinder(new FrameByTitleFinder(title, env.getComparator())), index, env); } /** * Constructor. * Waits for the frame with "title" subtitle. * Uses current timeouts and output values. * @param title a window title * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see JemmyProperties#getCurrentTimeouts() * @see JemmyProperties#getCurrentOutput() * */ public JFrameOperator(String title, int index) { this(title, index, ComponentOperator.getEnvironmentOperator()); } /** * Constructor. * Waits for the frame with "title" subtitle. * Uses current timeouts and output values. * @param title a window title * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see JemmyProperties#getCurrentTimeouts() * @see JemmyProperties#getCurrentOutput() * */ public JFrameOperator(String title) { this(title, 0); } /** * Constructor. * Waits for the index'th frame. * Uses current timeout and output for waiting and to init operator. * @param index Ordinal component index. * */ public JFrameOperator(int index) { this((JFrame) (JFrame)waitFrame(new JFrameFinder(), index, ComponentOperator.getEnvironmentOperator().getTimeouts(), ComponentOperator.getEnvironmentOperator().getOutput())); copyEnvironment(ComponentOperator.getEnvironmentOperator()); } /** * Constructor. * Waits for the first frame. * Uses current timeout and output for waiting and to init operator. * */ public JFrameOperator() { this(0); } /** * Searches an index'th frame. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @return JFrame instance or null if component was not found. */ public static JFrame findJFrame(ComponentChooser chooser, int index) { return((JFrame)FrameWaiter.getFrame(new JFrameFinder(chooser), index)); } /** * Searches a frame. * @param chooser a component chooser specifying searching criteria. * @return JFrame instance or null if component was not found. */ public static JFrame findJFrame(ComponentChooser chooser) { return(findJFrame(chooser, 0)); } /** * Searches an index'th frame by title. * @param title Frame title * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @param index an index between appropriate ones. * @return JFrame instance or null if component was not found. */ public static JFrame findJFrame(String title, boolean ce, boolean cc, int index) { return((JFrame)FrameWaiter. getFrame(new JFrameFinder(new FrameByTitleFinder(title, new DefaultStringComparator(ce, cc))), index)); } /** * Searches a frame by title. * @param title Frame title * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @return JFrame instance or null if component was not found. */ public static JFrame findJFrame(String title, boolean ce, boolean cc) { return(findJFrame(title, ce, cc, 0)); } /** * Waits an index'th frame. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @return JFrame instance or null if component was not found. * */ public static JFrame waitJFrame(ComponentChooser chooser, int index) { return((JFrame)waitFrame(new JFrameFinder(chooser), index, JemmyProperties.getCurrentTimeouts(), JemmyProperties.getCurrentOutput())); } /** * Waits a frame. * @param chooser a component chooser specifying searching criteria. * @return JFrame instance or null if component was not found. * */ public static JFrame waitJFrame(ComponentChooser chooser) { return(waitJFrame(chooser, 0)); } /** * Waits an index'th frame by title. * @param title Frame title * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @param index an index between appropriate ones. * @return JFrame instance or null if component was not found. * */ public static JFrame waitJFrame(String title, boolean ce, boolean cc, int index) { try { return((JFrame)(new FrameWaiter()). waitFrame(new JFrameFinder(new FrameByTitleFinder(title, new DefaultStringComparator(ce, cc))), index)); } catch(InterruptedException e) { JemmyProperties.getCurrentOutput().printStackTrace(e); return(null); } } /** * Waits a frame by title. * @param title Frame title * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @return JFrame instance or null if component was not found. * */ public static JFrame waitJFrame(String title, boolean ce, boolean cc) { return(waitJFrame(title, ce, cc, 0)); } //////////////////////////////////////////////////////// //Mapping // /**Maps JFrame.getAccessibleContext() through queue*/ public AccessibleContext getAccessibleContext() { return((AccessibleContext)runMapping(new MapAction("getAccessibleContext") { public Object map() { return(((JFrame)getSource()).getAccessibleContext()); }}));} /**Maps JFrame.getContentPane() through queue*/ public Container getContentPane() { return((Container)runMapping(new MapAction("getContentPane") { public Object map() { return(((JFrame)getSource()).getContentPane()); }}));} /**Maps JFrame.getDefaultCloseOperation() through queue*/ public int getDefaultCloseOperation() { return(runMapping(new MapIntegerAction("getDefaultCloseOperation") { public int map() { return(((JFrame)getSource()).getDefaultCloseOperation()); }}));} /**Maps JFrame.getGlassPane() through queue*/ public Component getGlassPane() { return((Component)runMapping(new MapAction("getGlassPane") { public Object map() { return(((JFrame)getSource()).getGlassPane()); }}));} /**Maps JFrame.getJMenuBar() through queue*/ public JMenuBar getJMenuBar() { return((JMenuBar)runMapping(new MapAction("getJMenuBar") { public Object map() { return(((JFrame)getSource()).getJMenuBar()); }}));} /**Maps JFrame.getLayeredPane() through queue*/ public JLayeredPane getLayeredPane() { return((JLayeredPane)runMapping(new MapAction("getLayeredPane") { public Object map() { return(((JFrame)getSource()).getLayeredPane()); }}));} /**Maps JFrame.getRootPane() through queue*/ public JRootPane getRootPane() { return((JRootPane)runMapping(new MapAction("getRootPane") { public Object map() { return(((JFrame)getSource()).getRootPane()); }}));} /**Maps JFrame.setContentPane(Container) through queue*/ public void setContentPane(final Container container) { runMapping(new MapVoidAction("setContentPane") { public void map() { ((JFrame)getSource()).setContentPane(container); }});} /**Maps JFrame.setDefaultCloseOperation(int) through queue*/ public void setDefaultCloseOperation(final int i) { runMapping(new MapVoidAction("setDefaultCloseOperation") { public void map() { ((JFrame)getSource()).setDefaultCloseOperation(i); }});} /**Maps JFrame.setGlassPane(Component) through queue*/ public void setGlassPane(final Component component) { runMapping(new MapVoidAction("setGlassPane") { public void map() { ((JFrame)getSource()).setGlassPane(component); }});} /**Maps JFrame.setJMenuBar(JMenuBar) through queue*/ public void setJMenuBar(final JMenuBar jMenuBar) { runMapping(new MapVoidAction("setJMenuBar") { public void map() { ((JFrame)getSource()).setJMenuBar(jMenuBar); }});} /**Maps JFrame.setLayeredPane(JLayeredPane) through queue*/ public void setLayeredPane(final JLayeredPane jLayeredPane) { runMapping(new MapVoidAction("setLayeredPane") { public void map() { ((JFrame)getSource()).setLayeredPane(jLayeredPane); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Checks component type. */ public static class JFrameFinder extends Finder { /** * Constructs JFrameFinder. * @param sf other searching criteria. */ public JFrameFinder(ComponentChooser sf) { super(JFrame.class, sf); } /** * Constructs JFrameFinder. */ public JFrameFinder() { super(JFrame.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JTextPaneOperator.java0000644000175000017500000003467011245712237023540 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import javax.swing.Icon; import javax.swing.JTextPane; import javax.swing.text.AttributeSet; import javax.swing.text.MutableAttributeSet; import javax.swing.text.Style; import javax.swing.text.StyledDocument; import org.netbeans.jemmy.ComponentChooser; /** *

Timeouts used:
* JTextComponentOperator.PushKeyTimeout - time between key pressing and releasing during text typing
* JTextComponentOperator.BetweenKeysTimeout - time to sleep between two chars typing
* JTextComponentOperator.ChangeCaretPositionTimeout - maximum time to chenge caret position
* JTextComponentOperator.TypeTextTimeout - maximum time to type text
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.WaitFocusTimeout - time to wait component focus
* JScrollBarOperator.OneScrollClickTimeout - time for one scroll click
* JScrollBarOperator.WholeScrollTimeout - time for the whole scrolling
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JTextPaneOperator extends JEditorPaneOperator { /** * Constructor. * @param b a component */ public JTextPaneOperator(JTextPane b) { super(b); } /** * Constructs a JTextPaneOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JTextPaneOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JTextPane)cont. waitSubComponent(new JTextPaneFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JTextPaneOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JTextPaneOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public JTextPaneOperator(ContainerOperator cont, String text, int index) { this((JTextPane) waitComponent(cont, new JTextPaneFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, cont.getComparator())), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public JTextPaneOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. */ public JTextPaneOperator(ContainerOperator cont, int index) { this((JTextPane) waitComponent(cont, new JTextPaneFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container */ public JTextPaneOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JTextPane in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JTextPane instance or null if component was not found. */ public static JTextPane findJTextPane(Container cont, ComponentChooser chooser, int index) { return((JTextPane)findJTextComponent(cont, new JTextPaneFinder(chooser), index)); } /** * Searches JTextPane in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JTextPane instance or null if component was not found. */ public static JTextPane findJTextPane(Container cont, ComponentChooser chooser) { return(findJTextPane(cont, chooser, 0)); } /** * Searches JTextPane by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JTextPane instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTextPane findJTextPane(Container cont, String text, boolean ce, boolean ccs, int index) { return(findJTextPane(cont, new JTextPaneFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Searches JTextPane by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JTextPane instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTextPane findJTextPane(Container cont, String text, boolean ce, boolean ccs) { return(findJTextPane(cont, text, ce, ccs, 0)); } /** * Waits JTextPane in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JTextPane instance. */ public static JTextPane waitJTextPane(Container cont, ComponentChooser chooser, int index) { return((JTextPane)waitJTextComponent(cont, new JTextPaneFinder(chooser), index)); } /** * Waits JTextPane in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JTextPane instance. */ public static JTextPane waitJTextPane(Container cont, ComponentChooser chooser) { return(waitJTextPane(cont, chooser, 0)); } /** * Waits JTextPane by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JTextPane instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTextPane waitJTextPane(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitJTextPane(cont, new JTextPaneFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Waits JTextPane by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JTextPane instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTextPane waitJTextPane(Container cont, String text, boolean ce, boolean ccs) { return(waitJTextPane(cont, text, ce, ccs, 0)); } //////////////////////////////////////////////////////// //Mapping // /**Maps JTextPane.addStyle(String, Style) through queue*/ public Style addStyle(final String string, final Style style) { return((Style)runMapping(new MapAction("addStyle") { public Object map() { return(((JTextPane)getSource()).addStyle(string, style)); }}));} /**Maps JTextPane.getCharacterAttributes() through queue*/ public AttributeSet getCharacterAttributes() { return((AttributeSet)runMapping(new MapAction("getCharacterAttributes") { public Object map() { return(((JTextPane)getSource()).getCharacterAttributes()); }}));} /**Maps JTextPane.getInputAttributes() through queue*/ public MutableAttributeSet getInputAttributes() { return((MutableAttributeSet)runMapping(new MapAction("getInputAttributes") { public Object map() { return(((JTextPane)getSource()).getInputAttributes()); }}));} /**Maps JTextPane.getLogicalStyle() through queue*/ public Style getLogicalStyle() { return((Style)runMapping(new MapAction("getLogicalStyle") { public Object map() { return(((JTextPane)getSource()).getLogicalStyle()); }}));} /**Maps JTextPane.getParagraphAttributes() through queue*/ public AttributeSet getParagraphAttributes() { return((AttributeSet)runMapping(new MapAction("getParagraphAttributes") { public Object map() { return(((JTextPane)getSource()).getParagraphAttributes()); }}));} /**Maps JTextPane.getStyle(String) through queue*/ public Style getStyle(final String string) { return((Style)runMapping(new MapAction("getStyle") { public Object map() { return(((JTextPane)getSource()).getStyle(string)); }}));} /**Maps JTextPane.getStyledDocument() through queue*/ public StyledDocument getStyledDocument() { return((StyledDocument)runMapping(new MapAction("getStyledDocument") { public Object map() { return(((JTextPane)getSource()).getStyledDocument()); }}));} /**Maps JTextPane.insertComponent(Component) through queue*/ public void insertComponent(final Component component) { runMapping(new MapVoidAction("insertComponent") { public void map() { ((JTextPane)getSource()).insertComponent(component); }});} /**Maps JTextPane.insertIcon(Icon) through queue*/ public void insertIcon(final Icon icon) { runMapping(new MapVoidAction("insertIcon") { public void map() { ((JTextPane)getSource()).insertIcon(icon); }});} /**Maps JTextPane.removeStyle(String) through queue*/ public void removeStyle(final String string) { runMapping(new MapVoidAction("removeStyle") { public void map() { ((JTextPane)getSource()).removeStyle(string); }});} /**Maps JTextPane.setCharacterAttributes(AttributeSet, boolean) through queue*/ public void setCharacterAttributes(final AttributeSet attributeSet, final boolean b) { runMapping(new MapVoidAction("setCharacterAttributes") { public void map() { ((JTextPane)getSource()).setCharacterAttributes(attributeSet, b); }});} /**Maps JTextPane.setLogicalStyle(Style) through queue*/ public void setLogicalStyle(final Style style) { runMapping(new MapVoidAction("setLogicalStyle") { public void map() { ((JTextPane)getSource()).setLogicalStyle(style); }});} /**Maps JTextPane.setParagraphAttributes(AttributeSet, boolean) through queue*/ public void setParagraphAttributes(final AttributeSet attributeSet, final boolean b) { runMapping(new MapVoidAction("setParagraphAttributes") { public void map() { ((JTextPane)getSource()).setParagraphAttributes(attributeSet, b); }});} /**Maps JTextPane.setStyledDocument(StyledDocument) through queue*/ public void setStyledDocument(final StyledDocument styledDocument) { runMapping(new MapVoidAction("setStyledDocument") { public void map() { ((JTextPane)getSource()).setStyledDocument(styledDocument); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Checks component type. */ public static class JTextPaneFinder extends Finder { /** * Constructs JTextPaneFinder. * @param sf other searching criteria. */ public JTextPaneFinder(ComponentChooser sf) { super(JTextPane.class, sf); } /** * Constructs JTextPaneFinder. */ public JTextPaneFinder() { super(JTextPane.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/ListOperator.java0000644000175000017500000004764711245712237022621 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.List; import java.awt.event.ActionListener; import java.awt.event.ItemListener; import java.util.Hashtable; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.MultiSelListDriver; /** *

Timeouts used:
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait component enabled
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class ListOperator extends ComponentOperator implements Outputable { /** * Identifier for a "item" properties. * @see #getDump */ public static final String ITEM_PREFIX_DPROP = "Item"; /** * Identifier for a "selected item" property. * @see #getDump */ public static final String SELECTED_ITEM_PREFIX_DPROP = "SelectedItem"; private TestOut output; private MultiSelListDriver driver; /** * Constructor. * @param b a component */ public ListOperator(List b) { super(b); driver = DriverManager.getMultiSelListDriver(getClass()); } /** * Constructs a ListOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public ListOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((List)cont. waitSubComponent(new ListFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a ListOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public ListOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits item text first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of item which is currently selected. * @param itemIndex Item index. * @param index Ordinal component index. * @throws TimeoutExpiredException */ public ListOperator(ContainerOperator cont, String text, int itemIndex, int index) { this((List)waitComponent(cont, new ListByItemFinder(text, itemIndex, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits component by selected item text first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of item which is currently selected. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public ListOperator(ContainerOperator cont, String text, int index) { this(cont, text, -1, index); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of item which is currently selected. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public ListOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public ListOperator(ContainerOperator cont, int index) { this((List) waitComponent(cont, new ListFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public ListOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches List in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return List instance or null if component was not found. */ public static List findList(Container cont, ComponentChooser chooser, int index) { return((List)findComponent(cont, new ListFinder(chooser), index)); } /** * Searches 0'th List in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return List instance or null if component was not found. */ public static List findList(Container cont, ComponentChooser chooser) { return(findList(cont, chooser, 0)); } public void setOutput(TestOut output) { super.setOutput(output.createErrorOutput()); this.output = output; } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (MultiSelListDriver)DriverManager. getDriver(DriverManager.MULTISELLIST_DRIVER_ID, getClass(), anotherOperator.getProperties()); } private int findItemIndex(String item, StringComparator comparator, int index){ int count = 0; for(int i = 0; i < getItemCount(); i++) { if(comparator.equals(getItem(i), item)) { if(count == index) { return(i); } else { count++; } } } return(-1); } /** * Searches an item index. * @param item item text. * @param index an ordinal index between appropriate ones. * @return an index. */ public int findItemIndex(String item, int index){ return(findItemIndex(item, getComparator(), index)); } /** * Searches an item index. * @param item item text. * @return an index. */ public int findItemIndex(String item){ return(findItemIndex(item, 0)); } private void selectItem(String item, StringComparator comparator, int index) { selectItem(findItemIndex(item, comparator, index)); } /** * Selects an item. * @param item item text. * @param index an ordinal index between appropriate ones. */ public void selectItem(String item, int index) { selectItem(item, getComparator(), index); } /** * Selects an item. * @param item item text. */ public void selectItem(String item) { selectItem(item, 0); } /** * Selects an item. * @param index an item index. */ public void selectItem(int index) { output.printLine("Select " + Integer.toString(index) + "`th item in list\n : " + toStringSource()); output.printGolden("Select " + Integer.toString(index) + "`th item in list"); driver.selectItem(this, index); if(getVerification()) { waitItemSelection(index, true); } } /** * Selects some items. * @param from start selection index. * @param to end selection index. */ public void selectItems(int from, int to) { output.printLine("Select items from " + Integer.toString(from) + "`th to " + Integer.toString(from) + "'th in list\n : " + toStringSource()); output.printGolden("Select items from " + Integer.toString(from) + "`th to " + Integer.toString(from) + "'th"); driver.selectItems(this, new int[] {from, to}); if(getVerification()) { waitItemsSelection(from, to, true); } } /** * Waits for items to be selected. * @param from Start selection inex * @param to End selection inex * @param selected Selected (true) or unselected (false). */ public void waitItemsSelection(final int from, final int to, final boolean selected) { getOutput().printLine("Wait items to be " + (selected ? "" : "un") + "selected in component \n : "+ toStringSource()); getOutput().printGolden("Wait items to be " + (selected ? "" : "un") + "selected"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { int[] indices = getSelectedIndexes(); for(int i = 0; i < indices.length; i++) { if(indices[i] < from || indices[i] > to) { return(false); } } return(true); } public String getDescription() { return("Items has been " + (selected ? "" : "un") + "selected"); } }); } /** * Waits for item to be selected. * @param itemIndex an item index to be selected. * @param selected Selected (true) or unselected (false). */ public void waitItemSelection(final int itemIndex, final boolean selected) { waitItemsSelection(itemIndex, itemIndex, selected); } public Hashtable getDump() { Hashtable result = super.getDump(); addToDump(result, ITEM_PREFIX_DPROP, ((List)getSource()).getItems()); addToDump(result, SELECTED_ITEM_PREFIX_DPROP, ((List)getSource()).getSelectedItems()); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps List.addActionListener(ActionListener) through queue*/ public void addActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("addActionListener") { public void map() { ((List)getSource()).addActionListener(actionListener); }});} /**Maps List.addItemListener(ItemListener) through queue*/ public void addItemListener(final ItemListener itemListener) { runMapping(new MapVoidAction("addItemListener") { public void map() { ((List)getSource()).addItemListener(itemListener); }});} /**Maps List.deselect(int) through queue*/ public void deselect(final int i) { runMapping(new MapVoidAction("deselect") { public void map() { ((List)getSource()).deselect(i); }});} /**Maps List.getItem(int) through queue*/ public String getItem(final int i) { return((String)runMapping(new MapAction("getItem") { public Object map() { return(((List)getSource()).getItem(i)); }}));} /**Maps List.getItemCount() through queue*/ public int getItemCount() { return(runMapping(new MapIntegerAction("getItemCount") { public int map() { return(((List)getSource()).getItemCount()); }}));} /**Maps List.getItems() through queue*/ public String[] getItems() { return((String[])runMapping(new MapAction("getItems") { public Object map() { return(((List)getSource()).getItems()); }}));} /**Maps List.getMinimumSize(int) through queue*/ public Dimension getMinimumSize(final int i) { return((Dimension)runMapping(new MapAction("getMinimumSize") { public Object map() { return(((List)getSource()).getMinimumSize(i)); }}));} /**Maps List.getPreferredSize(int) through queue*/ public Dimension getPreferredSize(final int i) { return((Dimension)runMapping(new MapAction("getPreferredSize") { public Object map() { return(((List)getSource()).getPreferredSize(i)); }}));} /**Maps List.getRows() through queue*/ public int getRows() { return(runMapping(new MapIntegerAction("getRows") { public int map() { return(((List)getSource()).getRows()); }}));} /**Maps List.getSelectedIndex() through queue*/ public int getSelectedIndex() { return(runMapping(new MapIntegerAction("getSelectedIndex") { public int map() { return(((List)getSource()).getSelectedIndex()); }}));} /**Maps List.getSelectedIndexes() through queue*/ public int[] getSelectedIndexes() { return((int[])runMapping(new MapAction("getSelectedIndexes") { public Object map() { return(((List)getSource()).getSelectedIndexes()); }}));} /**Maps List.getSelectedItem() through queue*/ public String getSelectedItem() { return((String)runMapping(new MapAction("getSelectedItem") { public Object map() { return(((List)getSource()).getSelectedItem()); }}));} /**Maps List.getSelectedItems() through queue*/ public String[] getSelectedItems() { return((String[])runMapping(new MapAction("getSelectedItems") { public Object map() { return(((List)getSource()).getSelectedItems()); }}));} /**Maps List.getSelectedObjects() through queue*/ public Object[] getSelectedObjects() { return((Object[])runMapping(new MapAction("getSelectedObjects") { public Object map() { return(((List)getSource()).getSelectedObjects()); }}));} /**Maps List.getVisibleIndex() through queue*/ public int getVisibleIndex() { return(runMapping(new MapIntegerAction("getVisibleIndex") { public int map() { return(((List)getSource()).getVisibleIndex()); }}));} /**Maps List.isIndexSelected(int) through queue*/ public boolean isIndexSelected(final int i) { return(runMapping(new MapBooleanAction("isIndexSelected") { public boolean map() { return(((List)getSource()).isIndexSelected(i)); }}));} /**Maps List.isMultipleMode() through queue*/ public boolean isMultipleMode() { return(runMapping(new MapBooleanAction("isMultipleMode") { public boolean map() { return(((List)getSource()).isMultipleMode()); }}));} /**Maps List.makeVisible(int) through queue*/ public void makeVisible(final int i) { runMapping(new MapVoidAction("makeVisible") { public void map() { ((List)getSource()).makeVisible(i); }});} /**Maps List.remove(int) through queue*/ public void remove(final int i) { runMapping(new MapVoidAction("remove") { public void map() { ((List)getSource()).remove(i); }});} /**Maps List.remove(String) through queue*/ public void remove(final String string) { runMapping(new MapVoidAction("remove") { public void map() { ((List)getSource()).remove(string); }});} /**Maps List.removeActionListener(ActionListener) through queue*/ public void removeActionListener(final ActionListener actionListener) { runMapping(new MapVoidAction("removeActionListener") { public void map() { ((List)getSource()).removeActionListener(actionListener); }});} /**Maps List.removeAll() through queue*/ public void removeAll() { runMapping(new MapVoidAction("removeAll") { public void map() { ((List)getSource()).removeAll(); }});} /**Maps List.removeItemListener(ItemListener) through queue*/ public void removeItemListener(final ItemListener itemListener) { runMapping(new MapVoidAction("removeItemListener") { public void map() { ((List)getSource()).removeItemListener(itemListener); }});} /**Maps List.replaceItem(String, int) through queue*/ public void replaceItem(final String string, final int i) { runMapping(new MapVoidAction("replaceItem") { public void map() { ((List)getSource()).replaceItem(string, i); }});} /**Maps List.select(int) through queue*/ public void select(final int i) { runMapping(new MapVoidAction("select") { public void map() { ((List)getSource()).select(i); }});} /**Maps List.setMultipleMode(boolean) through queue*/ public void setMultipleMode(final boolean b) { runMapping(new MapVoidAction("setMultipleMode") { public void map() { ((List)getSource()).setMultipleMode(b); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Allows to find component by item text. */ public static class ListByItemFinder implements ComponentChooser { String label; int itemIndex; StringComparator comparator; /** * Constructs ListByItemFinder. * @param lb a text pattern * @param ii item index to check. If equal to -1, selected item is checked. * @param comparator specifies string comparision algorithm. */ public ListByItemFinder(String lb, int ii, StringComparator comparator) { label = lb; itemIndex = ii; this.comparator = comparator; } /** * Constructs ListByItemFinder. * @param lb a text pattern * @param ii item index to check. If equal to -1, selected item is checked. */ public ListByItemFinder(String lb, int ii) { this(lb, ii, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof List) { if(label == null) { return(true); } if(((List)comp).getItemCount() > itemIndex) { int ii = itemIndex; if(ii == -1) { ii = ((List)comp).getSelectedIndex(); if(ii == -1) { return(false); } } return(comparator.equals(((List)comp).getItem(ii), label)); } } return(false); } public String getDescription() { return("List with text \"" + label + "\" in " + (new Integer(itemIndex)).toString() + "'th item"); } } /** * Checks component type. */ public static class ListFinder extends Finder { /** * Constructs ListFinder. * @param sf other searching criteria. */ public ListFinder(ComponentChooser sf) { super(List.class, sf); } /** * Constructs ListFinder. */ public ListFinder() { super(List.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JToggleButtonOperator.java0000644000175000017500000002500611245712237024416 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Container; import javax.swing.JToggleButton; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.TimeoutExpiredException; /** * *

Timeouts used:
* AbstractButtonOperator.PushButtonTimeout - time between button pressing and releasing
* ComponentOperator.WaitComponentTimeout - time to wait button displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait button enabled
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JToggleButtonOperator extends AbstractButtonOperator{ /** * Constructor. * @param b a component */ public JToggleButtonOperator(JToggleButton b) { super(b); } /** * Constructs a JToggleButtonOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JToggleButtonOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JToggleButton)cont. waitSubComponent(new JToggleButtonFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JToggleButtonOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JToggleButtonOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JToggleButtonOperator(ContainerOperator cont, String text, int index) { this((JToggleButton) waitComponent(cont, new JToggleButtonFinder(new AbstractButtonOperator. AbstractButtonByLabelFinder(text, cont.getComparator())), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JToggleButtonOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JToggleButtonOperator(ContainerOperator cont, int index) { this((JToggleButton) waitComponent(cont, new JToggleButtonFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JToggleButtonOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JToggleButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JToggleButton instance or null if component was not found. */ public static JToggleButton findJToggleButton(Container cont, ComponentChooser chooser, int index) { return((JToggleButton)findAbstractButton(cont, new JToggleButtonFinder(chooser), index)); } /** * Searches 0'th JToggleButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JToggleButton instance or null if component was not found. */ public static JToggleButton findJToggleButton(Container cont, ComponentChooser chooser) { return(findJToggleButton(cont, chooser, 0)); } /** * Searches JToggleButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JToggleButton instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JToggleButton findJToggleButton(Container cont, String text, boolean ce, boolean ccs, int index) { return(findJToggleButton(cont, new JToggleButtonFinder(new AbstractButtonOperator. AbstractButtonByLabelFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Searches JToggleButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JToggleButton instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JToggleButton findJToggleButton(Container cont, String text, boolean ce, boolean ccs) { return(findJToggleButton(cont, text, ce, ccs, 0)); } /** * Waits JToggleButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JToggleButton instance. * @throws TimeoutExpiredException */ public static JToggleButton waitJToggleButton(Container cont, ComponentChooser chooser, int index) { return((JToggleButton)waitAbstractButton(cont, new JToggleButtonFinder(chooser), index)); } /** * Waits 0'th JToggleButton in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JToggleButton instance. * @throws TimeoutExpiredException */ public static JToggleButton waitJToggleButton(Container cont, ComponentChooser chooser) { return(waitJToggleButton(cont, chooser, 0)); } /** * Waits JToggleButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JToggleButton instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JToggleButton waitJToggleButton(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitJToggleButton(cont, new JToggleButtonFinder(new AbstractButtonOperator. AbstractButtonByLabelFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Waits JToggleButton by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JToggleButton instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JToggleButton waitJToggleButton(Container cont, String text, boolean ce, boolean ccs) { return(waitJToggleButton(cont, text, ce, ccs, 0)); } /** * Prepares the button to click. */ protected void prepareToClick() { makeComponentVisible(); } /** * Checks component type. */ public static class JToggleButtonFinder extends Finder { /** * Constructs JToggleButtonFinder. * @param sf other searching criteria. */ public JToggleButtonFinder(ComponentChooser sf) { super(JToggleButton.class, sf); } /** * Constructs JToggleButtonFinder. */ public JToggleButtonFinder() { super(JToggleButton.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JSplitPaneOperator.java0000644000175000017500000006261011245712237023702 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.util.Hashtable; import javax.swing.JButton; import javax.swing.JSplitPane; import javax.swing.plaf.SplitPaneUI; import javax.swing.plaf.basic.BasicSplitPaneDivider; import org.netbeans.jemmy.Action; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.ScrollDriver; import org.netbeans.jemmy.drivers.scrolling.ScrollAdjuster; import org.netbeans.jemmy.util.EmptyVisualizer; /** *

Timeouts used:
* JSplitPaneOperator.ScrollClickTimeout - time for simple scroll click
* JSplitPaneOperator.BetweenClickTimeout - time to sleep between scroll clicks
* JSplitPaneOperator.WholeScrollTimeout - time for the whole scrolling
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * * Class to operate with javax.swing.JSplitPane component * */ public class JSplitPaneOperator extends JComponentOperator implements Timeoutable, Outputable{ /** * Identifier for a "minimum" property. * @see #getDump */ public static final String MINIMUM_DPROP = "Minimum"; /** * Identifier for a "maximum" property. * @see #getDump */ public static final String MAXIMUM_DPROP = "Maximum"; /** * Identifier for a "value" property. * @see #getDump */ public static final String VALUE_DPROP = "Value"; /** * Identifier for a "orientation" property. * @see #getDump */ public static final String ORIENTATION_DPROP = "Orientation"; /** * Identifier for a "HORIZONTAL" value of "orientation" property. * @see #getDump */ public static final String HORIZONTAL_ORIENTATION_DPROP_VALUE = "HORIZONTAL"; /** * Identifier for a "VERTICAL" value of "orientation" property. * @see #getDump */ public static final String VERTICAL_ORIENTATION_DPROP_VALUE = "VERTICAL"; /** * Identifier for a "one touch expendable" property. * @see #getDump */ public static final String IS_ONE_TOUCH_EXPANDABLE_DPROP = "One touch expandable"; private final static long SCROLL_CLICK_TIMEOUT = 0; private final static long BETWEEN_CLICK_TIMEOUT = 0; private final static long WHOLE_SCROLL_TIMEOUT = 60000; private Timeouts timeouts; private TestOut output; private ContainerOperator divider; private ScrollDriver driver; /** * Constructor. * @param b JSplitPane component. */ public JSplitPaneOperator(JSplitPane b) { super(b); driver = DriverManager.getScrollDriver(getClass()); } /** * Constructs a JSplitPaneOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JSplitPaneOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JSplitPane)cont. waitSubComponent(new JSplitPaneFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JSplitPaneOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JSplitPaneOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JSplitPaneOperator(ContainerOperator cont, int index) { this((JSplitPane)waitComponent(cont, new JSplitPaneFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @throws TimeoutExpiredException */ public JSplitPaneOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JSplitPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JSplitPane instance or null if component was not found. */ public static JSplitPane findJSplitPane(Container cont, ComponentChooser chooser, int index) { return((JSplitPane)findComponent(cont, new JSplitPaneFinder(chooser), index)); } /** * Searches 0'th JSplitPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JSplitPane instance or null if component was not found. */ public static JSplitPane findJSplitPane(Container cont, ComponentChooser chooser) { return(findJSplitPane(cont, chooser, 0)); } /** * Searches JSplitPane in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JSplitPane instance or null if component was not found. */ public static JSplitPane findJSplitPane(Container cont, int index) { return(findJSplitPane(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JSplitPane instance"), index)); } /** * Searches 0'th JSplitPane in container. * @param cont Container to search component in. * @return JSplitPane instance or null if component was not found. */ public static JSplitPane findJSplitPane(Container cont) { return(findJSplitPane(cont, 0)); } /** * Searches JSplitPane object which component lies on. * @param comp Component to find JSplitPane under. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JSplitPane instance or null if component was not found. */ public static JSplitPane findJSplitPaneUnder(Component comp, ComponentChooser chooser) { return((JSplitPane)findContainerUnder(comp, new JSplitPaneFinder(chooser))); } /** * Searches JSplitPane object which component lies on. * @param comp Component to find JSplitPane under. * @return JSplitPane instance or null if component was not found. */ public static JSplitPane findJSplitPaneUnder(Component comp) { return(findJSplitPaneUnder(comp, new JSplitPaneFinder())); } /** * Waits JSplitPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JSplitPane instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JSplitPane waitJSplitPane(Container cont, ComponentChooser chooser, int index) { return((JSplitPane)waitComponent(cont, new JSplitPaneFinder(chooser), index)); } /** * Waits 0'th JSplitPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JSplitPane instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JSplitPane waitJSplitPane(Container cont, ComponentChooser chooser) { return(waitJSplitPane(cont, chooser, 0)); } /** * Waits JSplitPane in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JSplitPane instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JSplitPane waitJSplitPane(Container cont, int index) { return(waitJSplitPane(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JSplitPane instance"), index)); } /** * Waits 0'th JSplitPane in container. * @param cont Container to search component in. * @return JSplitPane instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JSplitPane waitJSplitPane(Container cont) { return(waitJSplitPane(cont, 0)); } static { Timeouts.initDefault("JSplitPaneOperator.ScrollClickTimeout", SCROLL_CLICK_TIMEOUT); Timeouts.initDefault("JSplitPaneOperator.BetweenClickTimeout", BETWEEN_CLICK_TIMEOUT); Timeouts.initDefault("JSplitPaneOperator.WholeScrollTimeout", WHOLE_SCROLL_TIMEOUT); } public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; Timeouts times = timeouts; times.setTimeout("ComponentOperator.BeforeDragTimeout", 0); times.setTimeout("ComponentOperator.AfterDragTimeout", times.getTimeout("JSplitPaneOperator.ScrollClickTimeout")); super.setTimeouts(times); } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (ScrollDriver)DriverManager. getDriver(DriverManager.SCROLL_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Searches divider inside split pane. * @return an operator for the divider. */ public BasicSplitPaneDivider findDivider() { return((BasicSplitPaneDivider)waitSubComponent(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp instanceof BasicSplitPaneDivider); } public String getDescription() { return(""); } })); } /** * Searches divider inside split pane. * @return an operator for the divider. */ public ContainerOperator getDivider() { if(divider == null) { divider = new ContainerOperator(findDivider()); divider.copyEnvironment(this); divider.setOutput(getOutput().createErrorOutput()); } return(divider); } /** * Scrolls to the position defined by a ScrollAdjuster implementation. * @param adj defines scrolling direction, and so on. * @throws TimeoutExpiredException */ public void scrollTo(final ScrollAdjuster adj) { produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scroll(JSplitPaneOperator.this, adj); return(null); } public String getDescription() { return("Moving a divider"); } }, getTimeouts().getTimeout("JSplitPaneOperator.WholeScrollTimeout")); } /** * Changes divider location. * @param dividerLocation location to move divider to. */ public void moveDivider(int dividerLocation) { output.printTrace("Move JSplitPane divider to " + Integer.toString(dividerLocation) + " location. JSplitPane : \n" + toStringSource()); output.printGolden("Move JSplitPane divider to " + Integer.toString(dividerLocation) + " location"); scrollTo(new ValueScrollAdjuster(dividerLocation)); } /** * Changes divider location. * @param proportionalLocation Proportional location. * Should be great then 0 and less then 1. */ public void moveDivider(double proportionalLocation) { output.printTrace("Move JSplitPane divider to " + Double.toString(proportionalLocation) + " proportional location. JSplitPane : \n" + toStringSource()); output.printGolden("Move JSplitPane divider to " + Double.toString(proportionalLocation) + " proportional location"); scrollTo(new ValueScrollAdjuster(getMinimumDividerLocation() + (int)(proportionalLocation * (getMaximumDividerLocation() - getMinimumDividerLocation())))); } /** * Moves the divider all the way to the left/top. */ public void moveToMinimum() { output.printTrace("Scroll JSplitPane to minimum. JSplitPane : \n" + toStringSource()); output.printGolden("Scroll JSplitPane to minimum."); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scrollToMinimum(JSplitPaneOperator.this, getOrientation()); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("JSplitPaneOperator.WholeScrollTimeout")); } /** * Moves the divider all the way to the right/bottom. */ public void moveToMaximum() { output.printTrace("Scroll JSplitPane to maximum. JSplitPane : \n" + toStringSource()); output.printGolden("Scroll JSplitPane to maximum."); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scrollToMaximum(JSplitPaneOperator.this, getOrientation()); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("JSplitPaneOperator.WholeScrollTimeout")); } /** * Pushes one time right(bottom) expand button. * @throws TimeoutExpiredException */ public void expandRight() { String mess = "Expand "; if(getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { mess = mess + "right"; } else { mess = mess + "bottom"; } output.printTrace(mess + " JSplitPane side. JSplitPane : \n" + toStringSource()); output.printGolden(mess + " JSplitPane side."); expandTo(0); } /** * Pushes one time left(top) expand button. * @throws TimeoutExpiredException */ public void expandLeft() { String mess = "Expand "; if(getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { mess = mess + "left"; } else { mess = mess + "top"; } output.printTrace(mess + " JSplitPane side. JSplitPane : \n" + toStringSource()); output.printGolden(mess + " JSplitPane side."); expandTo(1); } public Hashtable getDump() { Hashtable result = super.getDump(); result.put(MINIMUM_DPROP, Integer.toString(((JSplitPane)getSource()).getMinimumDividerLocation())); result.put(MAXIMUM_DPROP, Integer.toString(((JSplitPane)getSource()).getMaximumDividerLocation())); result.put(ORIENTATION_DPROP, (((JSplitPane)getSource()).getOrientation() == JSplitPane.HORIZONTAL_SPLIT) ? HORIZONTAL_ORIENTATION_DPROP_VALUE : VERTICAL_ORIENTATION_DPROP_VALUE); result.put(VALUE_DPROP, Integer.toString(((JSplitPane)getSource()).getDividerLocation())); result.put(IS_ONE_TOUCH_EXPANDABLE_DPROP, ((JSplitPane)getSource()).isOneTouchExpandable() ? "true" : "false"); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JSplitPane.getBottomComponent() through queue*/ public Component getBottomComponent() { return((Component)runMapping(new MapAction("getBottomComponent") { public Object map() { return(((JSplitPane)getSource()).getBottomComponent()); }}));} /**Maps JSplitPane.getDividerLocation() through queue*/ public int getDividerLocation() { return(runMapping(new MapIntegerAction("getDividerLocation") { public int map() { return(((JSplitPane)getSource()).getDividerLocation()); }}));} /**Maps JSplitPane.getDividerSize() through queue*/ public int getDividerSize() { return(runMapping(new MapIntegerAction("getDividerSize") { public int map() { return(((JSplitPane)getSource()).getDividerSize()); }}));} /**Maps JSplitPane.getLastDividerLocation() through queue*/ public int getLastDividerLocation() { return(runMapping(new MapIntegerAction("getLastDividerLocation") { public int map() { return(((JSplitPane)getSource()).getLastDividerLocation()); }}));} /**Maps JSplitPane.getLeftComponent() through queue*/ public Component getLeftComponent() { return((Component)runMapping(new MapAction("getLeftComponent") { public Object map() { return(((JSplitPane)getSource()).getLeftComponent()); }}));} /**Maps JSplitPane.getMaximumDividerLocation() through queue*/ public int getMaximumDividerLocation() { return(runMapping(new MapIntegerAction("getMaximumDividerLocation") { public int map() { return(((JSplitPane)getSource()).getMaximumDividerLocation()); }}));} /**Maps JSplitPane.getMinimumDividerLocation() through queue*/ public int getMinimumDividerLocation() { return(runMapping(new MapIntegerAction("getMinimumDividerLocation") { public int map() { return(((JSplitPane)getSource()).getMinimumDividerLocation()); }}));} /**Maps JSplitPane.getOrientation() through queue*/ public int getOrientation() { return(runMapping(new MapIntegerAction("getOrientation") { public int map() { return(((JSplitPane)getSource()).getOrientation()); }}));} /**Maps JSplitPane.getRightComponent() through queue*/ public Component getRightComponent() { return((Component)runMapping(new MapAction("getRightComponent") { public Object map() { return(((JSplitPane)getSource()).getRightComponent()); }}));} /**Maps JSplitPane.getTopComponent() through queue*/ public Component getTopComponent() { return((Component)runMapping(new MapAction("getTopComponent") { public Object map() { return(((JSplitPane)getSource()).getTopComponent()); }}));} /**Maps JSplitPane.getUI() through queue*/ public SplitPaneUI getUI() { return((SplitPaneUI)runMapping(new MapAction("getUI") { public Object map() { return(((JSplitPane)getSource()).getUI()); }}));} /**Maps JSplitPane.isContinuousLayout() through queue*/ public boolean isContinuousLayout() { return(runMapping(new MapBooleanAction("isContinuousLayout") { public boolean map() { return(((JSplitPane)getSource()).isContinuousLayout()); }}));} /**Maps JSplitPane.isOneTouchExpandable() through queue*/ public boolean isOneTouchExpandable() { return(runMapping(new MapBooleanAction("isOneTouchExpandable") { public boolean map() { return(((JSplitPane)getSource()).isOneTouchExpandable()); }}));} /**Maps JSplitPane.resetToPreferredSizes() through queue*/ public void resetToPreferredSizes() { runMapping(new MapVoidAction("resetToPreferredSizes") { public void map() { ((JSplitPane)getSource()).resetToPreferredSizes(); }});} /**Maps JSplitPane.setBottomComponent(Component) through queue*/ public void setBottomComponent(final Component component) { runMapping(new MapVoidAction("setBottomComponent") { public void map() { ((JSplitPane)getSource()).setBottomComponent(component); }});} /**Maps JSplitPane.setContinuousLayout(boolean) through queue*/ public void setContinuousLayout(final boolean b) { runMapping(new MapVoidAction("setContinuousLayout") { public void map() { ((JSplitPane)getSource()).setContinuousLayout(b); }});} /**Maps JSplitPane.setDividerLocation(double) through queue*/ public void setDividerLocation(final double d) { runMapping(new MapVoidAction("setDividerLocation") { public void map() { ((JSplitPane)getSource()).setDividerLocation(d); }});} /**Maps JSplitPane.setDividerLocation(int) through queue*/ public void setDividerLocation(final int i) { runMapping(new MapVoidAction("setDividerLocation") { public void map() { ((JSplitPane)getSource()).setDividerLocation(i); }});} /**Maps JSplitPane.setDividerSize(int) through queue*/ public void setDividerSize(final int i) { runMapping(new MapVoidAction("setDividerSize") { public void map() { ((JSplitPane)getSource()).setDividerSize(i); }});} /**Maps JSplitPane.setLastDividerLocation(int) through queue*/ public void setLastDividerLocation(final int i) { runMapping(new MapVoidAction("setLastDividerLocation") { public void map() { ((JSplitPane)getSource()).setLastDividerLocation(i); }});} /**Maps JSplitPane.setLeftComponent(Component) through queue*/ public void setLeftComponent(final Component component) { runMapping(new MapVoidAction("setLeftComponent") { public void map() { ((JSplitPane)getSource()).setLeftComponent(component); }});} /**Maps JSplitPane.setOneTouchExpandable(boolean) through queue*/ public void setOneTouchExpandable(final boolean b) { runMapping(new MapVoidAction("setOneTouchExpandable") { public void map() { ((JSplitPane)getSource()).setOneTouchExpandable(b); }});} /**Maps JSplitPane.setOrientation(int) through queue*/ public void setOrientation(final int i) { runMapping(new MapVoidAction("setOrientation") { public void map() { ((JSplitPane)getSource()).setOrientation(i); }});} /**Maps JSplitPane.setRightComponent(Component) through queue*/ public void setRightComponent(final Component component) { runMapping(new MapVoidAction("setRightComponent") { public void map() { ((JSplitPane)getSource()).setRightComponent(component); }});} /**Maps JSplitPane.setTopComponent(Component) through queue*/ public void setTopComponent(final Component component) { runMapping(new MapVoidAction("setTopComponent") { public void map() { ((JSplitPane)getSource()).setTopComponent(component); }});} /**Maps JSplitPane.setUI(SplitPaneUI) through queue*/ public void setUI(final SplitPaneUI splitPaneUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JSplitPane)getSource()).setUI(splitPaneUI); }});} //End of mapping // //////////////////////////////////////////////////////// private void expandTo(int index) { makeComponentVisible(); JButtonOperator bo = new JButtonOperator((JButton)getDivider(). waitSubComponent(new JButtonOperator. JButtonFinder(ComponentSearcher. getTrueChooser("JButton")), index)); bo.copyEnvironment(getDivider()); bo.setVisualizer(new EmptyVisualizer()); bo.push(); } /** * Checks component type. */ public static class JSplitPaneFinder extends Finder { /** * Constructs JSplitPaneFinder. * @param sf other searching criteria. */ public JSplitPaneFinder(ComponentChooser sf) { super(JSplitPane.class, sf); } /** * Constructs JSplitPaneFinder. */ public JSplitPaneFinder() { super(JSplitPane.class); } } private class ValueScrollAdjuster implements ScrollAdjuster { int value; public ValueScrollAdjuster(int value) { this.value = value; } public int getScrollDirection() { if(getDividerLocation() == value) { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } else { return((getDividerLocation() < value) ? ScrollAdjuster.INCREASE_SCROLL_DIRECTION : ScrollAdjuster.DECREASE_SCROLL_DIRECTION); } } public int getScrollOrientation() { return(getOrientation()); } public String getDescription() { return("Scroll to " + Integer.toString(value) + " value"); } } } Jemmy2/src/org/netbeans/jemmy/operators/JPasswordFieldOperator.java0000644000175000017500000003124511245712237024551 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Container; import java.util.Hashtable; import javax.swing.JPasswordField; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.TimeoutExpiredException; /** *

Timeouts used:
* JTextComponentOperator.PushKeyTimeout - time between key pressing and releasing during text typing
* JTextComponentOperator.BetweenKeysTimeout - time to sleep between two chars typing
* JTextComponentOperator.ChangeCaretPositionTimeout - maximum time to chenge caret position
* JTextComponentOperator.TypeTextTimeout - maximum time to type text
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.WaitFocusTimeout - time to wait component focus
* JScrollBarOperator.OneScrollClickTimeout - time for one scroll click
* JScrollBarOperator.WholeScrollTimeout - time for the whole scrolling
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JPasswordFieldOperator extends JTextFieldOperator{ /** * Identifier for a "echo char" property. * @see #getDump */ public static final String ECHO_CHAR_DPROP = "Echo char"; /** * Constructor. * @param b a component */ public JPasswordFieldOperator(JPasswordField b) { super(b); } /** * Constructs a JPasswordFieldOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JPasswordFieldOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JPasswordField)cont. waitSubComponent(new JPasswordFieldFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JPasswordFieldOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JPasswordFieldOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JPasswordFieldOperator(ContainerOperator cont, String text, int index) { this((JPasswordField) waitComponent(cont, new JPasswordFieldFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, cont.getComparator())), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JPasswordFieldOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JPasswordFieldOperator(ContainerOperator cont, int index) { this((JPasswordField) waitComponent(cont, new JPasswordFieldFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JPasswordFieldOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JPasswordField in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JPasswordField instance or null if component was not found. */ public static JPasswordField findJPasswordField(Container cont, ComponentChooser chooser, int index) { return((JPasswordField)findJTextComponent(cont, new JPasswordFieldFinder(chooser), index)); } /** * Searches JPasswordField in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JPasswordField instance or null if component was not found. */ public static JPasswordField findJPasswordField(Container cont, ComponentChooser chooser) { return(findJPasswordField(cont, chooser, 0)); } /** * Searches JPasswordField by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JPasswordField instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JPasswordField findJPasswordField(Container cont, String text, boolean ce, boolean ccs, int index) { return(findJPasswordField(cont, new JPasswordFieldFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Searches JPasswordField by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JPasswordField instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JPasswordField findJPasswordField(Container cont, String text, boolean ce, boolean ccs) { return(findJPasswordField(cont, text, ce, ccs, 0)); } /** * Waits JPasswordField in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JPasswordField instance. * @throws TimeoutExpiredException */ public static JPasswordField waitJPasswordField(Container cont, ComponentChooser chooser, int index){ return((JPasswordField)waitJTextComponent(cont, new JPasswordFieldFinder(chooser), index)); } /** * Waits JPasswordField in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JPasswordField instance. * @throws TimeoutExpiredException */ public static JPasswordField waitJPasswordField(Container cont, ComponentChooser chooser) { return(waitJPasswordField(cont, chooser, 0)); } /** * Waits JPasswordField by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JPasswordField instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JPasswordField waitJPasswordField(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitJPasswordField(cont, new JPasswordFieldFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Waits JPasswordField by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JPasswordField instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JPasswordField waitJPasswordField(Container cont, String text, boolean ce, boolean ccs) { return(waitJPasswordField(cont, text, ce, ccs, 0)); } public Hashtable getDump() { Hashtable result = super.getDump(); result.put(ECHO_CHAR_DPROP, new Character(((JPasswordField)getSource()).getEchoChar()).toString()); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JPasswordField.echoCharIsSet() through queue*/ public boolean echoCharIsSet() { return(runMapping(new MapBooleanAction("echoCharIsSet") { public boolean map() { return(((JPasswordField)getSource()).echoCharIsSet()); }}));} /**Maps JPasswordField.getEchoChar() through queue*/ public char getEchoChar() { return(runMapping(new MapCharacterAction("getEchoChar") { public char map() { return(((JPasswordField)getSource()).getEchoChar()); }}));} /**Maps JPasswordField.getPassword() through queue*/ public char[] getPassword() { return((char[])runMapping(new MapAction("getPassword") { public Object map() { return(((JPasswordField)getSource()).getPassword()); }}));} /**Maps JPasswordField.setEchoChar(char) through queue*/ public void setEchoChar(final char c) { runMapping(new MapVoidAction("setEchoChar") { public void map() { ((JPasswordField)getSource()).setEchoChar(c); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Checks component type. */ public static class JPasswordFieldFinder extends Finder { /** * Constructs JPasswordFieldFinder. * @param sf other searching criteria. */ public JPasswordFieldFinder(ComponentChooser sf) { super(JPasswordField.class, sf); } /** * Constructs JPasswordFieldFinder. */ public JPasswordFieldFinder() { super(JPasswordField.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JRadioButtonMenuItemOperator.java0000644000175000017500000001656211245712237025706 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import javax.swing.JRadioButtonMenuItem; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.JemmyProperties; /** * *

Timeouts used:
* JMenuItemOperator.PushMenuTimeout - time between button pressing and releasing
* ComponentOperator.WaitComponentTimeout - time to wait button displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait button enabled
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JRadioButtonMenuItemOperator extends JMenuItemOperator { /** * Constructor. * @param item a component */ public JRadioButtonMenuItemOperator(JRadioButtonMenuItem item) { super(item); setTimeouts(JemmyProperties.getProperties().getTimeouts()); setOutput(JemmyProperties.getProperties().getOutput()); } /** * Constructs a JRadioButtonMenuItemOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JRadioButtonMenuItemOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JRadioButtonMenuItem)cont. waitSubComponent(new JRadioButtonMenuItemFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JRadioButtonMenuItemOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JRadioButtonMenuItemOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public JRadioButtonMenuItemOperator(ContainerOperator cont, String text, int index) { this((JRadioButtonMenuItem)waitComponent(cont, new JRadioButtonMenuItemByLabelFinder(text, cont.getComparator()), index)); setTimeouts(cont.getTimeouts()); setOutput(cont.getOutput()); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public JRadioButtonMenuItemOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. */ public JRadioButtonMenuItemOperator(ContainerOperator cont, int index) { this((JRadioButtonMenuItem) waitComponent(cont, new JRadioButtonMenuItemFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container */ public JRadioButtonMenuItemOperator(ContainerOperator cont) { this(cont, 0); } //////////////////////////////////////////////////////// //Mapping // //End of mapping // //////////////////////////////////////////////////////// /** * Allows to find component by text. */ public static class JRadioButtonMenuItemByLabelFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs JRadioButtonMenuItemByLabelFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public JRadioButtonMenuItemByLabelFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs JRadioButtonMenuItemByLabelFinder. * @param lb a text pattern */ public JRadioButtonMenuItemByLabelFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JRadioButtonMenuItem) { if(((JRadioButtonMenuItem)comp).getText() != null) { return(comparator.equals(((JRadioButtonMenuItem)comp).getText(), label)); } } return(false); } public String getDescription() { return("JRadioButtonMenuItem with text \"" + label + "\""); } } /** * Checks component type. */ public static class JRadioButtonMenuItemFinder extends Finder { /** * Constructs JRadioButtonMenuItemFinder. * @param sf other searching criteria. */ public JRadioButtonMenuItemFinder(ComponentChooser sf) { super(JRadioButtonMenuItem.class, sf); } /** * Constructs JRadioButtonMenuItemFinder. */ public JRadioButtonMenuItemFinder() { super(JRadioButtonMenuItem.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/LabelOperator.java0000644000175000017500000002770711245712237022720 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Label; import java.util.Hashtable; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.TimeoutExpiredException; /** *

Timeouts used:
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
. * * @see org.netbeans.jemmy.Timeouts * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class LabelOperator extends ComponentOperator { /** * Identifier for a "text" property. * @see #getDump */ public static final String TEXT_DPROP = "Text"; /** * Constructor. * @param b a component */ public LabelOperator(Label b) { super(b); } /** * Constructs a LabelOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public LabelOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((Label)cont. waitSubComponent(new LabelFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a LabelOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public LabelOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public LabelOperator(ContainerOperator cont, String text, int index) { this((Label)waitComponent(cont, new LabelByLabelFinder(text, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public LabelOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public LabelOperator(ContainerOperator cont, int index) { this((Label) waitComponent(cont, new LabelFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public LabelOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches Label in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return Label instance or null if component was not found. */ public static Label findLabel(Container cont, ComponentChooser chooser, int index) { return((Label)findComponent(cont, new LabelFinder(chooser), index)); } /** * Searches Label in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return Label instance or null if component was not found. */ public static Label findLabel(Container cont, ComponentChooser chooser) { return(findLabel(cont, chooser, 0)); } /** * Searches Label by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return Label instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static Label findLabel(Container cont, String text, boolean ce, boolean ccs, int index) { return(findLabel(cont, new LabelByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches Label by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return Label instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static Label findLabel(Container cont, String text, boolean ce, boolean ccs) { return(findLabel(cont, text, ce, ccs, 0)); } /** * Waits Label in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return Label instance. * @throws TimeoutExpiredException */ public static Label waitLabel(final Container cont, final ComponentChooser chooser, final int index) { return((Label)waitComponent(cont, new LabelFinder(chooser), index)); } /** * Waits Label in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return Label instance. * @throws TimeoutExpiredException */ public static Label waitLabel(Container cont, ComponentChooser chooser) { return(waitLabel(cont, chooser, 0)); } /** * Waits Label by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return Label instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static Label waitLabel(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitLabel(cont, new LabelByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits Label by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return Label instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static Label waitLabel(Container cont, String text, boolean ce, boolean ccs) { return(waitLabel(cont, text, ce, ccs, 0)); } public Hashtable getDump() { Hashtable result = super.getDump(); if(((Label)getSource()).getText() != null) { result.put(TEXT_DPROP, ((Label)getSource()).getText()); } else { result.put(TEXT_DPROP, "null"); } return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps Label.getAlignment() through queue*/ public int getAlignment() { return(runMapping(new MapIntegerAction("getAlignment") { public int map() { return(((Label)getSource()).getAlignment()); }}));} /**Maps Label.getText() through queue*/ public String getText() { return((String)runMapping(new MapAction("getText") { public Object map() { return(((Label)getSource()).getText()); }}));} /**Maps Label.setAlignment(int) through queue*/ public void setAlignment(final int i) { runMapping(new MapVoidAction("setAlignment") { public void map() { ((Label)getSource()).setAlignment(i); }});} /**Maps Label.setText(String) through queue*/ public void setText(final String string) { runMapping(new MapVoidAction("setText") { public void map() { ((Label)getSource()).setText(string); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Allows to find component by LabelByLabelFinder. */ public static class LabelByLabelFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs LabelByLabelFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public LabelByLabelFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs LabelByLabelFinder. * @param lb a text pattern */ public LabelByLabelFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof Label) { if(((Label)comp).getText() != null) { return(comparator.equals(((Label)comp).getText(), label)); } } return(false); } public String getDescription() { return("Label with text \"" + label + "\""); } } /** * Checks component type. */ public static class LabelFinder extends Finder { /** * Constructs LabelFinder. * @param sf other searching criteria. */ public LabelFinder(ComponentChooser sf) { super(Label.class, sf); } /** * Constructs LabelFinder. */ public LabelFinder() { super(Label.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/CheckboxOperator.java0000644000175000017500000004042111245712237023413 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Checkbox; import java.awt.CheckboxGroup; import java.awt.Component; import java.awt.Container; import java.awt.event.ItemListener; import java.util.Hashtable; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.drivers.ButtonDriver; import org.netbeans.jemmy.drivers.DriverManager; /** * *

Timeouts used:
* ButtonOperator.PushButtonTimeout - time between checkbox pressing and releasing
* ComponentOperator.WaitComponentTimeout - time to wait checkbox displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait checkbox enabled
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class CheckboxOperator extends ComponentOperator implements Outputable { /** * Identifier for a label property. * @see #getDump */ public static final String TEXT_DPROP = "Label"; private TestOut output; ButtonDriver driver; /** * Constructor. * @param b a component */ public CheckboxOperator(Checkbox b) { super(b); driver = DriverManager.getButtonDriver(getClass()); } /** * Constructs an CheckboxOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public CheckboxOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((Checkbox)cont. waitSubComponent(new CheckboxFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs an CheckboxOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. */ public CheckboxOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont container * @param text Checkbox text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public CheckboxOperator(ContainerOperator cont, String text, int index) { this((Checkbox) waitComponent(cont, new CheckboxByLabelFinder(text, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont container * @param text Checkbox text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public CheckboxOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public CheckboxOperator(ContainerOperator cont, int index) { this((Checkbox) waitComponent(cont, new CheckboxFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont container * @throws TimeoutExpiredException */ public CheckboxOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches Checkbox in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return Checkbox instance or null if component was not found. */ public static Checkbox findCheckbox(Container cont, ComponentChooser chooser, int index) { return((Checkbox)findComponent(cont, new CheckboxFinder(chooser), index)); } /** * Searches 0'th Checkbox in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return Checkbox instance or null if component was not found. */ public static Checkbox findCheckbox(Container cont, ComponentChooser chooser) { return(findCheckbox(cont, chooser, 0)); } /** * Searches Checkbox by text. * @param cont Container to search component in. * @param text Checkbox text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return Checkbox instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static Checkbox findCheckbox(Container cont, String text, boolean ce, boolean ccs, int index) { return(findCheckbox(cont, new CheckboxByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches Checkbox by text. * @param cont Container to search component in. * @param text Checkbox text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return Checkbox instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static Checkbox findCheckbox(Container cont, String text, boolean ce, boolean ccs) { return(findCheckbox(cont, text, ce, ccs, 0)); } /** * Waits Checkbox in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return Checkbox instance. * @throws TimeoutExpiredException */ public static Checkbox waitCheckbox(Container cont, ComponentChooser chooser, int index) { return((Checkbox)waitComponent(cont, new CheckboxFinder(chooser), index)); } /** * Waits 0'th Checkbox in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return Checkbox instance. * @throws TimeoutExpiredException */ public static Checkbox waitCheckbox(Container cont, ComponentChooser chooser) { return(waitCheckbox(cont, chooser, 0)); } /** * Waits Checkbox by text. * @param cont Container to search component in. * @param text Checkbox text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return Checkbox instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static Checkbox waitCheckbox(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitCheckbox(cont, new CheckboxByLabelFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits Checkbox by text. * @param cont Container to search component in. * @param text Checkbox text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return Checkbox instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static Checkbox waitCheckbox(Container cont, String text, boolean ce, boolean ccs) { return(waitCheckbox(cont, text, ce, ccs, 0)); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (ButtonDriver)DriverManager. getDriver(DriverManager.BUTTON_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Changes selection if necessary. * Uses a ButtonDriver registered for this operator. * @param newValue a button selection. */ public void changeSelection(boolean newValue) { makeComponentVisible(); if(getState() != newValue) { try { waitComponentEnabled(); } catch(InterruptedException e) { throw(new JemmyException("Interrupted!", e)); } output.printLine("Change checkbox selection to " + (newValue ? "true" : "false") + "\n :" + toStringSource()); output.printGolden("Change checkbox selection to " + (newValue ? "true" : "false")); driver.push(this); if(getVerification()) { waitSelected(newValue); } } } /** * Runs changeSelection(boolean) method in a separate thread. * @param selected a button selection. */ public void changeSelectionNoBlock(boolean selected) { produceNoBlocking(new NoBlockingAction("Button selection changing") { public Object doAction(Object param) { changeSelection(((Boolean)param).booleanValue()); return(null); } }, selected ? Boolean.TRUE : Boolean.FALSE); } /** * Waits for button to be selected. * @param selected selection. */ public void waitSelected(final boolean selected) { getOutput().printLine("Wait button to be selected \n : "+ toStringSource()); getOutput().printGolden("Wait button to be selected"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(getState() == selected); } public String getDescription() { return("Items has been " + (selected ? "" : "un") + "selected"); } }); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); result.put(TEXT_DPROP, ((Checkbox)getSource()).getLabel()); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps Checkbox.addItemListener(ItemListener) through queue*/ public void addItemListener(final ItemListener itemListener) { runMapping(new MapVoidAction("addItemListener") { public void map() { ((Checkbox)getSource()).addItemListener(itemListener); }});} /**Maps Checkbox.getCheckboxGroup() through queue*/ public CheckboxGroup getCheckboxGroup() { return((CheckboxGroup)runMapping(new MapAction("getCheckboxGroup") { public Object map() { return(((Checkbox)getSource()).getCheckboxGroup()); }}));} /**Maps Checkbox.getLabel() through queue*/ public String getLabel() { return((String)runMapping(new MapAction("getLabel") { public Object map() { return(((Checkbox)getSource()).getLabel()); }}));} /**Maps Checkbox.getState() through queue*/ public boolean getState() { return(runMapping(new MapBooleanAction("getState") { public boolean map() { return(((Checkbox)getSource()).getState()); }}));} /**Maps Checkbox.removeItemListener(ItemListener) through queue*/ public void removeItemListener(final ItemListener itemListener) { runMapping(new MapVoidAction("removeItemListener") { public void map() { ((Checkbox)getSource()).removeItemListener(itemListener); }});} /**Maps Checkbox.setCheckboxGroup(CheckboxGroup) through queue*/ public void setCheckboxGroup(final CheckboxGroup grp) { runMapping(new MapVoidAction("setCheckboxGroup") { public void map() { ((Checkbox)getSource()).setCheckboxGroup(grp); }});} /**Maps Checkbox.setLabel(String) through queue*/ public void setLabel(final String string) { runMapping(new MapVoidAction("setLabel") { public void map() { ((Checkbox)getSource()).setLabel(string); }});} /**Maps Checkbox.setState(boolean) through queue*/ public void setState(final boolean state) { runMapping(new MapVoidAction("setState") { public void map() { ((Checkbox)getSource()).setState(state); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Allows to find component by label. */ public static class CheckboxByLabelFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs CheckboxByLabelFinder. * @param lb a label pattern * @param comparator specifies string comparision algorithm. */ public CheckboxByLabelFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs CheckboxByLabelFinder. * @param lb a label pattern */ public CheckboxByLabelFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof Checkbox) { if(((Checkbox)comp).getLabel() != null) { return(comparator.equals(((Checkbox)comp).getLabel(), label)); } } return(false); } public String getDescription() { return("Checkbox with label \"" + label + "\""); } } /** * Checks component type. */ public static class CheckboxFinder extends Finder { /** * Constructs CheckboxFinder. * @param sf other searching criteria. */ public CheckboxFinder(ComponentChooser sf) { super(Checkbox.class, sf); } /** * Constructs CheckboxFinder. */ public CheckboxFinder() { super(Checkbox.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JScrollBarOperator.java0000644000175000017500000006630111245712347023671 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.event.AdjustmentListener; import java.util.Hashtable; import javax.swing.BoundedRangeModel; import javax.swing.JButton; import javax.swing.JScrollBar; import javax.swing.plaf.ScrollBarUI; import org.netbeans.jemmy.Action; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.Waitable; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.ScrollDriver; import org.netbeans.jemmy.drivers.scrolling.ScrollAdjuster; import org.netbeans.jemmy.util.EmptyVisualizer; /** * * Operator is supposed to be used to operate with an instance of * javax.swing.JScrollBar class.

* * *

Timeouts used:
* JScrollBarOperator.OneScrollClickTimeout - time for one scroll click
* JScrollBarOperator.WholeScrollTimeout - time for the whole scrolling
* JScrollBarOperator.BeforeDropTimeout - to sleep before drop * JScrollBarOperator.DragAndDropScrollingDelta - to sleep before drag steps * ComponentOperator.WaitComponentTimeout - time to wait component displayed
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class JScrollBarOperator extends JComponentOperator implements Timeoutable, Outputable{ /** * Identifier for a "minimum" property. * @see #getDump */ public static final String MINIMUM_DPROP = "Minimum"; /** * Identifier for a "maximum" property. * @see #getDump */ public static final String MAXIMUM_DPROP = "Maximum"; /** * Identifier for a "value" property. * @see #getDump */ public static final String VALUE_DPROP = "Value"; /** * Identifier for a "orientation" property. * @see #getDump */ public static final String ORIENTATION_DPROP = "Orientation"; /** * Identifier for a "HORIZONTAL" value of "orientation" property. * @see #getDump */ public static final String HORIZONTAL_ORIENTATION_DPROP_VALUE = "HORIZONTAL"; /** * Identifier for a "VERTICAL" value of "orientation" property. * @see #getDump */ public static final String VERTICAL_ORIENTATION_DPROP_VALUE = "VERTICAL"; private final static long ONE_SCROLL_CLICK_TIMEOUT = 0; private final static long WHOLE_SCROLL_TIMEOUT = 60000; private final static long BEFORE_DROP_TIMEOUT = 0; private final static long DRAG_AND_DROP_SCROLLING_DELTA = 0; private Timeouts timeouts; private TestOut output; private JButtonOperator minButtOperator; private JButtonOperator maxButtOperator; private ScrollDriver driver; /** * Constructor. * @param b JScrollBar component. */ public JScrollBarOperator(JScrollBar b) { super(b); driver = DriverManager.getScrollDriver(getClass()); } /** * Constructs a JScrollBarOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JScrollBarOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JScrollBar)cont. waitSubComponent(new JScrollBarFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JScrollBarOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JScrollBarOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JScrollBarOperator(ContainerOperator cont, int index) { this((JScrollBar)waitComponent(cont, new JScrollBarFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @throws TimeoutExpiredException */ public JScrollBarOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JScrollBar in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JScrollBar instance or null if component was not found. */ public static JScrollBar findJScrollBar(Container cont, ComponentChooser chooser, int index) { return((JScrollBar)findComponent(cont, new JScrollBarFinder(chooser), index)); } /** * Searches 0'th JScrollBar in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JScrollBar instance or null if component was not found. */ public static JScrollBar findJScrollBar(Container cont, ComponentChooser chooser) { return(findJScrollBar(cont, chooser, 0)); } /** * Searches JScrollBar in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JScrollBar instance or null if component was not found. */ public static JScrollBar findJScrollBar(Container cont, int index) { return(findJScrollBar(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JScrollBar instance"), index)); } /** * Searches 0'th JScrollBar in container. * @param cont Container to search component in. * @return JScrollBar instance or null if component was not found. */ public static JScrollBar findJScrollBar(Container cont) { return(findJScrollBar(cont, 0)); } /** * Waits JScrollBar in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JScrollBar instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JScrollBar waitJScrollBar(Container cont, ComponentChooser chooser, int index) { return((JScrollBar)waitComponent(cont, new JScrollBarFinder(chooser), index)); } /** * Waits 0'th JScrollBar in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JScrollBar instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JScrollBar waitJScrollBar(Container cont, ComponentChooser chooser) { return(waitJScrollBar(cont, chooser, 0)); } /** * Waits JScrollBar in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JScrollBar instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JScrollBar waitJScrollBar(Container cont, int index) { return(waitJScrollBar(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JScrollBar instance"), index)); } /** * Waits 0'th JScrollBar in container. * @param cont Container to search component in. * @return JScrollBar instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JScrollBar waitJScrollBar(Container cont) { return(waitJScrollBar(cont, 0)); } static { Timeouts.initDefault("JScrollBarOperator.OneScrollClickTimeout", ONE_SCROLL_CLICK_TIMEOUT); Timeouts.initDefault("JScrollBarOperator.WholeScrollTimeout", WHOLE_SCROLL_TIMEOUT); Timeouts.initDefault("JScrollBarOperator.BeforeDropTimeout", BEFORE_DROP_TIMEOUT); Timeouts.initDefault("JScrollBarOperator.DragAndDropScrollingDelta", DRAG_AND_DROP_SCROLLING_DELTA); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; super.setTimeouts(timeouts); } public Timeouts getTimeouts() { return(timeouts); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (ScrollDriver)DriverManager. getDriver(DriverManager.SCROLL_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Does simple scroll click. * @param increase a scrolling direction. * @throws TimeoutExpiredException * @deprecated All scrolling is done through a ScrollDriver registered to this operator type. */ public void scroll(boolean increase) { scrollToValue(getValue() + (increase ? 1 : -1)); } /** * Scrolls scrollbar to the position defined by w parameter. * Uses ScrollDriver registered to this operator type. * @param w Scrolling is stopped when w.actionProduced(waiterParam) != null * @param waiterParam a waiting parameter. * @param increase a scrolling direction. * @see #scrollTo(JScrollBarOperator.ScrollChecker) * @throws TimeoutExpiredException */ public void scrollTo(Waitable w, Object waiterParam, boolean increase) { scrollTo(new WaitableChecker(w, waiterParam, increase, this)); } /** * Scrolls scrollbar to the position defined by a ScrollChecker implementation. * @param checker ScrollChecker implementation defining scrolling direction, and so on. * @see ScrollChecker * @throws TimeoutExpiredException */ public void scrollTo(ScrollChecker checker) { scrollTo(new CheckerAdjustable(checker, this)); } /** * Scrolls scrollbar to the position defined by a ScrollAdjuster implementation. * @param adj defines scrolling direction, and so on. * @throws TimeoutExpiredException */ public void scrollTo(final ScrollAdjuster adj) { initOperators(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scroll(JScrollBarOperator.this, adj); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("JScrollBarOperator.WholeScrollTimeout")); } /** * Scrolls scroll bar to necessary value. * @param value Scroll bar value to scroll to. * @throws TimeoutExpiredException */ public void scrollToValue(int value) { output.printTrace("Scroll JScrollBar to " + Integer.toString(value) + " value\n" + toStringSource()); output.printGolden("Scroll JScrollBar to " + Integer.toString(value) + " value"); scrollTo(new ValueScrollAdjuster(value)); } /** * Scrolls scroll bar to necessary proportional value. * @param proportionalValue Proportional scroll to. Must be >= 0 and <= 1. * @throws TimeoutExpiredException */ public void scrollToValue(double proportionalValue) { output.printTrace("Scroll JScrollBar to " + Double.toString(proportionalValue) + " proportional value\n" + toStringSource()); output.printGolden("Scroll JScrollBar to " + Double.toString(proportionalValue) + " proportional value"); scrollTo(new ValueScrollAdjuster((int)(getMinimum() + (getMaximum() - getVisibleAmount() - getMinimum()) * proportionalValue))); } /** * Scrolls to minimum value. * @throws TimeoutExpiredException */ public void scrollToMinimum() { output.printTrace("Scroll JScrollBar to minimum value\n" + toStringSource()); output.printGolden("Scroll JScrollBar to minimum value"); initOperators(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scrollToMinimum(JScrollBarOperator.this, getOrientation()); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("JScrollBarOperator.WholeScrollTimeout")); } /** * Scrolls to maximum value. * @throws TimeoutExpiredException */ public void scrollToMaximum() { output.printTrace("Scroll JScrollBar to maximum value\n" + toStringSource()); output.printGolden("Scroll JScrollBar to maximum value"); initOperators(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scrollToMaximum(JScrollBarOperator.this, getOrientation()); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("JScrollBarOperator.WholeScrollTimeout")); } /** * Returns a button responsible for value decreasing. * @return an operator for the decrease button. */ public JButtonOperator getDecreaseButton() { initOperators(); return(minButtOperator); } /** * Returns a button responsible for value increasing. * @return an operator for the increase button. */ public JButtonOperator getIncreaseButton() { initOperators(); return(maxButtOperator); } public Hashtable getDump() { Hashtable result = super.getDump(); result.put(MINIMUM_DPROP, Integer.toString(((JScrollBar)getSource()).getMinimum())); result.put(MAXIMUM_DPROP, Integer.toString(((JScrollBar)getSource()).getMaximum())); result.put(ORIENTATION_DPROP, (((JScrollBar)getSource()).getOrientation() == JScrollBar.HORIZONTAL) ? HORIZONTAL_ORIENTATION_DPROP_VALUE : VERTICAL_ORIENTATION_DPROP_VALUE); result.put(VALUE_DPROP, Integer.toString(((JScrollBar)getSource()).getValue())); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JScrollBar.addAdjustmentListener(AdjustmentListener) through queue*/ public void addAdjustmentListener(final AdjustmentListener adjustmentListener) { runMapping(new MapVoidAction("addAdjustmentListener") { public void map() { ((JScrollBar)getSource()).addAdjustmentListener(adjustmentListener); }});} /**Maps JScrollBar.getBlockIncrement() through queue*/ public int getBlockIncrement() { return(runMapping(new MapIntegerAction("getBlockIncrement") { public int map() { return(((JScrollBar)getSource()).getBlockIncrement()); }}));} /**Maps JScrollBar.getBlockIncrement(int) through queue*/ public int getBlockIncrement(final int i) { return(runMapping(new MapIntegerAction("getBlockIncrement") { public int map() { return(((JScrollBar)getSource()).getBlockIncrement(i)); }}));} /**Maps JScrollBar.getMaximum() through queue*/ public int getMaximum() { return(runMapping(new MapIntegerAction("getMaximum") { public int map() { return(((JScrollBar)getSource()).getMaximum()); }}));} /**Maps JScrollBar.getMinimum() through queue*/ public int getMinimum() { return(runMapping(new MapIntegerAction("getMinimum") { public int map() { return(((JScrollBar)getSource()).getMinimum()); }}));} /**Maps JScrollBar.getModel() through queue*/ public BoundedRangeModel getModel() { return((BoundedRangeModel)runMapping(new MapAction("getModel") { public Object map() { return(((JScrollBar)getSource()).getModel()); }}));} /**Maps JScrollBar.getOrientation() through queue*/ public int getOrientation() { return(runMapping(new MapIntegerAction("getOrientation") { public int map() { return(((JScrollBar)getSource()).getOrientation()); }}));} /**Maps JScrollBar.getUI() through queue*/ public ScrollBarUI getUI() { return((ScrollBarUI)runMapping(new MapAction("getUI") { public Object map() { return(((JScrollBar)getSource()).getUI()); }}));} /**Maps JScrollBar.getUnitIncrement() through queue*/ public int getUnitIncrement() { return(runMapping(new MapIntegerAction("getUnitIncrement") { public int map() { return(((JScrollBar)getSource()).getUnitIncrement()); }}));} /**Maps JScrollBar.getUnitIncrement(int) through queue*/ public int getUnitIncrement(final int i) { return(runMapping(new MapIntegerAction("getUnitIncrement") { public int map() { return(((JScrollBar)getSource()).getUnitIncrement(i)); }}));} /**Maps JScrollBar.getValue() through queue*/ public int getValue() { return(runMapping(new MapIntegerAction("getValue") { public int map() { return(((JScrollBar)getSource()).getValue()); }}));} /**Maps JScrollBar.getValueIsAdjusting() through queue*/ public boolean getValueIsAdjusting() { return(runMapping(new MapBooleanAction("getValueIsAdjusting") { public boolean map() { return(((JScrollBar)getSource()).getValueIsAdjusting()); }}));} /**Maps JScrollBar.getVisibleAmount() through queue*/ public int getVisibleAmount() { return(runMapping(new MapIntegerAction("getVisibleAmount") { public int map() { return(((JScrollBar)getSource()).getVisibleAmount()); }}));} /**Maps JScrollBar.removeAdjustmentListener(AdjustmentListener) through queue*/ public void removeAdjustmentListener(final AdjustmentListener adjustmentListener) { runMapping(new MapVoidAction("removeAdjustmentListener") { public void map() { ((JScrollBar)getSource()).removeAdjustmentListener(adjustmentListener); }});} /**Maps JScrollBar.setBlockIncrement(int) through queue*/ public void setBlockIncrement(final int i) { runMapping(new MapVoidAction("setBlockIncrement") { public void map() { ((JScrollBar)getSource()).setBlockIncrement(i); }});} /**Maps JScrollBar.setMaximum(int) through queue*/ public void setMaximum(final int i) { runMapping(new MapVoidAction("setMaximum") { public void map() { ((JScrollBar)getSource()).setMaximum(i); }});} /**Maps JScrollBar.setMinimum(int) through queue*/ public void setMinimum(final int i) { runMapping(new MapVoidAction("setMinimum") { public void map() { ((JScrollBar)getSource()).setMinimum(i); }});} /**Maps JScrollBar.setModel(BoundedRangeModel) through queue*/ public void setModel(final BoundedRangeModel boundedRangeModel) { runMapping(new MapVoidAction("setModel") { public void map() { ((JScrollBar)getSource()).setModel(boundedRangeModel); }});} /**Maps JScrollBar.setOrientation(int) through queue*/ public void setOrientation(final int i) { runMapping(new MapVoidAction("setOrientation") { public void map() { ((JScrollBar)getSource()).setOrientation(i); }});} /**Maps JScrollBar.setUnitIncrement(int) through queue*/ public void setUnitIncrement(final int i) { runMapping(new MapVoidAction("setUnitIncrement") { public void map() { ((JScrollBar)getSource()).setUnitIncrement(i); }});} /**Maps JScrollBar.setValue(int) through queue*/ public void setValue(final int i) { runMapping(new MapVoidAction("setValue") { public void map() { ((JScrollBar)getSource()).setValue(i); }});} /**Maps JScrollBar.setValueIsAdjusting(boolean) through queue*/ public void setValueIsAdjusting(final boolean b) { runMapping(new MapVoidAction("setValueIsAdjusting") { public void map() { ((JScrollBar)getSource()).setValueIsAdjusting(b); }});} /**Maps JScrollBar.setValues(int, int, int, int) through queue*/ public void setValues(final int i, final int i1, final int i2, final int i3) { runMapping(new MapVoidAction("setValues") { public void map() { ((JScrollBar)getSource()).setValues(i, i1, i2, i3); }});} /**Maps JScrollBar.setVisibleAmount(int) through queue*/ public void setVisibleAmount(final int i) { runMapping(new MapVoidAction("setVisibleAmount") { public void map() { ((JScrollBar)getSource()).setVisibleAmount(i); }});} //End of mapping // //////////////////////////////////////////////////////// private void initOperators() { if(minButtOperator != null && maxButtOperator != null) { return; } ComponentChooser chooser = new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp instanceof JButton); } public String getDescription() { return(""); } }; ComponentSearcher searcher = new ComponentSearcher((Container)getSource()); searcher.setOutput(output.createErrorOutput()); JButton butt0 = (JButton)searcher.findComponent(chooser, 0); JButton butt1 = (JButton)searcher.findComponent(chooser, 1); if(butt0 == null || butt1 == null) { minButtOperator = null; maxButtOperator = null; return; } JButton minButt, maxButt; if(((JScrollBar)getSource()).getOrientation() == JScrollBar.HORIZONTAL) { if(butt0.getX() < butt1.getX()) { minButt = butt0; maxButt = butt1; } else { minButt = butt1; maxButt = butt0; } } else { if(butt0.getY() < butt1.getY()) { minButt = butt0; maxButt = butt1; } else { minButt = butt1; maxButt = butt0; } } minButtOperator = new JButtonOperator(minButt); maxButtOperator = new JButtonOperator(maxButt); minButtOperator.copyEnvironment(this); maxButtOperator.copyEnvironment(this); minButtOperator.setOutput(output.createErrorOutput()); maxButtOperator.setOutput(output.createErrorOutput()); Timeouts times = timeouts.cloneThis(); times.setTimeout("AbstractButtonOperator.PushButtonTimeout", times.getTimeout("JScrollBarOperator.OneScrollClickTimeout")); minButtOperator.setTimeouts(times); maxButtOperator.setTimeouts(times); minButtOperator.setVisualizer(new EmptyVisualizer()); maxButtOperator.setVisualizer(new EmptyVisualizer()); } /** * Interface can be used to define some kind of complicated * scrolling rules. */ public interface ScrollChecker { /** * Defines a scrolling direction. * @param oper an operator * @see org.netbeans.jemmy.drivers.scrolling.ScrollAdjuster#INCREASE_SCROLL_DIRECTION * @see org.netbeans.jemmy.drivers.scrolling.ScrollAdjuster#DECREASE_SCROLL_DIRECTION * @see org.netbeans.jemmy.drivers.scrolling.ScrollAdjuster#DO_NOT_TOUCH_SCROLL_DIRECTION * @return one of the following values:
* ScrollAdjuster.INCREASE_SCROLL_DIRECTION
* ScrollAdjuster.DECREASE_SCROLL_DIRECTION
* ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION
*/ public int getScrollDirection(JScrollBarOperator oper); /** * Scrolling rules decription. * @return a description */ public String getDescription(); } private class ValueScrollAdjuster implements ScrollAdjuster { int value; public ValueScrollAdjuster(int value) { this.value = value; } public int getScrollDirection() { if(getValue() == value) { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } else { return((getValue() < value) ? ScrollAdjuster.INCREASE_SCROLL_DIRECTION : ScrollAdjuster.DECREASE_SCROLL_DIRECTION); } } public int getScrollOrientation() { return(getOrientation()); } public String getDescription() { return("Scroll to " + Integer.toString(value) + " value"); } } private class WaitableChecker implements ScrollAdjuster { Waitable w; Object waitParam; boolean increase; boolean reached = false; public WaitableChecker(Waitable w, Object waitParam, boolean increase, JScrollBarOperator oper) { this.w = w; this.waitParam = waitParam; this.increase = increase; } public int getScrollDirection() { if(!reached && w.actionProduced(waitParam) != null) { reached = true; } if(reached) { return(this.DO_NOT_TOUCH_SCROLL_DIRECTION); } else { return(increase ? this.INCREASE_SCROLL_DIRECTION : this.DECREASE_SCROLL_DIRECTION); } } public int getScrollOrientation() { return(getOrientation()); } public String getDescription() { return(w.getDescription()); } } private class CheckerAdjustable implements ScrollAdjuster { ScrollChecker checker; JScrollBarOperator oper; public CheckerAdjustable(ScrollChecker checker, JScrollBarOperator oper) { this.checker = checker; this.oper = oper; } public int getScrollDirection() { return(checker.getScrollDirection(oper)); } public int getScrollOrientation() { return(getOrientation()); } public String getDescription() { return(checker.getDescription()); } } /** * Checks component type. */ public static class JScrollBarFinder extends Finder { /** * Constructs JScrollBarFinder. * @param sf other searching criteria. */ public JScrollBarFinder(ComponentChooser sf) { super(JScrollBar.class, sf); } /** * Constructs JScrollBarFinder. */ public JScrollBarFinder() { super(JScrollBar.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JTextComponentOperator.java0000644000175000017500000012537411245712237024621 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.Hashtable; import javax.swing.JScrollPane; import javax.swing.event.CaretListener; import javax.swing.plaf.TextUI; import javax.swing.text.BadLocationException; import javax.swing.text.Caret; import javax.swing.text.Document; import javax.swing.text.Highlighter; import javax.swing.text.JTextComponent; import javax.swing.text.Keymap; import org.netbeans.jemmy.Action; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyInputException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.TextDriver; import org.netbeans.jemmy.util.EmptyVisualizer; /** * * Class provides basic functions to operate with JTextComponent * (selection, typing, deleting) * *

Timeouts used:
* JTextComponentOperator.PushKeyTimeout - time between key pressing and releasing during text typing
* JTextComponentOperator.BetweenKeysTimeout - time to sleep between two chars typing
* JTextComponentOperator.ChangeCaretPositionTimeout - maximum time to chenge caret position
* JTextComponentOperator.TypeTextTimeout - maximum time to type text
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.WaitFocusTimeout - time to wait component focus
* ComponentOperator.WaitStateTimeout - time to wait for text
* JScrollBarOperator.OneScrollClickTimeout - time for one scroll click
* JScrollBarOperator.WholeScrollTimeout - time for the whole scrolling
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class JTextComponentOperator extends JComponentOperator implements Timeoutable, Outputable{ /** * Identifier for a "text" property. * @see #getDump */ public static final String TEXT_DPROP = "Text"; /** * Identifier for a "selected text" property. * @see #getDump */ public static final String SELECTED_TEXT_DPROP = "Selected text"; /** * Identifier for a "editable" property. * @see #getDump */ public static final String IS_EDITABLE_DPROP = "Editable"; private final static long PUSH_KEY_TIMEOUT = 0; private final static long BETWEEN_KEYS_TIMEOUT = 0; private final static long CHANGE_CARET_POSITION_TIMEOUT = 60000; private final static long TYPE_TEXT_TIMEOUT = 60000; private Timeouts timeouts; private TestOut output; /** * Notifies what modifiers are pressed. * @deprecated All text operations are performed by TextDriver regitered for this operator type. */ protected int modifiersPressed = 0; private TextDriver driver; /** * Constructor. * @param b Component to operate with. */ public JTextComponentOperator(JTextComponent b) { super(b); driver = DriverManager.getTextDriver(getClass()); } /** * Constructs a JTextComponentOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JTextComponentOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JTextComponent)cont. waitSubComponent(new JTextComponentFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JTextComponentOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JTextComponentOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTextComponentOperator(ContainerOperator cont, String text, int index) { this((JTextComponent)waitComponent(cont, new JTextComponentByTextFinder(text, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTextComponentOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JTextComponentOperator(ContainerOperator cont, int index) { this((JTextComponent) waitComponent(cont, new JTextComponentFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JTextComponentOperator(ContainerOperator cont) { this(cont, 0); } static { Timeouts.initDefault("JTextComponentOperator.PushKeyTimeout", PUSH_KEY_TIMEOUT); Timeouts.initDefault("JTextComponentOperator.BetweenKeysTimeout", BETWEEN_KEYS_TIMEOUT); Timeouts.initDefault("JTextComponentOperator.ChangeCaretPositionTimeout", CHANGE_CARET_POSITION_TIMEOUT); Timeouts.initDefault("JTextComponentOperator.TypeTextTimeout", TYPE_TEXT_TIMEOUT); } /** * Searches JTextComponent in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JTextComponent instance or null if component was not found. */ public static JTextComponent findJTextComponent(Container cont, ComponentChooser chooser, int index) { return((JTextComponent)findComponent(cont, new JTextComponentFinder(chooser), index)); } /** * Searches JTextComponent in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JTextComponent instance or null if component was not found. */ public static JTextComponent findJTextComponent(Container cont, ComponentChooser chooser) { return(findJTextComponent(cont, chooser, 0)); } /** * Searches JTextComponent by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JTextComponent instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTextComponent findJTextComponent(Container cont, String text, boolean ce, boolean ccs, int index) { return(findJTextComponent(cont, new JTextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches JTextComponent by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JTextComponent instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTextComponent findJTextComponent(Container cont, String text, boolean ce, boolean ccs) { return(findJTextComponent(cont, text, ce, ccs, 0)); } /** * Waits JTextComponent in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JTextComponent instance. * @throws TimeoutExpiredException */ public static JTextComponent waitJTextComponent(final Container cont, final ComponentChooser chooser, final int index) { return((JTextComponent)waitComponent(cont, new JTextComponentFinder(chooser), index)); } /** * Waits JTextComponent in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JTextComponent instance. * @throws TimeoutExpiredException */ public static JTextComponent waitJTextComponent(Container cont, ComponentChooser chooser) { return(waitJTextComponent(cont, chooser, 0)); } /** * Waits JTextComponent by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JTextComponent instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JTextComponent waitJTextComponent(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitJTextComponent(cont, new JTextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits JTextComponent by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JTextComponent instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JTextComponent waitJTextComponent(Container cont, String text, boolean ce, boolean ccs) { return(waitJTextComponent(cont, text, ce, ccs, 0)); } public void setTimeouts(Timeouts times) { timeouts = times; timeouts.setTimeout("ComponentOperator.PushKeyTimeout", timeouts.getTimeout("JTextComponentOperator.PushKeyTimeout")); super.setTimeouts(timeouts); } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (TextDriver)DriverManager. getDriver(DriverManager.TEXT_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Finds start text position. * @param text Text to be searched. * @param tChooser Additional search criteria. * @param index Index of text instance (first instance has index 0) * @return Caret position correspondent to text start. * @see JTextComponentOperator.TextChooser */ public int getPositionByText(String text, TextChooser tChooser, int index) { output.printLine("Find " + tChooser.getDescription() + "\"" + text + "\" text in text component\n : " + toStringSource()); output.printGolden("Find " + tChooser.getDescription() + "\"" + text + "\" text in text component"); String allText = getDisplayedText(); Document doc = getDocument(); int position = 0; int ind = 0; while((position = allText.indexOf(text, position)) >= 0) { if(tChooser.checkPosition(doc, position)) { if(ind == index) { return(position); } else { ind++; } } position = position + text.length(); } return(-1); } /** * Finds start text position. * @param text Text to be searched. * @param tChooser Additional search criteria. * @return Caret position correspondent to text start. */ public int getPositionByText(String text, TextChooser tChooser) { return(getPositionByText(text, tChooser, 0)); } /** * Finds start text position. * @param text Text to be searched. * @param index Index of text instance (first instance has index 0) * @return Caret position correspondent to text start. */ public int getPositionByText(String text, int index) { return(getPositionByText(text, new TextChooser() { public boolean checkPosition(Document doc, int offset) { return(true); } public String getDescription() { return("any"); } }, index)); } /** * Finds start text position. * @param text Text to be searched. * @return Caret position correspondent to text start. */ public int getPositionByText(String text) { return(getPositionByText(text, 0)); } /** * Requests a focus, clears text, types new one and pushes Enter. * @param text New text value. Shouln't include final '\n'. * @throws TimeoutExpiredException */ public void enterText(final String text) { makeComponentVisible(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.enterText(JTextComponentOperator.this, text); return(null); } public String getDescription() { return("Text entering"); } }, getTimeouts().getTimeout("JTextComponentOperator.TypeTextTimeout")); } /** * Changes caret position. * @param position Position to move caret to. * @see #changeCaretPosition(String, int, boolean) * @throws TimeoutExpiredException */ public void changeCaretPosition(final int position) { output.printLine("Change caret position to " + Integer.toString(position)); makeComponentVisible(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.changeCaretPosition(JTextComponentOperator.this, position); return(null); } public String getDescription() { return("Caret moving"); } }, getTimeouts().getTimeout("JTextComponentOperator.ChangeCaretPositionTimeout")); if(getVerification()) { waitCaretPosition(position); } } /** * Puts caret before or after text. * @param text Text to be searched. * @param index Index of text instance (first instance has index 0) * @param before If true put caret before text, otherwise after. * @see #changeCaretPosition(int) * @see #getPositionByText(String, int) * @throws TimeoutExpiredException * @throws NoSuchTextException */ public void changeCaretPosition(String text, int index, boolean before) { output.printLine("Put caret " + (before ? "before" : "after") + " " + Integer.toString(index) + "'th instance of \"" + text + "\" text"); makeComponentVisible(); int offset = getPositionByText(text, index); if(offset == -1) { throw(new NoSuchTextException(text)); } offset = before ? offset : offset + text.length(); changeCaretPosition(offset); } /** * Puts caret before or after text. * @param text Text to be searched. * @param before If true put caret before text, otherwise after. * @see #changeCaretPosition(int) * @see #getPositionByText(String, int) * @throws TimeoutExpiredException * @throws NoSuchTextException */ public void changeCaretPosition(String text, boolean before) { changeCaretPosition(text, 0, before); } /** * Types text starting from known position. * If verification mode is on, checks that right text has been typed * and caret has been moved to right position. * @param text Text to be typed. * @param caretPosition Position to start type text * @see #typeText(String) * @throws TimeoutExpiredException * @throws NoSuchTextException */ public void typeText(final String text, final int caretPosition) { output.printLine("Typing text \"" + text + "\" from " + Integer.toString(caretPosition) + " position " + "in text component\n : " + toStringSource()); output.printGolden("Typing text \"" + text + "\" in text component"); makeComponentVisible(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.typeText(JTextComponentOperator.this, text, caretPosition); return(null); } public String getDescription() { return("Text typing"); } }, getTimeouts().getTimeout("JTextComponentOperator.TypeTextTimeout")); if(getVerification()) { waitText(text, -1); } } /** * Types text starting from the current position. * @param text Text to be typed. * @see #typeText(String, int) * @throws TimeoutExpiredException */ public void typeText(String text) { typeText(text, getCaretPosition()); } /** * Selects a part of text. * @param startPosition Start caret position * @param finalPosition Final caret position * @see #selectText(String, int) * @see #selectText(String) * @throws TimeoutExpiredException */ public void selectText(final int startPosition, final int finalPosition) { output.printLine("Select text from " + Integer.toString(startPosition) + " to " + Integer.toString(finalPosition) + " in text component\n : " + toStringSource()); makeComponentVisible(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.selectText(JTextComponentOperator.this, startPosition, finalPosition); return(null); } public String getDescription() { return("Text selecting"); } }, getTimeouts().getTimeout("JTextComponentOperator.TypeTextTimeout")); } /** * Selects a part of text. * @param text Text to be selected * @param index Index of text instance (first instance has index 0) * @see #selectText(int, int) * @see #selectText(String) * @see #getPositionByText(String, int) * @throws TimeoutExpiredException * @throws NoSuchTextException */ public void selectText(String text, int index) { output.printLine("Select " + Integer.toString(index) + "'th instance of \"" + text + "\" text in component\n : " + toStringSource()); makeComponentVisible(); int start = getPositionByText(text, index); if(start == -1) { throw(new NoSuchTextException(text)); } selectText(start, start + text.length()); } /** * Selects a part of text. * @param text Text to be selected * @see #selectText(String, int) * @see #selectText(int, int) * @throws TimeoutExpiredException * @throws NoSuchTextException */ public void selectText(String text) { selectText(text, 0); } /** * Clears text. * @throws TimeoutExpiredException */ public void clearText() { output.printLine("Clearing text in text component\n : " + toStringSource()); output.printGolden("Clearing text in text component"); makeComponentVisible(); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.clearText(JTextComponentOperator.this); return(null); } public String getDescription() { return("Text clearing"); } }, getTimeouts().getTimeout("JTextComponentOperator.TypeTextTimeout")); } /** * Scrolls to a text poistion. * @param position a position to scroll. * @throws TimeoutExpiredException */ public void scrollToPosition(int position) { output.printTrace("Scroll JTextComponent to " + Integer.toString(position) + " position\n : " + toStringSource()); output.printGolden("Scroll JTextComponent to " + Integer.toString(position) + " position"); makeComponentVisible(); //try to find JScrollPane under. JScrollPane scroll = (JScrollPane)getContainer(new JScrollPaneOperator. JScrollPaneFinder(ComponentSearcher. getTrueChooser("JScrollPane"))); if(scroll == null) { return; } JScrollPaneOperator scroller = new JScrollPaneOperator(scroll); scroller.copyEnvironment(this); scroller.setVisualizer(new EmptyVisualizer()); Rectangle rect = modelToView(position); scroller.scrollToComponentRectangle(getSource(), (int)rect.getX(), (int)rect.getY(), (int)rect.getWidth(), (int)rect.getHeight()); } /** * Returns text which is really displayed. * Results returned by getText() and getDisplayedText() * are different if text component is used to display javax.swing.text.StyledDocument * @return the text which is displayed. */ public String getDisplayedText() { try { Document doc = getDocument(); return(doc.getText(0, doc.getLength())); } catch(BadLocationException e) { throw(new JemmyException("Exception during text operation with\n : " + toStringSource(), e)); } } /** * Wait for text to be displayed starting from certain position. * @param text text to wait. * @param position starting text position. */ public void waitText(final String text, final int position) { getOutput().printLine("Wait \"" + text + "\" text starting from " + Integer.toString(position) + " position in component \n : "+ toStringSource()); getOutput().printGolden("Wait \"" + text + "\" text starting from " + Integer.toString(position) + " position"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { String alltext = getDisplayedText(); if(position >= 0) { if(position + text.length() <= alltext.length()) { return(alltext.substring(position, position + text.length()). equals(text)); } else { return(false); } } else { return(alltext.indexOf(text) >= 0); } } public String getDescription() { return("Has \"" + text + "\" text starting from " + Integer.toString(position) + " position"); } }); } /** * Waits for certain text. * @param text Text to be compared by getComparator() comparator. */ public void waitText(String text) { getOutput().printLine("Wait \"" + text + "\" text in component \n : "+ toStringSource()); getOutput().printGolden("Wait \"" + text + "\" text"); waitState(new JTextComponentByTextFinder(text, getComparator())); } /** * Wait for caret to be moved to certain position. * @param position a position which caret supposed to be moved to. */ public void waitCaretPosition(final int position) { getOutput().printLine("Wait caret to be at \"" + Integer.toString(position) + " position in component \n : "+ toStringSource()); getOutput().printGolden("Wait caret to be at \"" + Integer.toString(position) + " position"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(getCaretPosition() == position); } public String getDescription() { return("Has caret at " + Integer.toString(position) + " position"); } }); } public Hashtable getDump() { Hashtable result = super.getDump(); result.put(TEXT_DPROP, ((JTextComponent)getSource()).getText()); if(((JTextComponent)getSource()).getSelectedText() != null && !((JTextComponent)getSource()).getSelectedText().equals("")) { result.put(SELECTED_TEXT_DPROP, ((JTextComponent)getSource()).getSelectedText()); } result.put(IS_EDITABLE_DPROP, ((JTextComponent)getSource()).isEditable() ? "true" : "false"); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JTextComponent.addCaretListener(CaretListener) through queue*/ public void addCaretListener(final CaretListener caretListener) { runMapping(new MapVoidAction("addCaretListener") { public void map() { ((JTextComponent)getSource()).addCaretListener(caretListener); }});} /**Maps JTextComponent.copy() through queue*/ public void copy() { runMapping(new MapVoidAction("copy") { public void map() { ((JTextComponent)getSource()).copy(); }});} /**Maps JTextComponent.cut() through queue*/ public void cut() { runMapping(new MapVoidAction("cut") { public void map() { ((JTextComponent)getSource()).cut(); }});} /**Maps JTextComponent.getActions() through queue*/ public javax.swing.Action[] getActions() { return((javax.swing.Action[])runMapping(new MapAction("getActions") { public Object map() { return(((JTextComponent)getSource()).getActions()); }}));} /**Maps JTextComponent.getCaret() through queue*/ public Caret getCaret() { return((Caret)runMapping(new MapAction("getCaret") { public Object map() { return(((JTextComponent)getSource()).getCaret()); }}));} /**Maps JTextComponent.getCaretColor() through queue*/ public Color getCaretColor() { return((Color)runMapping(new MapAction("getCaretColor") { public Object map() { return(((JTextComponent)getSource()).getCaretColor()); }}));} /**Maps JTextComponent.getCaretPosition() through queue*/ public int getCaretPosition() { return(runMapping(new MapIntegerAction("getCaretPosition") { public int map() { return(((JTextComponent)getSource()).getCaretPosition()); }}));} /**Maps JTextComponent.getDisabledTextColor() through queue*/ public Color getDisabledTextColor() { return((Color)runMapping(new MapAction("getDisabledTextColor") { public Object map() { return(((JTextComponent)getSource()).getDisabledTextColor()); }}));} /**Maps JTextComponent.getDocument() through queue*/ public Document getDocument() { return((Document)runMapping(new MapAction("getDocument") { public Object map() { return(((JTextComponent)getSource()).getDocument()); }}));} /**Maps JTextComponent.getFocusAccelerator() through queue*/ public char getFocusAccelerator() { return(runMapping(new MapCharacterAction("getFocusAccelerator") { public char map() { return(((JTextComponent)getSource()).getFocusAccelerator()); }}));} /**Maps JTextComponent.getHighlighter() through queue*/ public Highlighter getHighlighter() { return((Highlighter)runMapping(new MapAction("getHighlighter") { public Object map() { return(((JTextComponent)getSource()).getHighlighter()); }}));} /**Maps JTextComponent.getKeymap() through queue*/ public Keymap getKeymap() { return((Keymap)runMapping(new MapAction("getKeymap") { public Object map() { return(((JTextComponent)getSource()).getKeymap()); }}));} /**Maps JTextComponent.getMargin() through queue*/ public Insets getMargin() { return((Insets)runMapping(new MapAction("getMargin") { public Object map() { return(((JTextComponent)getSource()).getMargin()); }}));} /**Maps JTextComponent.getPreferredScrollableViewportSize() through queue*/ public Dimension getPreferredScrollableViewportSize() { return((Dimension)runMapping(new MapAction("getPreferredScrollableViewportSize") { public Object map() { return(((JTextComponent)getSource()).getPreferredScrollableViewportSize()); }}));} /**Maps JTextComponent.getScrollableBlockIncrement(Rectangle, int, int) through queue*/ public int getScrollableBlockIncrement(final Rectangle rectangle, final int i, final int i1) { return(runMapping(new MapIntegerAction("getScrollableBlockIncrement") { public int map() { return(((JTextComponent)getSource()).getScrollableBlockIncrement(rectangle, i, i1)); }}));} /**Maps JTextComponent.getScrollableTracksViewportHeight() through queue*/ public boolean getScrollableTracksViewportHeight() { return(runMapping(new MapBooleanAction("getScrollableTracksViewportHeight") { public boolean map() { return(((JTextComponent)getSource()).getScrollableTracksViewportHeight()); }}));} /**Maps JTextComponent.getScrollableTracksViewportWidth() through queue*/ public boolean getScrollableTracksViewportWidth() { return(runMapping(new MapBooleanAction("getScrollableTracksViewportWidth") { public boolean map() { return(((JTextComponent)getSource()).getScrollableTracksViewportWidth()); }}));} /**Maps JTextComponent.getScrollableUnitIncrement(Rectangle, int, int) through queue*/ public int getScrollableUnitIncrement(final Rectangle rectangle, final int i, final int i1) { return(runMapping(new MapIntegerAction("getScrollableUnitIncrement") { public int map() { return(((JTextComponent)getSource()).getScrollableUnitIncrement(rectangle, i, i1)); }}));} /**Maps JTextComponent.getSelectedText() through queue*/ public String getSelectedText() { return((String)runMapping(new MapAction("getSelectedText") { public Object map() { return(((JTextComponent)getSource()).getSelectedText()); }}));} /**Maps JTextComponent.getSelectedTextColor() through queue*/ public Color getSelectedTextColor() { return((Color)runMapping(new MapAction("getSelectedTextColor") { public Object map() { return(((JTextComponent)getSource()).getSelectedTextColor()); }}));} /**Maps JTextComponent.getSelectionColor() through queue*/ public Color getSelectionColor() { return((Color)runMapping(new MapAction("getSelectionColor") { public Object map() { return(((JTextComponent)getSource()).getSelectionColor()); }}));} /**Maps JTextComponent.getSelectionEnd() through queue*/ public int getSelectionEnd() { return(runMapping(new MapIntegerAction("getSelectionEnd") { public int map() { return(((JTextComponent)getSource()).getSelectionEnd()); }}));} /**Maps JTextComponent.getSelectionStart() through queue*/ public int getSelectionStart() { return(runMapping(new MapIntegerAction("getSelectionStart") { public int map() { return(((JTextComponent)getSource()).getSelectionStart()); }}));} /**Maps JTextComponent.getText() through queue*/ public String getText() { return((String)runMapping(new MapAction("getText") { public Object map() { return(((JTextComponent)getSource()).getText()); }}));} /**Maps JTextComponent.getText(int, int) through queue*/ public String getText(final int i, final int i1) { return((String)runMapping(new MapAction("getText") { public Object map() throws BadLocationException { return(((JTextComponent)getSource()).getText(i, i1)); }}));} /**Maps JTextComponent.getUI() through queue*/ public TextUI getUI() { return((TextUI)runMapping(new MapAction("getUI") { public Object map() { return(((JTextComponent)getSource()).getUI()); }}));} /**Maps JTextComponent.isEditable() through queue*/ public boolean isEditable() { return(runMapping(new MapBooleanAction("isEditable") { public boolean map() { return(((JTextComponent)getSource()).isEditable()); }}));} /**Maps JTextComponent.modelToView(int) through queue*/ public Rectangle modelToView(final int i) { return((Rectangle)runMapping(new MapAction("modelToView") { public Object map() throws BadLocationException { return(((JTextComponent)getSource()).modelToView(i)); }}));} /**Maps JTextComponent.moveCaretPosition(int) through queue*/ public void moveCaretPosition(final int i) { runMapping(new MapVoidAction("moveCaretPosition") { public void map() { ((JTextComponent)getSource()).moveCaretPosition(i); }});} /**Maps JTextComponent.paste() through queue*/ public void paste() { runMapping(new MapVoidAction("paste") { public void map() { ((JTextComponent)getSource()).paste(); }});} /**Maps JTextComponent.read(Reader, Object) through queue*/ public void read(final Reader reader, final Object object) { runMapping(new MapVoidAction("read") { public void map() throws IOException { ((JTextComponent)getSource()).read(reader, object); }});} /**Maps JTextComponent.removeCaretListener(CaretListener) through queue*/ public void removeCaretListener(final CaretListener caretListener) { runMapping(new MapVoidAction("removeCaretListener") { public void map() { ((JTextComponent)getSource()).removeCaretListener(caretListener); }});} /**Maps JTextComponent.replaceSelection(String) through queue*/ public void replaceSelection(final String string) { runMapping(new MapVoidAction("replaceSelection") { public void map() { ((JTextComponent)getSource()).replaceSelection(string); }});} /**Maps JTextComponent.select(int, int) through queue*/ public void select(final int i, final int i1) { runMapping(new MapVoidAction("select") { public void map() { ((JTextComponent)getSource()).select(i, i1); }});} /**Maps JTextComponent.selectAll() through queue*/ public void selectAll() { runMapping(new MapVoidAction("selectAll") { public void map() { ((JTextComponent)getSource()).selectAll(); }});} /**Maps JTextComponent.setCaret(Caret) through queue*/ public void setCaret(final Caret caret) { runMapping(new MapVoidAction("setCaret") { public void map() { ((JTextComponent)getSource()).setCaret(caret); }});} /**Maps JTextComponent.setCaretColor(Color) through queue*/ public void setCaretColor(final Color color) { runMapping(new MapVoidAction("setCaretColor") { public void map() { ((JTextComponent)getSource()).setCaretColor(color); }});} /**Maps JTextComponent.setCaretPosition(int) through queue*/ public void setCaretPosition(final int i) { runMapping(new MapVoidAction("setCaretPosition") { public void map() { ((JTextComponent)getSource()).setCaretPosition(i); }});} /**Maps JTextComponent.setDisabledTextColor(Color) through queue*/ public void setDisabledTextColor(final Color color) { runMapping(new MapVoidAction("setDisabledTextColor") { public void map() { ((JTextComponent)getSource()).setDisabledTextColor(color); }});} /**Maps JTextComponent.setDocument(Document) through queue*/ public void setDocument(final Document document) { runMapping(new MapVoidAction("setDocument") { public void map() { ((JTextComponent)getSource()).setDocument(document); }});} /**Maps JTextComponent.setEditable(boolean) through queue*/ public void setEditable(final boolean b) { runMapping(new MapVoidAction("setEditable") { public void map() { ((JTextComponent)getSource()).setEditable(b); }});} /**Maps JTextComponent.setFocusAccelerator(char) through queue*/ public void setFocusAccelerator(final char c) { runMapping(new MapVoidAction("setFocusAccelerator") { public void map() { ((JTextComponent)getSource()).setFocusAccelerator(c); }});} /**Maps JTextComponent.setHighlighter(Highlighter) through queue*/ public void setHighlighter(final Highlighter highlighter) { runMapping(new MapVoidAction("setHighlighter") { public void map() { ((JTextComponent)getSource()).setHighlighter(highlighter); }});} /**Maps JTextComponent.setKeymap(Keymap) through queue*/ public void setKeymap(final Keymap keymap) { runMapping(new MapVoidAction("setKeymap") { public void map() { ((JTextComponent)getSource()).setKeymap(keymap); }});} /**Maps JTextComponent.setMargin(Insets) through queue*/ public void setMargin(final Insets insets) { runMapping(new MapVoidAction("setMargin") { public void map() { ((JTextComponent)getSource()).setMargin(insets); }});} /**Maps JTextComponent.setSelectedTextColor(Color) through queue*/ public void setSelectedTextColor(final Color color) { runMapping(new MapVoidAction("setSelectedTextColor") { public void map() { ((JTextComponent)getSource()).setSelectedTextColor(color); }});} /**Maps JTextComponent.setSelectionColor(Color) through queue*/ public void setSelectionColor(final Color color) { runMapping(new MapVoidAction("setSelectionColor") { public void map() { ((JTextComponent)getSource()).setSelectionColor(color); }});} /**Maps JTextComponent.setSelectionEnd(int) through queue*/ public void setSelectionEnd(final int i) { runMapping(new MapVoidAction("setSelectionEnd") { public void map() { ((JTextComponent)getSource()).setSelectionEnd(i); }});} /**Maps JTextComponent.setSelectionStart(int) through queue*/ public void setSelectionStart(final int i) { runMapping(new MapVoidAction("setSelectionStart") { public void map() { ((JTextComponent)getSource()).setSelectionStart(i); }});} /**Maps JTextComponent.setText(String) through queue*/ public void setText(final String string) { runMapping(new MapVoidAction("setText") { public void map() { ((JTextComponent)getSource()).setText(string); }});} /**Maps JTextComponent.setUI(TextUI) through queue*/ public void setUI(final TextUI textUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JTextComponent)getSource()).setUI(textUI); }});} /**Maps JTextComponent.viewToModel(Point) through queue*/ public int viewToModel(final Point point) { return(runMapping(new MapIntegerAction("viewToModel") { public int map() { return(((JTextComponent)getSource()).viewToModel(point)); }}));} /**Maps JTextComponent.write(Writer) through queue*/ public void write(final Writer writer) { runMapping(new MapVoidAction("write") { public void map() throws IOException { ((JTextComponent)getSource()).write(writer); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Can be throught during a text operation * if text has not been found in the component. */ public class NoSuchTextException extends JemmyInputException { /** * Constructor. * @param text a nonexistent text. */ public NoSuchTextException(String text) { super("No such text as \"" + text + "\"", getSource()); } } /** * Interface defining additional text cearch criteria. * @see #getPositionByText(java.lang.String, JTextComponentOperator.TextChooser) */ public interface TextChooser { /** * Checkes if position fits the criteria. * @param document a document to be checked. * @param offset a checked position * @return true if the position fits the criteria. */ public boolean checkPosition(Document document, int offset); /** * Returns a printable description of the criteria. * @return a description of this chooser. */ public String getDescription(); } /** * Allows to find component by text. */ public static class JTextComponentByTextFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs JTextComponentByTextFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public JTextComponentByTextFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs JTextComponentByTextFinder. * @param lb a text pattern */ public JTextComponentByTextFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JTextComponent) { if(((JTextComponent)comp).getText() != null) { return(comparator.equals(((JTextComponent)comp).getText(), label)); } } return(false); } public String getDescription() { return("JTextComponent with text \"" + label + "\""); } } /** * Checks component type. */ public static class JTextComponentFinder extends Finder { /** * Constructs JTextComponentFinder. * @param sf other searching criteria. */ public JTextComponentFinder(ComponentChooser sf) { super(JTextComponent.class, sf); } /** * Constructs JTextComponentFinder. */ public JTextComponentFinder() { super(JTextComponent.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/ScrollbarOperator.java0000644000175000017500000004411711245712347023620 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Container; import java.awt.Scrollbar; import java.awt.event.AdjustmentListener; import org.netbeans.jemmy.Action; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.Waitable; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.ScrollDriver; import org.netbeans.jemmy.drivers.scrolling.ScrollAdjuster; /** *

Timeouts used:
* ScrollbarOperator.WholeScrollTimeout - time for one scroll click
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class ScrollbarOperator extends ComponentOperator implements Timeoutable, Outputable{ private final static long ONE_SCROLL_CLICK_TIMEOUT = 0; private final static long WHOLE_SCROLL_TIMEOUT = 60000; private final static long BEFORE_DROP_TIMEOUT = 0; private final static long DRAG_AND_DROP_SCROLLING_DELTA = 0; private Timeouts timeouts; private TestOut output; private ScrollDriver driver; /** * Constructs a ScrollbarOperator object. * @param b a component */ public ScrollbarOperator(Scrollbar b) { super(b); driver = DriverManager.getScrollDriver(getClass()); } /** * Constructs a ScrollbarOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public ScrollbarOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((Scrollbar)cont. waitSubComponent(new ScrollbarFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a ScrollbarOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public ScrollbarOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructs a ScrollbarOperator object. * @param cont a container * @param index an index between appropriate ones. */ public ScrollbarOperator(ContainerOperator cont, int index) { this((Scrollbar)waitComponent(cont, new ScrollbarFinder(), index)); copyEnvironment(cont); } /** * Constructs a ScrollbarOperator object. * @param cont a container */ public ScrollbarOperator(ContainerOperator cont) { this(cont, 0); } /** * Finds a scrollbar. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @return the scrollbar fitting searching criteria */ public static Scrollbar findScrollbar(Container cont, ComponentChooser chooser, int index) { return((Scrollbar)findComponent(cont, new ScrollbarFinder(chooser), index)); } /** * Finds a scrollbar. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @return the scrollbar fitting searching criteria */ public static Scrollbar findScrollbar(Container cont, ComponentChooser chooser) { return(findScrollbar(cont, chooser, 0)); } /** * Finds a scrollbar. * @param cont a container * @param index an index between appropriate ones. * @return the scrollbar fitting searching criteria */ public static Scrollbar findScrollbar(Container cont, int index) { return(findScrollbar(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th Scrollbar instance"), index)); } /** * Finds a scrollbar. * @param cont a container * @return the scrollbar fitting searching criteria */ public static Scrollbar findScrollbar(Container cont) { return(findScrollbar(cont, 0)); } /** * Waits a scrollbar. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @return the scrollbar fitting searching criteria */ public static Scrollbar waitScrollbar(Container cont, ComponentChooser chooser, int index) { return((Scrollbar)waitComponent(cont, new ScrollbarFinder(chooser), index)); } /** * Waits a scrollbar. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @return the scrollbar fitting searching criteria */ public static Scrollbar waitScrollbar(Container cont, ComponentChooser chooser) { return(waitScrollbar(cont, chooser, 0)); } /** * Waits a scrollbar. * @param cont a container * @param index an index between appropriate ones. * @return the scrollbar fitting searching criteria */ public static Scrollbar waitScrollbar(Container cont, int index) { return(waitScrollbar(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th Scrollbar instance"), index)); } /** * Waits a scrollbar. * @param cont a container * @return the scrollbar fitting searching criteria */ public static Scrollbar waitScrollbar(Container cont) { return(waitScrollbar(cont, 0)); } static { Timeouts.initDefault("ScrollbarOperator.OneScrollClickTimeout", ONE_SCROLL_CLICK_TIMEOUT); Timeouts.initDefault("ScrollbarOperator.WholeScrollTimeout", WHOLE_SCROLL_TIMEOUT); Timeouts.initDefault("ScrollbarOperator.BeforeDropTimeout", BEFORE_DROP_TIMEOUT); Timeouts.initDefault("ScrollbarOperator.DragAndDropScrollingDelta", DRAG_AND_DROP_SCROLLING_DELTA); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; super.setTimeouts(timeouts); } public Timeouts getTimeouts() { return(timeouts); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (ScrollDriver)DriverManager. getDriver(DriverManager.SCROLL_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Scrolls scrollbar to the position defined by w parameter. * Uses ScrollDriver registered to this operator type. * @param w Scrolling is stopped when w.actionProduced(waiterParam) != null * @param waiterParam a waiting parameter. * @param increase a scrolling direction. * @throws TimeoutExpiredException */ public void scrollTo(Waitable w, Object waiterParam, boolean increase) { scrollTo(new WaitableChecker(w, waiterParam, increase, this)); } /** * Scrolls scrollbar to the position defined by a ScrollAdjuster implementation. * @param adj defines scrolling direction, and so on. * @throws TimeoutExpiredException */ public void scrollTo(final ScrollAdjuster adj) { produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scroll(ScrollbarOperator.this, adj); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("ScrollbarOperator.WholeScrollTimeout")); } /** * Scrolls scroll bar to necessary value. * @param value Scroll bar value to scroll to. * @throws TimeoutExpiredException */ public void scrollToValue(int value) { output.printTrace("Scroll Scrollbar to " + Integer.toString(value) + " value\n" + toStringSource()); output.printGolden("Scroll Scrollbar to " + Integer.toString(value) + " value"); scrollTo(new ValueScrollAdjuster(value)); } /** * Scrolls scroll bar to necessary proportional value. * @param proportionalValue Proportional scroll to. Must be >= 0 and <= 1. * @throws TimeoutExpiredException */ public void scrollToValue(double proportionalValue) { output.printTrace("Scroll Scrollbar to " + Double.toString(proportionalValue) + " proportional value\n" + toStringSource()); output.printGolden("Scroll Scrollbar to " + Double.toString(proportionalValue) + " proportional value"); scrollTo(new ValueScrollAdjuster((int)(getMinimum() + (getMaximum() - getVisibleAmount() - getMinimum()) * proportionalValue))); } /** * Scrolls to minimum value. * @throws TimeoutExpiredException */ public void scrollToMinimum() { output.printTrace("Scroll Scrollbar to minimum value\n" + toStringSource()); output.printGolden("Scroll Scrollbar to minimum value"); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scrollToMinimum(ScrollbarOperator.this, getOrientation()); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("ScrollbarOperator.WholeScrollTimeout")); } /** * Scrolls to maximum value. * @throws TimeoutExpiredException */ public void scrollToMaximum() { output.printTrace("Scroll Scrollbar to maximum value\n" + toStringSource()); output.printGolden("Scroll Scrollbar to maximum value"); produceTimeRestricted(new Action() { public Object launch(Object obj) { driver.scrollToMaximum(ScrollbarOperator.this, getOrientation()); return(null); } public String getDescription() { return("Scrolling"); } }, getTimeouts().getTimeout("ScrollbarOperator.WholeScrollTimeout")); } //////////////////////////////////////////////////////// //Mapping // /**Maps Scrollbar.addAdjustmentListener(AdjustmentListener) through queue*/ public void addAdjustmentListener(final AdjustmentListener adjustmentListener) { runMapping(new MapVoidAction("addAdjustmentListener") { public void map() { ((Scrollbar)getSource()).addAdjustmentListener(adjustmentListener); }});} /**Maps Scrollbar.getBlockIncrement() through queue*/ public int getBlockIncrement() { return(runMapping(new MapIntegerAction("getBlockIncrement") { public int map() { return(((Scrollbar)getSource()).getBlockIncrement()); }}));} /**Maps Scrollbar.getMaximum() through queue*/ public int getMaximum() { return(runMapping(new MapIntegerAction("getMaximum") { public int map() { return(((Scrollbar)getSource()).getMaximum()); }}));} /**Maps Scrollbar.getMinimum() through queue*/ public int getMinimum() { return(runMapping(new MapIntegerAction("getMinimum") { public int map() { return(((Scrollbar)getSource()).getMinimum()); }}));} /**Maps Scrollbar.getOrientation() through queue*/ public int getOrientation() { return(runMapping(new MapIntegerAction("getOrientation") { public int map() { return(((Scrollbar)getSource()).getOrientation()); }}));} /**Maps Scrollbar.getUnitIncrement() through queue*/ public int getUnitIncrement() { return(runMapping(new MapIntegerAction("getUnitIncrement") { public int map() { return(((Scrollbar)getSource()).getUnitIncrement()); }}));} /**Maps Scrollbar.getValue() through queue*/ public int getValue() { return(runMapping(new MapIntegerAction("getValue") { public int map() { return(((Scrollbar)getSource()).getValue()); }}));} /**Maps Scrollbar.getVisibleAmount() through queue*/ public int getVisibleAmount() { return(runMapping(new MapIntegerAction("getVisibleAmount") { public int map() { return(((Scrollbar)getSource()).getVisibleAmount()); }}));} /**Maps Scrollbar.removeAdjustmentListener(AdjustmentListener) through queue*/ public void removeAdjustmentListener(final AdjustmentListener adjustmentListener) { runMapping(new MapVoidAction("removeAdjustmentListener") { public void map() { ((Scrollbar)getSource()).removeAdjustmentListener(adjustmentListener); }});} /**Maps Scrollbar.setBlockIncrement(int) through queue*/ public void setBlockIncrement(final int i) { runMapping(new MapVoidAction("setBlockIncrement") { public void map() { ((Scrollbar)getSource()).setBlockIncrement(i); }});} /**Maps Scrollbar.setMaximum(int) through queue*/ public void setMaximum(final int i) { runMapping(new MapVoidAction("setMaximum") { public void map() { ((Scrollbar)getSource()).setMaximum(i); }});} /**Maps Scrollbar.setMinimum(int) through queue*/ public void setMinimum(final int i) { runMapping(new MapVoidAction("setMinimum") { public void map() { ((Scrollbar)getSource()).setMinimum(i); }});} /**Maps Scrollbar.setOrientation(int) through queue*/ public void setOrientation(final int i) { runMapping(new MapVoidAction("setOrientation") { public void map() { ((Scrollbar)getSource()).setOrientation(i); }});} /**Maps Scrollbar.setUnitIncrement(int) through queue*/ public void setUnitIncrement(final int i) { runMapping(new MapVoidAction("setUnitIncrement") { public void map() { ((Scrollbar)getSource()).setUnitIncrement(i); }});} /**Maps Scrollbar.setValue(int) through queue*/ public void setValue(final int i) { runMapping(new MapVoidAction("setValue") { public void map() { ((Scrollbar)getSource()).setValue(i); }});} /**Maps Scrollbar.setValues(int, int, int, int) through queue*/ public void setValues(final int i, final int i1, final int i2, final int i3) { runMapping(new MapVoidAction("setValues") { public void map() { ((Scrollbar)getSource()).setValues(i, i1, i2, i3); }});} /**Maps Scrollbar.setVisibleAmount(int) through queue*/ public void setVisibleAmount(final int i) { runMapping(new MapVoidAction("setVisibleAmount") { public void map() { ((Scrollbar)getSource()).setVisibleAmount(i); }});} //End of mapping // //////////////////////////////////////////////////////// private class ValueScrollAdjuster implements ScrollAdjuster { int value; public ValueScrollAdjuster(int value) { this.value = value; } public int getScrollDirection() { if(getValue() == value) { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } else { return((getValue() < value) ? ScrollAdjuster.INCREASE_SCROLL_DIRECTION : ScrollAdjuster.DECREASE_SCROLL_DIRECTION); } } public int getScrollOrientation() { return(getOrientation()); } public String getDescription() { return("Scroll to " + Integer.toString(value) + " value"); } } private class WaitableChecker implements ScrollAdjuster { Waitable w; Object waitParam; boolean increase; boolean reached = false; public WaitableChecker(Waitable w, Object waitParam, boolean increase, ScrollbarOperator oper) { this.w = w; this.waitParam = waitParam; this.increase = increase; } public int getScrollDirection() { if(!reached && w.actionProduced(waitParam) != null) { reached = true; } if(reached) { return(this.DO_NOT_TOUCH_SCROLL_DIRECTION); } else { return(increase ? this.INCREASE_SCROLL_DIRECTION : this.DECREASE_SCROLL_DIRECTION); } } public int getScrollOrientation() { return(getOrientation()); } public String getDescription() { return(w.getDescription()); } } /** * Checks component type. */ public static class ScrollbarFinder extends Finder { /** * Constructs ScrollbarFinder. * @param sf other searching criteria. */ public ScrollbarFinder(ComponentChooser sf) { super(Scrollbar.class, sf); } /** * Constructs ScrollbarFinder. */ public ScrollbarFinder() { super(Scrollbar.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JComponentOperator.java0000644000175000017500000010541611245712237023747 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Window; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.beans.VetoableChangeListener; import java.util.Hashtable; import javax.accessibility.AccessibleContext; import javax.swing.JComponent; import javax.swing.JInternalFrame; import javax.swing.JRootPane; import javax.swing.JToolTip; import javax.swing.KeyStroke; import javax.swing.border.Border; import javax.swing.event.AncestorListener; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; /** *

Timeouts used:
* JComponentOperator.WaitToolTipTimeout - time to wait tool tip displayed
* JComponentOperator.ShowToolTipTimeout - time to show tool tip
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JComponentOperator extends ContainerOperator implements Timeoutable, Outputable{ /** * Identifier for a "tooltip text" property. * @see #getDump */ public static final String TOOLTIP_TEXT_DPROP = "Tooltip text"; public static final String A11Y_DATA = "Accessible data (yes/no)"; public static final String A11Y_NAME_DPROP = "Accessible name"; public static final String A11Y_DESCRIPTION_DPROP = "Accessible decription"; private final static long WAIT_TOOL_TIP_TIMEOUT = 10000; private final static long SHOW_TOOL_TIP_TIMEOUT = 0; private Timeouts timeouts; private TestOut output; /** * Constructor. * @param b a component */ public JComponentOperator(JComponent b) { super(b); } /** * Constructs a JComponentOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JComponentOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JComponent)cont. waitSubComponent(new JComponentFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JComponentOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JComponentOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JComponentOperator(ContainerOperator cont, int index) { this((JComponent)waitComponent(cont, new JComponentFinder(ComponentSearcher.getTrueChooser("Any JComponent")), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @throws TimeoutExpiredException */ public JComponentOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JComponent in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JComponent instance or null if component was not found. */ public static JComponent findJComponent(Container cont, ComponentChooser chooser, int index) { return((JComponent)findComponent(cont, new JComponentFinder(chooser), index)); } /** * Searches 0'th JComponent in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JComponent instance or null if component was not found. */ public static JComponent findJComponent(Container cont, ComponentChooser chooser) { return(findJComponent(cont, chooser, 0)); } /** * Searches JComponent by tooltip text. * @param cont Container to search component in. * @param toolTipText Tooltip text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JComponent instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JComponent findJComponent(Container cont, String toolTipText, boolean ce, boolean ccs, int index) { return(findJComponent(cont, new JComponentByTipFinder(toolTipText, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches JComponent by tooltip text. * @param cont Container to search component in. * @param toolTipText Tooltip text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JComponent instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JComponent findJComponent(Container cont, String toolTipText, boolean ce, boolean ccs) { return(findJComponent(cont, toolTipText, ce, ccs, 0)); } /** * Waits JComponent in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JComponent instance or null if component was not found. * @throws TimeoutExpiredException */ public static JComponent waitJComponent(Container cont, ComponentChooser chooser, final int index) { return((JComponent)waitComponent(cont, new JComponentFinder(chooser), index)); } /** * Waits 0'th JComponent in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JComponent instance or null if component was not found. * @throws TimeoutExpiredException */ public static JComponent waitJComponent(Container cont, ComponentChooser chooser) { return(waitJComponent(cont, chooser, 0)); } /** * Waits JComponent by tooltip text. * @param cont Container to search component in. * @param toolTipText Tooltip text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JComponent instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JComponent waitJComponent(Container cont, String toolTipText, boolean ce, boolean ccs, int index) { return(waitJComponent(cont, new JComponentByTipFinder(toolTipText, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits JComponent by tooltip text. * @param cont Container to search component in. * @param toolTipText Tooltip text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JComponent instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JComponent waitJComponent(Container cont, String toolTipText, boolean ce, boolean ccs) { return(waitJComponent(cont, toolTipText, ce, ccs, 0)); } static { Timeouts.initDefault("JComponentOperator.WaitToolTipTimeout", WAIT_TOOL_TIP_TIMEOUT); Timeouts.initDefault("JComponentOperator.ShowToolTipTimeout", SHOW_TOOL_TIP_TIMEOUT); } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } public int getCenterXForClick() { Rectangle rect = getVisibleRect(); return((int)rect.getX() + (int)rect.getWidth() / 2); } public int getCenterYForClick() { Rectangle rect = getVisibleRect(); return((int)rect.getY() + (int)rect.getHeight() / 2); } /** * Showes tool tip. * @return JToolTip component. * @throws TimeoutExpiredException */ public JToolTip showToolTip() { enterMouse(); moveMouse(getCenterXForClick(), getCenterYForClick()); return(waitToolTip()); } public JToolTip waitToolTip() { return((JToolTip)waitComponent(WindowOperator. waitWindow(new JToolTipWindowFinder(), 0, getTimeouts(), getOutput()), new JToolTipFinder(), 0, getTimeouts(), getOutput())); } /** * Looks for a first window-like container. * @return either WindowOperator of JInternalFrameOperator */ public ContainerOperator getWindowContainerOperator() { Component resultComp; if(getSource() instanceof Window) { resultComp = getSource(); } else { resultComp = getContainer(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp instanceof Window || comp instanceof JInternalFrame); } public String getDescription() { return(""); } }); } ContainerOperator result; if(resultComp instanceof Window) { result = new WindowOperator((Window)resultComp); } else { result = new ContainerOperator((Container)resultComp); } result.copyEnvironment(this); return(result); } public Hashtable getDump() { Hashtable result = super.getDump(); if(getToolTipText() != null) { result.put(TOOLTIP_TEXT_DPROP, getToolTipText()); } //System.out.println("Dump a11y = " + System.getProperty("jemmy.dump.a11y")); if(System.getProperty("jemmy.dump.a11y") != null && System.getProperty("jemmy.dump.a11y").equals("on")) { AccessibleContext a11y = ((JComponent)getSource()).getAccessibleContext(); if(a11y != null) { result.put(A11Y_DATA, "yes"); String accName = (a11y.getAccessibleName() == null) ? "null" : a11y.getAccessibleName(); String accDesc = (a11y.getAccessibleDescription() == null) ? "null" : a11y.getAccessibleDescription(); result.put(A11Y_NAME_DPROP, accName); result.put(A11Y_DESCRIPTION_DPROP, accDesc); } else { result.put(A11Y_DATA, "no"); } } return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JComponent.addAncestorListener(AncestorListener) through queue*/ public void addAncestorListener(final AncestorListener ancestorListener) { runMapping(new MapVoidAction("addAncestorListener") { public void map() { ((JComponent)getSource()).addAncestorListener(ancestorListener); }});} /**Maps JComponent.addVetoableChangeListener(VetoableChangeListener) through queue*/ public void addVetoableChangeListener(final VetoableChangeListener vetoableChangeListener) { runMapping(new MapVoidAction("addVetoableChangeListener") { public void map() { ((JComponent)getSource()).addVetoableChangeListener(vetoableChangeListener); }});} /**Maps JComponent.computeVisibleRect(Rectangle) through queue*/ public void computeVisibleRect(final Rectangle rectangle) { runMapping(new MapVoidAction("computeVisibleRect") { public void map() { ((JComponent)getSource()).computeVisibleRect(rectangle); }});} /**Maps JComponent.createToolTip() through queue*/ public JToolTip createToolTip() { return((JToolTip)runMapping(new MapAction("createToolTip") { public Object map() { return(((JComponent)getSource()).createToolTip()); }}));} /**Maps JComponent.firePropertyChange(String, byte, byte) through queue*/ public void firePropertyChange(final String string, final byte b, final byte b1) { runMapping(new MapVoidAction("firePropertyChange") { public void map() { ((JComponent)getSource()).firePropertyChange(string, b, b1); }});} /**Maps JComponent.firePropertyChange(String, char, char) through queue*/ public void firePropertyChange(final String string, final char c, final char c1) { runMapping(new MapVoidAction("firePropertyChange") { public void map() { ((JComponent)getSource()).firePropertyChange(string, c, c1); }});} /**Maps JComponent.firePropertyChange(String, double, double) through queue*/ public void firePropertyChange(final String string, final double d, final double d1) { runMapping(new MapVoidAction("firePropertyChange") { public void map() { ((JComponent)getSource()).firePropertyChange(string, d, d1); }});} /**Maps JComponent.firePropertyChange(String, float, float) through queue*/ public void firePropertyChange(final String string, final float f, final float f1) { runMapping(new MapVoidAction("firePropertyChange") { public void map() { ((JComponent)getSource()).firePropertyChange(string, f, f1); }});} /**Maps JComponent.firePropertyChange(String, int, int) through queue*/ public void firePropertyChange(final String string, final int i, final int i1) { runMapping(new MapVoidAction("firePropertyChange") { public void map() { ((JComponent)getSource()).firePropertyChange(string, i, i1); }});} /**Maps JComponent.firePropertyChange(String, long, long) through queue*/ public void firePropertyChange(final String string, final long l, final long l1) { runMapping(new MapVoidAction("firePropertyChange") { public void map() { ((JComponent)getSource()).firePropertyChange(string, l, l1); }});} /**Maps JComponent.firePropertyChange(String, short, short) through queue*/ public void firePropertyChange(final String string, final short s, final short s1) { runMapping(new MapVoidAction("firePropertyChange") { public void map() { ((JComponent)getSource()).firePropertyChange(string, s, s1); }});} /**Maps JComponent.firePropertyChange(String, boolean, boolean) through queue*/ public void firePropertyChange(final String string, final boolean b, final boolean b1) { runMapping(new MapVoidAction("firePropertyChange") { public void map() { ((JComponent)getSource()).firePropertyChange(string, b, b1); }});} /**Maps JComponent.getAccessibleContext() through queue*/ public AccessibleContext getAccessibleContext() { return((AccessibleContext)runMapping(new MapAction("getAccessibleContext") { public Object map() { return(((JComponent)getSource()).getAccessibleContext()); }}));} /**Maps JComponent.getActionForKeyStroke(KeyStroke) through queue*/ public ActionListener getActionForKeyStroke(final KeyStroke keyStroke) { return((ActionListener)runMapping(new MapAction("getActionForKeyStroke") { public Object map() { return(((JComponent)getSource()).getActionForKeyStroke(keyStroke)); }}));} /**Maps JComponent.getAutoscrolls() through queue*/ public boolean getAutoscrolls() { return(runMapping(new MapBooleanAction("getAutoscrolls") { public boolean map() { return(((JComponent)getSource()).getAutoscrolls()); }}));} /**Maps JComponent.getBorder() through queue*/ public Border getBorder() { return((Border)runMapping(new MapAction("getBorder") { public Object map() { return(((JComponent)getSource()).getBorder()); }}));} /**Maps JComponent.getClientProperty(Object) through queue*/ public Object getClientProperty(final Object object) { return((Object)runMapping(new MapAction("getClientProperty") { public Object map() { return(((JComponent)getSource()).getClientProperty(object)); }}));} /**Maps JComponent.getConditionForKeyStroke(KeyStroke) through queue*/ public int getConditionForKeyStroke(final KeyStroke keyStroke) { return(runMapping(new MapIntegerAction("getConditionForKeyStroke") { public int map() { return(((JComponent)getSource()).getConditionForKeyStroke(keyStroke)); }}));} /**Maps JComponent.getDebugGraphicsOptions() through queue*/ public int getDebugGraphicsOptions() { return(runMapping(new MapIntegerAction("getDebugGraphicsOptions") { public int map() { return(((JComponent)getSource()).getDebugGraphicsOptions()); }}));} /**Maps JComponent.getInsets(Insets) through queue*/ public Insets getInsets(final Insets insets) { return((Insets)runMapping(new MapAction("getInsets") { public Object map() { return(((JComponent)getSource()).getInsets(insets)); }}));} /**Maps JComponent.getNextFocusableComponent() through queue*/ public Component getNextFocusableComponent() { return((Component)runMapping(new MapAction("getNextFocusableComponent") { public Object map() { return(((JComponent)getSource()).getNextFocusableComponent()); }}));} /**Maps JComponent.getRegisteredKeyStrokes() through queue*/ public KeyStroke[] getRegisteredKeyStrokes() { return((KeyStroke[])runMapping(new MapAction("getRegisteredKeyStrokes") { public Object map() { return(((JComponent)getSource()).getRegisteredKeyStrokes()); }}));} /**Maps JComponent.getRootPane() through queue*/ public JRootPane getRootPane() { return((JRootPane)runMapping(new MapAction("getRootPane") { public Object map() { return(((JComponent)getSource()).getRootPane()); }}));} /**Maps JComponent.getToolTipLocation(MouseEvent) through queue*/ public Point getToolTipLocation(final MouseEvent mouseEvent) { return((Point)runMapping(new MapAction("getToolTipLocation") { public Object map() { return(((JComponent)getSource()).getToolTipLocation(mouseEvent)); }}));} /**Maps JComponent.getToolTipText() through queue*/ public String getToolTipText() { return((String)runMapping(new MapAction("getToolTipText") { public Object map() { return(((JComponent)getSource()).getToolTipText()); }}));} /**Maps JComponent.getToolTipText(MouseEvent) through queue*/ public String getToolTipText(final MouseEvent mouseEvent) { return((String)runMapping(new MapAction("getToolTipText") { public Object map() { return(((JComponent)getSource()).getToolTipText(mouseEvent)); }}));} /**Maps JComponent.getTopLevelAncestor() through queue*/ public Container getTopLevelAncestor() { return((Container)runMapping(new MapAction("getTopLevelAncestor") { public Object map() { return(((JComponent)getSource()).getTopLevelAncestor()); }}));} /**Maps JComponent.getUIClassID() through queue*/ public String getUIClassID() { return((String)runMapping(new MapAction("getUIClassID") { public Object map() { return(((JComponent)getSource()).getUIClassID()); }}));} /**Maps JComponent.getVisibleRect() through queue*/ public Rectangle getVisibleRect() { return((Rectangle)runMapping(new MapAction("getVisibleRect") { public Object map() { return(((JComponent)getSource()).getVisibleRect()); }}));} /**Maps JComponent.grabFocus() through queue*/ public void grabFocus() { runMapping(new MapVoidAction("grabFocus") { public void map() { ((JComponent)getSource()).grabFocus(); }});} /**Maps JComponent.isFocusCycleRoot() through queue*/ public boolean isFocusCycleRoot() { return(runMapping(new MapBooleanAction("isFocusCycleRoot") { public boolean map() { return(((JComponent)getSource()).isFocusCycleRoot()); }}));} /**Maps JComponent.isManagingFocus() through queue*/ public boolean isManagingFocus() { return(runMapping(new MapBooleanAction("isManagingFocus") { public boolean map() { return(((JComponent)getSource()).isManagingFocus()); }}));} /**Maps JComponent.isOptimizedDrawingEnabled() through queue*/ public boolean isOptimizedDrawingEnabled() { return(runMapping(new MapBooleanAction("isOptimizedDrawingEnabled") { public boolean map() { return(((JComponent)getSource()).isOptimizedDrawingEnabled()); }}));} /**Maps JComponent.isPaintingTile() through queue*/ public boolean isPaintingTile() { return(runMapping(new MapBooleanAction("isPaintingTile") { public boolean map() { return(((JComponent)getSource()).isPaintingTile()); }}));} /**Maps JComponent.isRequestFocusEnabled() through queue*/ public boolean isRequestFocusEnabled() { return(runMapping(new MapBooleanAction("isRequestFocusEnabled") { public boolean map() { return(((JComponent)getSource()).isRequestFocusEnabled()); }}));} /**Maps JComponent.isValidateRoot() through queue*/ public boolean isValidateRoot() { return(runMapping(new MapBooleanAction("isValidateRoot") { public boolean map() { return(((JComponent)getSource()).isValidateRoot()); }}));} /**Maps JComponent.paintImmediately(int, int, int, int) through queue*/ public void paintImmediately(final int i, final int i1, final int i2, final int i3) { runMapping(new MapVoidAction("paintImmediately") { public void map() { ((JComponent)getSource()).paintImmediately(i, i1, i2, i3); }});} /**Maps JComponent.paintImmediately(Rectangle) through queue*/ public void paintImmediately(final Rectangle rectangle) { runMapping(new MapVoidAction("paintImmediately") { public void map() { ((JComponent)getSource()).paintImmediately(rectangle); }});} /**Maps JComponent.putClientProperty(Object, Object) through queue*/ public void putClientProperty(final Object object, final Object object1) { runMapping(new MapVoidAction("putClientProperty") { public void map() { ((JComponent)getSource()).putClientProperty(object, object1); }});} /**Maps JComponent.registerKeyboardAction(ActionListener, String, KeyStroke, int) through queue*/ public void registerKeyboardAction(final ActionListener actionListener, final String string, final KeyStroke keyStroke, final int i) { runMapping(new MapVoidAction("registerKeyboardAction") { public void map() { ((JComponent)getSource()).registerKeyboardAction(actionListener, string, keyStroke, i); }});} /**Maps JComponent.registerKeyboardAction(ActionListener, KeyStroke, int) through queue*/ public void registerKeyboardAction(final ActionListener actionListener, final KeyStroke keyStroke, final int i) { runMapping(new MapVoidAction("registerKeyboardAction") { public void map() { ((JComponent)getSource()).registerKeyboardAction(actionListener, keyStroke, i); }});} /**Maps JComponent.removeAncestorListener(AncestorListener) through queue*/ public void removeAncestorListener(final AncestorListener ancestorListener) { runMapping(new MapVoidAction("removeAncestorListener") { public void map() { ((JComponent)getSource()).removeAncestorListener(ancestorListener); }});} /**Maps JComponent.removeVetoableChangeListener(VetoableChangeListener) through queue*/ public void removeVetoableChangeListener(final VetoableChangeListener vetoableChangeListener) { runMapping(new MapVoidAction("removeVetoableChangeListener") { public void map() { ((JComponent)getSource()).removeVetoableChangeListener(vetoableChangeListener); }});} /**Maps JComponent.repaint(Rectangle) through queue*/ public void repaint(final Rectangle rectangle) { runMapping(new MapVoidAction("repaint") { public void map() { ((JComponent)getSource()).repaint(rectangle); }});} /**Maps JComponent.requestDefaultFocus() through queue*/ public boolean requestDefaultFocus() { return(runMapping(new MapBooleanAction("requestDefaultFocus") { public boolean map() { return(((JComponent)getSource()).requestDefaultFocus()); }}));} /**Maps JComponent.resetKeyboardActions() through queue*/ public void resetKeyboardActions() { runMapping(new MapVoidAction("resetKeyboardActions") { public void map() { ((JComponent)getSource()).resetKeyboardActions(); }});} /**Maps JComponent.revalidate() through queue*/ public void revalidate() { runMapping(new MapVoidAction("revalidate") { public void map() { ((JComponent)getSource()).revalidate(); }});} /**Maps JComponent.scrollRectToVisible(Rectangle) through queue*/ public void scrollRectToVisible(final Rectangle rectangle) { runMapping(new MapVoidAction("scrollRectToVisible") { public void map() { ((JComponent)getSource()).scrollRectToVisible(rectangle); }});} /**Maps JComponent.setAlignmentX(float) through queue*/ public void setAlignmentX(final float f) { runMapping(new MapVoidAction("setAlignmentX") { public void map() { ((JComponent)getSource()).setAlignmentX(f); }});} /**Maps JComponent.setAlignmentY(float) through queue*/ public void setAlignmentY(final float f) { runMapping(new MapVoidAction("setAlignmentY") { public void map() { ((JComponent)getSource()).setAlignmentY(f); }});} /**Maps JComponent.setAutoscrolls(boolean) through queue*/ public void setAutoscrolls(final boolean b) { runMapping(new MapVoidAction("setAutoscrolls") { public void map() { ((JComponent)getSource()).setAutoscrolls(b); }});} /**Maps JComponent.setBorder(Border) through queue*/ public void setBorder(final Border border) { runMapping(new MapVoidAction("setBorder") { public void map() { ((JComponent)getSource()).setBorder(border); }});} /**Maps JComponent.setDebugGraphicsOptions(int) through queue*/ public void setDebugGraphicsOptions(final int i) { runMapping(new MapVoidAction("setDebugGraphicsOptions") { public void map() { ((JComponent)getSource()).setDebugGraphicsOptions(i); }});} /**Maps JComponent.setDoubleBuffered(boolean) through queue*/ public void setDoubleBuffered(final boolean b) { runMapping(new MapVoidAction("setDoubleBuffered") { public void map() { ((JComponent)getSource()).setDoubleBuffered(b); }});} /**Maps JComponent.setMaximumSize(Dimension) through queue*/ public void setMaximumSize(final Dimension dimension) { runMapping(new MapVoidAction("setMaximumSize") { public void map() { ((JComponent)getSource()).setMaximumSize(dimension); }});} /**Maps JComponent.setMinimumSize(Dimension) through queue*/ public void setMinimumSize(final Dimension dimension) { runMapping(new MapVoidAction("setMinimumSize") { public void map() { ((JComponent)getSource()).setMinimumSize(dimension); }});} /**Maps JComponent.setNextFocusableComponent(Component) through queue*/ public void setNextFocusableComponent(final Component component) { runMapping(new MapVoidAction("setNextFocusableComponent") { public void map() { ((JComponent)getSource()).setNextFocusableComponent(component); }});} /**Maps JComponent.setOpaque(boolean) through queue*/ public void setOpaque(final boolean b) { runMapping(new MapVoidAction("setOpaque") { public void map() { ((JComponent)getSource()).setOpaque(b); }});} /**Maps JComponent.setPreferredSize(Dimension) through queue*/ public void setPreferredSize(final Dimension dimension) { runMapping(new MapVoidAction("setPreferredSize") { public void map() { ((JComponent)getSource()).setPreferredSize(dimension); }});} /**Maps JComponent.setRequestFocusEnabled(boolean) through queue*/ public void setRequestFocusEnabled(final boolean b) { runMapping(new MapVoidAction("setRequestFocusEnabled") { public void map() { ((JComponent)getSource()).setRequestFocusEnabled(b); }});} /**Maps JComponent.setToolTipText(String) through queue*/ public void setToolTipText(final String string) { runMapping(new MapVoidAction("setToolTipText") { public void map() { ((JComponent)getSource()).setToolTipText(string); }});} /**Maps JComponent.unregisterKeyboardAction(KeyStroke) through queue*/ public void unregisterKeyboardAction(final KeyStroke keyStroke) { runMapping(new MapVoidAction("unregisterKeyboardAction") { public void map() { ((JComponent)getSource()).unregisterKeyboardAction(keyStroke); }});} /**Maps JComponent.updateUI() through queue*/ public void updateUI() { runMapping(new MapVoidAction("updateUI") { public void map() { ((JComponent)getSource()).updateUI(); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Allows to find component by tooltip. */ public static class JComponentByTipFinder implements ComponentChooser { String label; StringComparator comparator; boolean compareExactly; boolean compareCaseSensitive; /** * Constructs JComponentByTipFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public JComponentByTipFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs JComponentByTipFinder. * @param lb a text pattern */ public JComponentByTipFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JComponent) { if(((JComponent)comp).getToolTipText() != null) { return(comparator.equals(((JComponent)comp).getToolTipText(), label)); } } return(false); } public String getDescription() { return("JComponent with tool tip \"" + label + "\""); } } /** * Checks component type. */ public static class JComponentFinder extends Finder { /** * Constructs JComponentFinder. * @param sf other searching criteria. */ public JComponentFinder(ComponentChooser sf) { super(JComponent.class, sf); } /** * Constructs JComponentFinder. */ public JComponentFinder() { super(JComponent.class); } } class JToolTipWindowFinder implements ComponentChooser { ComponentChooser ppFinder; public JToolTipWindowFinder() { ppFinder = new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp.isShowing() && comp.isVisible() && comp instanceof JToolTip); } public String getDescription() { return("A tool tip"); } }; } public boolean checkComponent(Component comp) { if(comp.isShowing() && comp instanceof Window) { ComponentSearcher cs = new ComponentSearcher((Container)comp); cs.setOutput(JemmyProperties.getCurrentOutput().createErrorOutput()); return(cs.findComponent(ppFinder) != null); } return(false); } public String getDescription() { return("A tool tip window"); } } class JToolTipFinder extends Finder { public JToolTipFinder(ComponentChooser sf) { super(JToolTip.class, sf); } public JToolTipFinder() { super(JToolTip.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JScrollPaneOperator.java0000644000175000017500000007104611245712237024050 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Point; import java.awt.Rectangle; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JViewport; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.plaf.ScrollPaneUI; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.drivers.scrolling.ScrollAdjuster; import org.netbeans.jemmy.util.EmptyVisualizer; /** *

Timeouts used:
* JScrollBarOperator.OneScrollClickTimeout - time for one scroll click
* JScrollBarOperator.WholeScrollTimeout - time for the whole scrolling
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JScrollPaneOperator extends JComponentOperator implements Timeoutable, Outputable { private static int X_POINT_RECT_SIZE = 6; private static int Y_POINT_RECT_SIZE = 4; private Timeouts timeouts; private TestOut output; private JScrollBarOperator hScrollBarOper = null; private JScrollBarOperator vScrollBarOper = null; /** * Constructor. * @param b JScrollPane component. */ public JScrollPaneOperator(JScrollPane b) { super(b); } /** * Constructs a JScrollPaneOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JScrollPaneOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JScrollPane)cont. waitSubComponent(new JScrollPaneFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JScrollPaneOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JScrollPaneOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JScrollPaneOperator(ContainerOperator cont, int index) { this((JScrollPane)waitComponent(cont, new JScrollPaneFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @throws TimeoutExpiredException */ public JScrollPaneOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JScrollPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JScrollPane instance or null if component was not found. */ public static JScrollPane findJScrollPane(Container cont, ComponentChooser chooser, int index) { return((JScrollPane)findComponent(cont, new JScrollPaneFinder(chooser), index)); } /** * Searches 0'th JScrollPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JScrollPane instance or null if component was not found. */ public static JScrollPane findJScrollPane(Container cont, ComponentChooser chooser) { return(findJScrollPane(cont, chooser, 0)); } /** * Searches JScrollPane in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JScrollPane instance or null if component was not found. */ public static JScrollPane findJScrollPane(Container cont, int index) { return(findJScrollPane(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JScrollPane instance"), index)); } /** * Searches 0'th JScrollPane in container. * @param cont Container to search component in. * @return JScrollPane instance or null if component was not found. */ public static JScrollPane findJScrollPane(Container cont) { return(findJScrollPane(cont, 0)); } /** * Searches JScrollPane object which component lies on. * @param comp Component to find JScrollPane under. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JScrollPane instance or null if component was not found. */ public static JScrollPane findJScrollPaneUnder(Component comp, ComponentChooser chooser) { return((JScrollPane)findContainerUnder(comp, new JScrollPaneFinder(chooser))); } /** * Searches JScrollPane object which component lies on. * @param comp Component to find JScrollPane under. * @return JScrollPane instance or null if component was not found. */ public static JScrollPane findJScrollPaneUnder(Component comp) { return(findJScrollPaneUnder(comp, new JScrollPaneFinder())); } /** * Waits JScrollPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JScrollPane instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JScrollPane waitJScrollPane(Container cont, ComponentChooser chooser, int index) { return((JScrollPane)waitComponent(cont, new JScrollPaneFinder(chooser), index)); } /** * Waits 0'th JScrollPane in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JScrollPane instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JScrollPane waitJScrollPane(Container cont, ComponentChooser chooser) { return(waitJScrollPane(cont, chooser, 0)); } /** * Waits JScrollPane in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return JScrollPane instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JScrollPane waitJScrollPane(Container cont, int index) { return(waitJScrollPane(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th JScrollPane instance"), index)); } /** * Waits 0'th JScrollPane in container. * @param cont Container to search component in. * @return JScrollPane instance or null if component was not displayed. * @throws TimeoutExpiredException */ public static JScrollPane waitJScrollPane(Container cont) { return(waitJScrollPane(cont, 0)); } /** * Sets values for both JScrollBars. * @param hValue a value for the horizontal scrollbar. * @param vValue a value for the vertical scrollbar. */ public void setValues(int hValue, int vValue) { initOperators(); hScrollBarOper.setValue(hValue); vScrollBarOper.setValue(vValue); } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } /** * Scrolls horizontal scroll bar. * @param value Value to scroll horizontal scroll bar to. * @throws TimeoutExpiredException */ public void scrollToHorizontalValue(int value) { output.printTrace("Scroll JScrollPane to " + Integer.toString(value) + " horizontal value \n" + toStringSource()); output.printGolden("Scroll JScrollPane to " + Integer.toString(value) + " horizontal value"); initOperators(); makeComponentVisible(); if(hScrollBarOper != null && hScrollBarOper.getSource().isVisible()) { hScrollBarOper.scrollToValue(value); } } /** * Scrolls horizontal scroll bar. * @param proportionalValue Proportional value to scroll horizontal scroll bar to. * @throws TimeoutExpiredException */ public void scrollToHorizontalValue(double proportionalValue) { output.printTrace("Scroll JScrollPane to " + Double.toString(proportionalValue) + " proportional horizontal value \n" + toStringSource()); output.printGolden("Scroll JScrollPane to " + Double.toString(proportionalValue) + " proportional horizontal value"); initOperators(); makeComponentVisible(); if(hScrollBarOper != null && hScrollBarOper.getSource().isVisible()) { hScrollBarOper.scrollToValue(proportionalValue); } } /** * Scrolls vertical scroll bar. * @param value Value to scroll vertical scroll bar to. * @throws TimeoutExpiredException */ public void scrollToVerticalValue(int value) { output.printTrace("Scroll JScrollPane to " + Integer.toString(value) + " vertical value \n" + toStringSource()); output.printGolden("Scroll JScrollPane to " + Integer.toString(value) + " vertical value"); initOperators(); makeComponentVisible(); if(vScrollBarOper != null && vScrollBarOper.getSource().isVisible()) { vScrollBarOper.scrollToValue(value); } } /** * Scrolls vertical scroll bar. * @param proportionalValue Value to scroll vertical scroll bar to. * @throws TimeoutExpiredException */ public void scrollToVerticalValue(double proportionalValue) { output.printTrace("Scroll JScrollPane to " + Double.toString(proportionalValue) + " proportional vertical value \n" + toStringSource()); output.printGolden("Scroll JScrollPane to " + Double.toString(proportionalValue) + " proportional vertical value"); initOperators(); makeComponentVisible(); if(vScrollBarOper != null && vScrollBarOper.getSource().isVisible()) { vScrollBarOper.scrollToValue(proportionalValue); } } /** * Scrolls both scroll bars. * @param valueX Value to scroll horizontal scroll bar to. * @param valueY Value to scroll vertical scroll bar to. * @throws TimeoutExpiredException */ public void scrollToValues(int valueX, int valueY) { scrollToVerticalValue(valueX); scrollToHorizontalValue(valueX); } /** * Scrolls both scroll bars. * @param proportionalValueX Value to scroll horizontal scroll bar to. * @param proportionalValueY Value to scroll vertical scroll bar to. * @throws TimeoutExpiredException */ public void scrollToValues(double proportionalValueX, double proportionalValueY) { scrollToVerticalValue(proportionalValueX); scrollToHorizontalValue(proportionalValueY); } /** * Scrolls pane to top. * @throws TimeoutExpiredException */ public void scrollToTop() { output.printTrace("Scroll JScrollPane to top\n" + toStringSource()); output.printGolden("Scroll JScrollPane to top"); initOperators(); makeComponentVisible(); if(vScrollBarOper != null && vScrollBarOper.getSource().isVisible()) { vScrollBarOper.scrollToMinimum(); } } /** * Scrolls pane to bottom. * @throws TimeoutExpiredException */ public void scrollToBottom() { output.printTrace("Scroll JScrollPane to bottom\n" + toStringSource()); output.printGolden("Scroll JScrollPane to bottom"); initOperators(); makeComponentVisible(); if(vScrollBarOper != null && vScrollBarOper.getSource().isVisible()) { vScrollBarOper.scrollToMaximum(); } } /** * Scrolls pane to left. * @throws TimeoutExpiredException */ public void scrollToLeft() { output.printTrace("Scroll JScrollPane to left\n" + toStringSource()); output.printGolden("Scroll JScrollPane to left"); initOperators(); makeComponentVisible(); if(hScrollBarOper != null && hScrollBarOper.getSource().isVisible()) { hScrollBarOper.scrollToMinimum(); } } /** * Scrolls pane to right. * @throws TimeoutExpiredException */ public void scrollToRight() { output.printTrace("Scroll JScrollPane to right\n" + toStringSource()); output.printGolden("Scroll JScrollPane to right"); initOperators(); makeComponentVisible(); if(hScrollBarOper != null && hScrollBarOper.getSource().isVisible()) { hScrollBarOper.scrollToMaximum(); } } /** * Scrolls pane to rectangle of a component. * @param comp a subcomponent defining coordinate system. * @param x coordinate * @param y coordinate * @param width rectangle width * @param height rectangle height * @throws TimeoutExpiredException */ public void scrollToComponentRectangle(Component comp, int x, int y, int width, int height) { initOperators(); makeComponentVisible(); if(hScrollBarOper != null && hScrollBarOper.getSource().isVisible()) { hScrollBarOper.scrollTo(new ComponentRectChecker(comp, x, y, width, height, JScrollBar.HORIZONTAL)); } if(vScrollBarOper != null && vScrollBarOper.getSource().isVisible()) { vScrollBarOper.scrollTo(new ComponentRectChecker(comp, x, y, width, height, JScrollBar.VERTICAL)); } } /** * Scrolls pane to point. * @param comp a subcomponent defining coordinate system. * @param x coordinate * @param y coordinate * @throws TimeoutExpiredException */ public void scrollToComponentPoint(Component comp, int x, int y) { scrollToComponentRectangle(comp, x - X_POINT_RECT_SIZE, y - Y_POINT_RECT_SIZE, 2 * X_POINT_RECT_SIZE, 2 * Y_POINT_RECT_SIZE); } /** * Scrolls pane to component on this pane. * Component should lay on the JScrollPane view. * @param comp Component to scroll to. * @throws TimeoutExpiredException */ public void scrollToComponent(final Component comp) { String componentToString = (String)runMapping( new Operator.MapAction("comp.toString()") { public Object map() { return comp.toString(); } } ); output.printTrace("Scroll JScrollPane " + toStringSource() + "\nto component " + componentToString); output.printGolden("Scroll JScrollPane to " + comp.getClass().getName() + " component."); scrollToComponentRectangle(comp, 0, 0, comp.getWidth(), comp.getHeight()); } /** * Returns operator used for horizontal scrollbar. * @return an operator for the horizontal scrollbar. */ public JScrollBarOperator getHScrollBarOperator() { initOperators(); return(hScrollBarOper); } /** * Returns operator used for vertical scrollbar. * @return an operator for the vertical scrollbar. */ public JScrollBarOperator getVScrollBarOperator() { initOperators(); return(vScrollBarOper); } /** * Checks if component's rectangle is inside view port (no scrolling necessary). * @param comp a subcomponent defining coordinate system. * @param x coordinate * @param y coordinate * @param width rectangle width * @param height rectangle height * @return true if pointed subcomponent rectangle is inside the scrolling area. */ public boolean checkInside(Component comp, int x, int y, int width, int height) { Component view = getViewport().getView(); Point toPoint = SwingUtilities. convertPoint(comp, x, y, getViewport().getView()); initOperators(); if(hScrollBarOper != null && hScrollBarOper.getSource().isVisible()) { if(toPoint.x < hScrollBarOper.getValue()) { return(false); } if(comp.getWidth() > view.getWidth()) { return(toPoint.x > 0); } else { return(toPoint.x + comp.getWidth() > hScrollBarOper.getValue() + view.getWidth()); } } if(vScrollBarOper != null && vScrollBarOper.getSource().isVisible()) { if(toPoint.y < vScrollBarOper.getValue()) { return(false); } if(comp.getHeight() > view.getHeight()) { return(toPoint.y > 0); } else { return(toPoint.y + comp.getHeight() > vScrollBarOper.getValue() + view.getHeight()); } } return(true); } /** * Checks if component is inside view port (no scrolling necessary). * @param comp a subcomponent * @return true if pointed subcomponent is inside the scrolling area. */ public boolean checkInside(Component comp) { return(checkInside(comp, 0, 0, comp.getWidth(), comp.getHeight())); } //////////////////////////////////////////////////////// //Mapping // /**Maps JScrollPane.createHorizontalScrollBar() through queue*/ public JScrollBar createHorizontalScrollBar() { return((JScrollBar)runMapping(new MapAction("createHorizontalScrollBar") { public Object map() { return(((JScrollPane)getSource()).createHorizontalScrollBar()); }}));} /**Maps JScrollPane.createVerticalScrollBar() through queue*/ public JScrollBar createVerticalScrollBar() { return((JScrollBar)runMapping(new MapAction("createVerticalScrollBar") { public Object map() { return(((JScrollPane)getSource()).createVerticalScrollBar()); }}));} /**Maps JScrollPane.getColumnHeader() through queue*/ public JViewport getColumnHeader() { return((JViewport)runMapping(new MapAction("getColumnHeader") { public Object map() { return(((JScrollPane)getSource()).getColumnHeader()); }}));} /**Maps JScrollPane.getCorner(String) through queue*/ public Component getCorner(final String string) { return((Component)runMapping(new MapAction("getCorner") { public Object map() { return(((JScrollPane)getSource()).getCorner(string)); }}));} /**Maps JScrollPane.getHorizontalScrollBar() through queue*/ public JScrollBar getHorizontalScrollBar() { return((JScrollBar)runMapping(new MapAction("getHorizontalScrollBar") { public Object map() { return(((JScrollPane)getSource()).getHorizontalScrollBar()); }}));} /**Maps JScrollPane.getHorizontalScrollBarPolicy() through queue*/ public int getHorizontalScrollBarPolicy() { return(runMapping(new MapIntegerAction("getHorizontalScrollBarPolicy") { public int map() { return(((JScrollPane)getSource()).getHorizontalScrollBarPolicy()); }}));} /**Maps JScrollPane.getRowHeader() through queue*/ public JViewport getRowHeader() { return((JViewport)runMapping(new MapAction("getRowHeader") { public Object map() { return(((JScrollPane)getSource()).getRowHeader()); }}));} /**Maps JScrollPane.getUI() through queue*/ public ScrollPaneUI getUI() { return((ScrollPaneUI)runMapping(new MapAction("getUI") { public Object map() { return(((JScrollPane)getSource()).getUI()); }}));} /**Maps JScrollPane.getVerticalScrollBar() through queue*/ public JScrollBar getVerticalScrollBar() { return((JScrollBar)runMapping(new MapAction("getVerticalScrollBar") { public Object map() { return(((JScrollPane)getSource()).getVerticalScrollBar()); }}));} /**Maps JScrollPane.getVerticalScrollBarPolicy() through queue*/ public int getVerticalScrollBarPolicy() { return(runMapping(new MapIntegerAction("getVerticalScrollBarPolicy") { public int map() { return(((JScrollPane)getSource()).getVerticalScrollBarPolicy()); }}));} /**Maps JScrollPane.getViewport() through queue*/ public JViewport getViewport() { return((JViewport)runMapping(new MapAction("getViewport") { public Object map() { return(((JScrollPane)getSource()).getViewport()); }}));} /**Maps JScrollPane.getViewportBorder() through queue*/ public Border getViewportBorder() { return((Border)runMapping(new MapAction("getViewportBorder") { public Object map() { return(((JScrollPane)getSource()).getViewportBorder()); }}));} /**Maps JScrollPane.getViewportBorderBounds() through queue*/ public Rectangle getViewportBorderBounds() { return((Rectangle)runMapping(new MapAction("getViewportBorderBounds") { public Object map() { return(((JScrollPane)getSource()).getViewportBorderBounds()); }}));} /**Maps JScrollPane.setColumnHeader(JViewport) through queue*/ public void setColumnHeader(final JViewport jViewport) { runMapping(new MapVoidAction("setColumnHeader") { public void map() { ((JScrollPane)getSource()).setColumnHeader(jViewport); }});} /**Maps JScrollPane.setColumnHeaderView(Component) through queue*/ public void setColumnHeaderView(final Component component) { runMapping(new MapVoidAction("setColumnHeaderView") { public void map() { ((JScrollPane)getSource()).setColumnHeaderView(component); }});} /**Maps JScrollPane.setCorner(String, Component) through queue*/ public void setCorner(final String string, final Component component) { runMapping(new MapVoidAction("setCorner") { public void map() { ((JScrollPane)getSource()).setCorner(string, component); }});} /**Maps JScrollPane.setHorizontalScrollBar(JScrollBar) through queue*/ public void setHorizontalScrollBar(final JScrollBar jScrollBar) { runMapping(new MapVoidAction("setHorizontalScrollBar") { public void map() { ((JScrollPane)getSource()).setHorizontalScrollBar(jScrollBar); }});} /**Maps JScrollPane.setHorizontalScrollBarPolicy(int) through queue*/ public void setHorizontalScrollBarPolicy(final int i) { runMapping(new MapVoidAction("setHorizontalScrollBarPolicy") { public void map() { ((JScrollPane)getSource()).setHorizontalScrollBarPolicy(i); }});} /**Maps JScrollPane.setRowHeader(JViewport) through queue*/ public void setRowHeader(final JViewport jViewport) { runMapping(new MapVoidAction("setRowHeader") { public void map() { ((JScrollPane)getSource()).setRowHeader(jViewport); }});} /**Maps JScrollPane.setRowHeaderView(Component) through queue*/ public void setRowHeaderView(final Component component) { runMapping(new MapVoidAction("setRowHeaderView") { public void map() { ((JScrollPane)getSource()).setRowHeaderView(component); }});} /**Maps JScrollPane.setUI(ScrollPaneUI) through queue*/ public void setUI(final ScrollPaneUI scrollPaneUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JScrollPane)getSource()).setUI(scrollPaneUI); }});} /**Maps JScrollPane.setVerticalScrollBar(JScrollBar) through queue*/ public void setVerticalScrollBar(final JScrollBar jScrollBar) { runMapping(new MapVoidAction("setVerticalScrollBar") { public void map() { ((JScrollPane)getSource()).setVerticalScrollBar(jScrollBar); }});} /**Maps JScrollPane.setVerticalScrollBarPolicy(int) through queue*/ public void setVerticalScrollBarPolicy(final int i) { runMapping(new MapVoidAction("setVerticalScrollBarPolicy") { public void map() { ((JScrollPane)getSource()).setVerticalScrollBarPolicy(i); }});} /**Maps JScrollPane.setViewport(JViewport) through queue*/ public void setViewport(final JViewport jViewport) { runMapping(new MapVoidAction("setViewport") { public void map() { ((JScrollPane)getSource()).setViewport(jViewport); }});} /**Maps JScrollPane.setViewportBorder(Border) through queue*/ public void setViewportBorder(final Border border) { runMapping(new MapVoidAction("setViewportBorder") { public void map() { ((JScrollPane)getSource()).setViewportBorder(border); }});} /**Maps JScrollPane.setViewportView(Component) through queue*/ public void setViewportView(final Component component) { runMapping(new MapVoidAction("setViewportView") { public void map() { ((JScrollPane)getSource()).setViewportView(component); }});} //End of mapping // //////////////////////////////////////////////////////// private void initOperators() { if(hScrollBarOper == null && getHorizontalScrollBar() != null && getHorizontalScrollBar().isVisible()) { hScrollBarOper = new JScrollBarOperator(getHorizontalScrollBar()); hScrollBarOper.copyEnvironment(this); hScrollBarOper.setVisualizer(new EmptyVisualizer()); } if(vScrollBarOper == null && getVerticalScrollBar() != null && getVerticalScrollBar().isVisible()) { vScrollBarOper = new JScrollBarOperator(getVerticalScrollBar()); vScrollBarOper.copyEnvironment(this); vScrollBarOper.setVisualizer(new EmptyVisualizer()); } } private class ComponentRectChecker implements JScrollBarOperator.ScrollChecker { Component comp; int x; int y; int width; int height; int orientation; public ComponentRectChecker(Component comp, int x, int y, int width, int height, int orientation) { this.comp = comp; this.x = x; this.y = y; this.width = width; this.height = height; this.orientation = orientation; } public int getScrollDirection(JScrollBarOperator oper) { Point toPoint = SwingUtilities. convertPoint(comp, x, y, getViewport().getView()); int to = (orientation == JScrollBar.HORIZONTAL) ? toPoint.x : toPoint.y; int ln = (orientation == JScrollBar.HORIZONTAL) ? width : height; int lv = (orientation == JScrollBar.HORIZONTAL) ? getViewport().getWidth() : getViewport().getHeight(); int vl = oper.getValue(); if(to < vl) { return(ScrollAdjuster.DECREASE_SCROLL_DIRECTION); } else if((to + ln - 1) > (vl + lv) && to > vl) { return(ScrollAdjuster.INCREASE_SCROLL_DIRECTION); } else { return(ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION); } } public String getDescription() { return(""); } } /** * Checks component type. */ public static class JScrollPaneFinder extends Finder { /** * Constructs JScrollPaneFinder. * @param sf other searching criteria. */ public JScrollPaneFinder(ComponentChooser sf) { super(JScrollPane.class, sf); } /** * Constructs JScrollPaneFinder. */ public JScrollPaneFinder() { super(JScrollPane.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/ContainerOperator.java0000644000175000017500000004463311245712447023623 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Graphics; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.Point; import java.awt.event.ContainerListener; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.Waitable; import org.netbeans.jemmy.Waiter; /** *

Timeouts used:
* ComponentOperator.WaitComponentTimeout - time to wait container displayed
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class ContainerOperator extends ComponentOperator implements Timeoutable, Outputable { private final static long WAIT_SUBCOMPONENT_TIMEOUT = 60000; private ComponentSearcher searcher; private Timeouts timeouts; private TestOut output; /** * Constructor. * @param b Container component. */ public ContainerOperator(Container b) { super(b); searcher = new ComponentSearcher(b); searcher.setOutput(TestOut.getNullOutput()); } /** * Constructs a ContainerOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public ContainerOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((Container)cont. waitSubComponent(new ContainerFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a ContainerOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. */ public ContainerOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @param index Ordinal component index. * @throws TimeoutExpiredException */ public ContainerOperator(ContainerOperator cont, int index) { this((Container)waitComponent(cont, new ContainerFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator pointing a container to search component in. * @throws TimeoutExpiredException */ public ContainerOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches Container in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return Container instance or null if component was not found. */ public static Container findContainer(Container cont, ComponentChooser chooser, int index) { return((Container)findComponent(cont, new ContainerFinder(chooser), index)); } /** * Searches 0'th Container in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return Container instance or null if component was not found. */ public static Container findContainer(Container cont, ComponentChooser chooser) { return(findContainer(cont, chooser, 0)); } /** * Searches Container in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return Container instance or null if component was not found. */ public static Container findContainer(Container cont, int index) { return(findContainer(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th Container instance"), index)); } /** * Searches 0'th Container in container. * @param cont Container to search component in. * @return Container instance or null if component was not found. */ public static Container findContainer(Container cont) { return(findContainer(cont, 0)); } /** * Searches Container object which component lies on. * @param comp Component to find Container under. * @param chooser a chooser specifying searching criteria. * @return Container instance or null if component was not found. */ public static Container findContainerUnder(Component comp, ComponentChooser chooser) { return((Container)new ComponentOperator(comp). getContainer(new ContainerFinder(chooser))); } /** * Searches Container object which component lies on. * @param comp Component to find Container under. * @return Container instance or null if component was not found. */ public static Container findContainerUnder(Component comp) { return(findContainerUnder(comp, ComponentSearcher.getTrueChooser("Container"))); } /** * Waits Container in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return Container instance. * @throws TimeoutExpiredException */ public static Container waitContainer(Container cont, ComponentChooser chooser, int index) { return((Container)waitComponent(cont, new ContainerFinder(chooser), index)); } /** * Waits 0'th Container in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return Container instance. * @throws TimeoutExpiredException */ public static Container waitContainer(Container cont, ComponentChooser chooser) { return(waitContainer(cont, chooser, 0)); } /** * Waits Container in container. * @param cont Container to search component in. * @param index Ordinal component index. * @return Container instance. * @throws TimeoutExpiredException */ public static Container waitContainer(Container cont, int index) { return(waitContainer(cont, ComponentSearcher.getTrueChooser(Integer.toString(index) + "'th Container instance"), index)); } /** * Waits 0'th Container in container. * @param cont Container to search component in. * @return Container instance. * @throws TimeoutExpiredException */ public static Container waitContainer(Container cont) { return(waitContainer(cont, 0)); } static { Timeouts.initDefault("ComponentOperator.WaitComponentTimeout", WAIT_SUBCOMPONENT_TIMEOUT); } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } /** * Searches for a subcomponent. * @param chooser a chooser specifying searching criteria. * @param index Ordinal component index. * @return Component instance. */ public Component findSubComponent(ComponentChooser chooser, int index) { getOutput().printLine("Looking for \"" + chooser.getDescription() + "\" subcomponent"); return(searcher.findComponent(chooser, index)); } /** * Searches for a subcomponent. * @param chooser a chooser specifying searching criteria. * @return Component instance. */ public Component findSubComponent(ComponentChooser chooser) { return(findSubComponent(chooser, 0)); } /** * Waits for a subcomponent. * @param chooser a chooser specifying searching criteria. * @param index Ordinal component index. * @return Component instance. */ public Component waitSubComponent(final ComponentChooser chooser, final int index) { getOutput().printLine("Waiting for \"" + chooser.getDescription() + "\" subcomponent"); final ComponentSearcher searcher = new ComponentSearcher((Container)getSource()); searcher.setOutput(getOutput().createErrorOutput()); Waiter waiter = new Waiter(new Waitable() { public Object actionProduced(Object obj) { return(searcher.findComponent(chooser, index)); } public String getDescription() { return("Wait for \"" + chooser.getDescription() + "\" subcomponent to be displayed"); } }); waiter.setTimeoutsToCloneOf(getTimeouts(), "ComponentOperator.WaitComponentTimeout"); waiter.setOutput(getOutput()); try { return((Component)waiter.waitAction(null)); } catch (InterruptedException e) { throw(new JemmyException("Waiting for \"" + chooser.getDescription() + "\" component has been interrupted", e)); } } /** * Waits for a subcomponent. * @param chooser a chooser specifying searching criteria. * @return Component instance. */ public Component waitSubComponent(ComponentChooser chooser) { return(waitSubComponent(chooser, 0)); } /** * Waits for a subcomponent and creates an operator. * @param chooser a chooser specifying searching criteria. * @param index Ordinal component index. * @return Component instance. */ public ComponentOperator createSubOperator(ComponentChooser chooser, int index) { return(createOperator(waitSubComponent(chooser, index))); } /** * Waits for a subcomponent and creates an operator. * @param chooser a chooser specifying searching criteria. * @return Component instance. */ public ComponentOperator createSubOperator(ComponentChooser chooser) { return(createSubOperator(chooser, 0)); } //////////////////////////////////////////////////////// //Mapping // /**Maps Container.add(Component) through queue*/ public Component add(final Component component) { return((Component)runMapping(new MapAction("add") { public Object map() { return(((Container)getSource()).add(component)); }}));} /**Maps Container.add(Component, int) through queue*/ public Component add(final Component component, final int i) { return((Component)runMapping(new MapAction("add") { public Object map() { return(((Container)getSource()).add(component, i)); }}));} /**Maps Container.add(Component, Object) through queue*/ public void add(final Component component, final Object object) { runMapping(new MapVoidAction("add") { public void map() { ((Container)getSource()).add(component, object); }});} /**Maps Container.add(Component, Object, int) through queue*/ public void add(final Component component, final Object object, final int i) { runMapping(new MapVoidAction("add") { public void map() { ((Container)getSource()).add(component, object, i); }});} /**Maps Container.add(String, Component) through queue*/ public Component add(final String string, final Component component) { return((Component)runMapping(new MapAction("add") { public Object map() { return(((Container)getSource()).add(string, component)); }}));} /**Maps Container.addContainerListener(ContainerListener) through queue*/ public void addContainerListener(final ContainerListener containerListener) { runMapping(new MapVoidAction("addContainerListener") { public void map() { ((Container)getSource()).addContainerListener(containerListener); }});} /**Maps Container.findComponentAt(int, int) through queue*/ public Component findComponentAt(final int i, final int i1) { return((Component)runMapping(new MapAction("findComponentAt") { public Object map() { return(((Container)getSource()).findComponentAt(i, i1)); }}));} /**Maps Container.findComponentAt(Point) through queue*/ public Component findComponentAt(final Point point) { return((Component)runMapping(new MapAction("findComponentAt") { public Object map() { return(((Container)getSource()).findComponentAt(point)); }}));} /**Maps Container.getComponent(int) through queue*/ public Component getComponent(final int i) { return((Component)runMapping(new MapAction("getComponent") { public Object map() { return(((Container)getSource()).getComponent(i)); }}));} /**Maps Container.getComponentCount() through queue*/ public int getComponentCount() { return(runMapping(new MapIntegerAction("getComponentCount") { public int map() { return(((Container)getSource()).getComponentCount()); }}));} /**Maps Container.getComponents() through queue*/ public Component[] getComponents() { return((Component[])runMapping(new MapAction("getComponents") { public Object map() { return(((Container)getSource()).getComponents()); }}));} /**Maps Container.getInsets() through queue*/ public Insets getInsets() { return((Insets)runMapping(new MapAction("getInsets") { public Object map() { return(((Container)getSource()).getInsets()); }}));} /**Maps Container.getLayout() through queue*/ public LayoutManager getLayout() { return((LayoutManager)runMapping(new MapAction("getLayout") { public Object map() { return(((Container)getSource()).getLayout()); }}));} /**Maps Container.isAncestorOf(Component) through queue*/ public boolean isAncestorOf(final Component component) { return(runMapping(new MapBooleanAction("isAncestorOf") { public boolean map() { return(((Container)getSource()).isAncestorOf(component)); }}));} /**Maps Container.paintComponents(Graphics) through queue*/ public void paintComponents(final Graphics graphics) { runMapping(new MapVoidAction("paintComponents") { public void map() { ((Container)getSource()).paintComponents(graphics); }});} /**Maps Container.printComponents(Graphics) through queue*/ public void printComponents(final Graphics graphics) { runMapping(new MapVoidAction("printComponents") { public void map() { ((Container)getSource()).printComponents(graphics); }});} /**Maps Container.remove(int) through queue*/ public void remove(final int i) { runMapping(new MapVoidAction("remove") { public void map() { ((Container)getSource()).remove(i); }});} /**Maps Container.remove(Component) through queue*/ public void remove(final Component component) { runMapping(new MapVoidAction("remove") { public void map() { ((Container)getSource()).remove(component); }});} /**Maps Container.removeAll() through queue*/ public void removeAll() { runMapping(new MapVoidAction("removeAll") { public void map() { ((Container)getSource()).removeAll(); }});} /**Maps Container.removeContainerListener(ContainerListener) through queue*/ public void removeContainerListener(final ContainerListener containerListener) { runMapping(new MapVoidAction("removeContainerListener") { public void map() { ((Container)getSource()).removeContainerListener(containerListener); }});} /**Maps Container.setLayout(LayoutManager) through queue*/ public void setLayout(final LayoutManager layoutManager) { runMapping(new MapVoidAction("setLayout") { public void map() { ((Container)getSource()).setLayout(layoutManager); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Checks component type. */ public static class ContainerFinder extends Finder { /** * Constructs ContainerFinder. * @param sf other searching criteria. */ public ContainerFinder(ComponentChooser sf) { super(Container.class, sf); } /** * Constructs ContainerFinder. */ public ContainerFinder() { super(Container.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JCheckBoxMenuItemOperator.java0000644000175000017500000001740011245712237025132 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import javax.swing.JCheckBoxMenuItem; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.JemmyProperties; /** * *

Timeouts used:
* JMenuItemOperator.PushMenuTimeout - time between button pressing and releasing
* ComponentOperator.WaitComponentTimeout - time to wait button displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait button enabled
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JCheckBoxMenuItemOperator extends JMenuItemOperator { /** * Constructor. * @param item a component. */ public JCheckBoxMenuItemOperator(JCheckBoxMenuItem item) { super(item); setTimeouts(JemmyProperties.getProperties().getTimeouts()); setOutput(JemmyProperties.getProperties().getOutput()); } /** * Constructs a JCheckBoxMenuItemOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JCheckBoxMenuItemOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JCheckBoxMenuItem)cont. waitSubComponent(new JCheckBoxMenuItemFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JCheckBoxMenuItemOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JCheckBoxMenuItemOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public JCheckBoxMenuItemOperator(ContainerOperator cont, String text, int index) { this((JCheckBoxMenuItem)waitComponent(cont, new JCheckBoxMenuItemByLabelFinder(text, cont.getComparator()), index)); setTimeouts(cont.getTimeouts()); setOutput(cont.getOutput()); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public JCheckBoxMenuItemOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. */ public JCheckBoxMenuItemOperator(ContainerOperator cont, int index) { this((JCheckBoxMenuItem) waitComponent(cont, new JCheckBoxMenuItemFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container */ public JCheckBoxMenuItemOperator(ContainerOperator cont) { this(cont, 0); } //////////////////////////////////////////////////////// //Mapping // /**Maps JCheckBoxMenuItem.getState() through queue*/ public boolean getState() { return(runMapping(new MapBooleanAction("getState") { public boolean map() { return(((JCheckBoxMenuItem)getSource()).getState()); }}));} /**Maps JCheckBoxMenuItem.setState(boolean) through queue*/ public void setState(final boolean b) { runMapping(new MapVoidAction("setState") { public void map() { ((JCheckBoxMenuItem)getSource()).setState(b); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Allows to find component by text. */ public static class JCheckBoxMenuItemByLabelFinder implements ComponentChooser { String label; StringComparator comparator; /** * Constructs JCheckBoxMenuItemByLabelFinder. * @param lb a text pattern * @param comparator specifies string comparision algorithm. */ public JCheckBoxMenuItemByLabelFinder(String lb, StringComparator comparator) { label = lb; this.comparator = comparator; } /** * Constructs JCheckBoxMenuItemByLabelFinder. * @param lb a text pattern */ public JCheckBoxMenuItemByLabelFinder(String lb) { this(lb, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JCheckBoxMenuItem) { if(((JCheckBoxMenuItem)comp).getText() != null) { return(comparator.equals(((JCheckBoxMenuItem)comp).getText(), label)); } } return(false); } public String getDescription() { return("JCheckBoxMenuItem with text \"" + label + "\""); } } /** * Checks component type. */ public static class JCheckBoxMenuItemFinder extends Finder { /** * Constructs JCheckBoxMenuItemFinder. * @param sf other searching criteria. */ public JCheckBoxMenuItemFinder(ComponentChooser sf) { super(JCheckBoxMenuItem.class, sf); } /** * Constructs JCheckBoxMenuItemFinder. */ public JCheckBoxMenuItemFinder() { super(JCheckBoxMenuItem.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JDialogOperator.java0000644000175000017500000006014711245712237023205 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.Window; import javax.accessibility.AccessibleContext; import javax.swing.JDialog; import javax.swing.JLayeredPane; import javax.swing.JMenuBar; import javax.swing.JRootPane; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.DialogWaiter; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeouts; /** *

Timeouts used:
* DialogWaiter.WaitDialogTimeout - time to wait dialog displayed
* DialogWaiter.AfterDialogTimeout - time to sleep after dialog has been dispayed
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JDialogOperator extends DialogOperator { /** * Constructor. * @param w a component */ public JDialogOperator(JDialog w) { super(w); } /** * Constructs a JDialogOperator object. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @param env an operator to copy environment from. */ public JDialogOperator(ComponentChooser chooser, int index, Operator env) { this(waitJDialog(new JDialogFinder(chooser), index, env.getTimeouts(), env.getOutput())); copyEnvironment(env); } /** * Constructs a JDialogOperator object. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JDialogOperator(ComponentChooser chooser, int index) { this(chooser, index, Operator.getEnvironmentOperator()); } /** * Constructs a JDialogOperator object. * @param chooser a component chooser specifying searching criteria. */ public JDialogOperator(ComponentChooser chooser) { this(chooser, 0); } /** * Constructs a JDialogOperator object. * @param owner window - owner * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JDialogOperator(WindowOperator owner, ComponentChooser chooser, int index) { this((JDialog)owner. waitSubWindow(new JDialogFinder(chooser), index)); copyEnvironment(owner); } /** * Constructs a JDialogOperator object. * @param owner window - owner * @param chooser a component chooser specifying searching criteria. */ public JDialogOperator(WindowOperator owner, ComponentChooser chooser) { this(owner, chooser, 0); } /** * Constructor. * Waits for the dialog with "title" subtitle. * Uses owner's timeout and output for waiting and to init operator. * @param owner Operator pointing to a window owner. * @param title The desired title. * @param index Ordinal index. The first dialog has index 0. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public JDialogOperator(WindowOperator owner, String title, int index) { this(waitJDialog(owner, new JDialogFinder(new DialogByTitleFinder(title, owner.getComparator())), index)); copyEnvironment(owner); } /** * Constructor. * Waits for the dialog with "title" subtitle. * Uses owner's timeout and output for waiting and to init operator. * @param owner Operator pointing to a window owner. * @param title The desired title. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public JDialogOperator(WindowOperator owner, String title) { this(owner, title, 0); } /** * Constructor. * Waits for the index'th dialog between owner's children. * Uses owner'th timeout and output for waiting and to init operator. * @param owner Operator pointing to a window owner. * @param index Ordinal component index. * */ public JDialogOperator(WindowOperator owner, int index) { this((JDialog) waitJDialog(owner, new JDialogFinder(), index)); copyEnvironment(owner); } /** * Constructor. * Waits for the first dialog between owner's children. * Uses owner'th timeout and output for waiting and to init operator. * @param owner Operator pointing to a window owner. * */ public JDialogOperator(WindowOperator owner) { this(owner, 0); } /** * Constructor. * Waits for the dialog with "title" subtitle. * Constructor can be used in complicated cases when * output or timeouts should differ from default. * @param title a window title * @param index Ordinal component index. * @param env an operator to copy environment from. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public JDialogOperator(String title, int index, Operator env) { this(new JDialogFinder(new DialogByTitleFinder(title, env.getComparator())), index, env); } /** * Constructor. * Waits for the dialog with "title" subtitle. * Uses current timeouts and output values. * @param title a window title * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see JemmyProperties#getCurrentTimeouts() * @see JemmyProperties#getCurrentOutput() * */ public JDialogOperator(String title, int index) { this(title, index, ComponentOperator.getEnvironmentOperator()); } /** * Constructor. * Waits for the dialog with "title" subtitle. * Uses current timeouts and output values. * @param title a window title * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @see JemmyProperties#getCurrentTimeouts() * @see JemmyProperties#getCurrentOutput() * */ public JDialogOperator(String title) { this(title, 0); } /** * Constructor. * Waits for the index'th dialog. * Uses current timeout and output for waiting and to init operator. * @param index Ordinal component index. * */ public JDialogOperator(int index) { this((JDialog) waitJDialog(new JDialogFinder(), index, ComponentOperator.getEnvironmentOperator().getTimeouts(), ComponentOperator.getEnvironmentOperator().getOutput())); copyEnvironment(ComponentOperator.getEnvironmentOperator()); } /** * Constructor. * Waits for the first dialog. * Uses current timeout and output for waiting and to init operator. * */ public JDialogOperator() { this(0); } /** * Searches an index'th dialog. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @return JDialog instance or null if component was not found. */ public static JDialog findJDialog(ComponentChooser chooser, int index) { return((JDialog)DialogWaiter.getDialog(new JDialogFinder(chooser), index)); } /** * Searches a dialog. * @param chooser a component chooser specifying searching criteria. * @return JDialog instance or null if component was not found. */ public static JDialog findJDialog(ComponentChooser chooser) { return(findJDialog(chooser, 0)); } /** * Searches an index'th dialog by title. * @param title Dialog title * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @param index an index between appropriate ones. * @return JDialog instance or null if component was not found. */ public static JDialog findJDialog(String title, boolean ce, boolean cc, int index) { return((JDialog)DialogWaiter. getDialog(new JDialogFinder(new DialogByTitleFinder(title, new DefaultStringComparator(ce, cc))), index)); } /** * Searches a dialog by title. * @param title Dialog title * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @return JDialog instance or null if component was not found. */ public static JDialog findJDialog(String title, boolean ce, boolean cc) { return(findJDialog(title, ce, cc, 0)); } /** * Searches an index'th dialog between owner's owned windows. * @param owner Window - dialog owner. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @return JDialog instance or null if component was not found. */ public static JDialog findJDialog(Window owner, ComponentChooser chooser, int index) { return((JDialog)DialogWaiter.getDialog(owner, new JDialogFinder(chooser), index)); } /** * Searches a dialog between owner's owned windows. * @param owner Window - dialog owner. * @param chooser a component chooser specifying searching criteria. * @return JDialog instance or null if component was not found. */ public static JDialog findJDialog(Window owner, ComponentChooser chooser) { return(findJDialog(owner, chooser, 0)); } /** * Searches an index'th dialog by title between owner's owned windows. * @param owner Window - dialog owner. * @param title Dialog title * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @param index an index between appropriate ones. * @return JDialog instance or null if component was not found. */ public static JDialog findJDialog(Window owner, String title, boolean ce, boolean cc, int index) { return((JDialog)DialogWaiter. getDialog(owner, new JDialogFinder(new DialogByTitleFinder(title, new DefaultStringComparator(ce, cc))), index)); } /** * Searches a dialog by title between owner's owned windows. * @param owner Window - dialog owner. * @param title Dialog title * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @return JDialog instance or null if component was not found. */ public static JDialog findJDialog(Window owner, String title, boolean ce, boolean cc) { return(findJDialog(owner, title, ce, cc, 0)); } /** * Waits an index'th dialog. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @return JDialog instance or null if component was not found. * */ public static JDialog waitJDialog(ComponentChooser chooser, int index) { return(waitJDialog(chooser, index, JemmyProperties.getCurrentTimeouts(), JemmyProperties.getCurrentOutput())); } /** * Waits a dialog. * @param chooser a component chooser specifying searching criteria. * @return JDialog instance or null if component was not found. * */ public static JDialog waitJDialog(ComponentChooser chooser) { return(waitJDialog(chooser, 0)); } /** * Waits an index'th dialog by title. * @param title Dialog title * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @param index an index between appropriate ones. * @return JDialog instance or null if component was not found. * */ public static JDialog waitJDialog(String title, boolean ce, boolean cc, int index) { return(waitJDialog(new JDialogFinder(new DialogByTitleFinder(title, new DefaultStringComparator(ce, cc))), index)); } /** * Waits a dialog by title. * @param title Dialog title * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @return JDialog instance or null if component was not found. * */ public static JDialog waitJDialog(String title, boolean ce, boolean cc) { return(waitJDialog(title, ce, cc, 0)); } /** * Waits an index'th dialog between owner's owned windows. * @param owner Window - dialog owner. * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. * @return JDialog instance or null if component was not found. * */ public static JDialog waitJDialog(Window owner, ComponentChooser chooser, int index) { return(waitJDialog(owner, chooser, index, JemmyProperties.getCurrentTimeouts(), JemmyProperties.getCurrentOutput())); } /** * Waits a dialog between owner's owned windows. * @param owner Window - dialog owner. * @param chooser a component chooser specifying searching criteria. * @return JDialog instance or null if component was not found. * */ public static JDialog waitJDialog(Window owner, ComponentChooser chooser) { return(waitJDialog(owner, chooser, 0)); } /** * Waits an index'th dialog by title between owner's owned windows. * @param owner Window - dialog owner. * @param title Dialog title * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @param index an index between appropriate ones. * @return JDialog instance or null if component was not found. * */ public static JDialog waitJDialog(Window owner, String title, boolean ce, boolean cc, int index) { return(waitJDialog(owner, new JDialogFinder(new DialogByTitleFinder(title, new DefaultStringComparator(ce, cc))), index)); } /** * Waits a dialog by title between owner's owned windows. * @param owner Window - dialog owner. * @param title Dialog title * @param ce Compare exactly. If true, text can be a substring of caption. * @param cc Compare case sensitively. If true, both text and caption are * @return JDialog instance or null if component was not found. * */ public static JDialog waitJDialog(Window owner, String title, boolean ce, boolean cc) { return(waitJDialog(owner, title, ce, cc, 0)); } /** * Searhs for modal dialog currently staying on top. * @return dialog or null if no modal dialog is currently * displayed. */ public static Dialog getTopModalDialog() { return(DialogWaiter.getDialog(new ComponentChooser() { public boolean checkComponent(Component comp) { if(comp instanceof Dialog) { Dialog dialog = (Dialog)comp; if(dialog.isModal()) { Window[] ow = dialog.getOwnedWindows(); for(int i = 0; i < ow.length; i++) { if(ow[i].isVisible()) { return(false); } } return(true); } } return(false); } public String getDescription() { return("Upper modal dialog"); } })); } //////////////////////////////////////////////////////// //Mapping // /**Maps JDialog.getAccessibleContext() through queue*/ public AccessibleContext getAccessibleContext() { return((AccessibleContext)runMapping(new MapAction("getAccessibleContext") { public Object map() { return(((JDialog)getSource()).getAccessibleContext()); }}));} /**Maps JDialog.getContentPane() through queue*/ public Container getContentPane() { return((Container)runMapping(new MapAction("getContentPane") { public Object map() { return(((JDialog)getSource()).getContentPane()); }}));} /**Maps JDialog.getDefaultCloseOperation() through queue*/ public int getDefaultCloseOperation() { return(runMapping(new MapIntegerAction("getDefaultCloseOperation") { public int map() { return(((JDialog)getSource()).getDefaultCloseOperation()); }}));} /**Maps JDialog.getGlassPane() through queue*/ public Component getGlassPane() { return((Component)runMapping(new MapAction("getGlassPane") { public Object map() { return(((JDialog)getSource()).getGlassPane()); }}));} /**Maps JDialog.getJMenuBar() through queue*/ public JMenuBar getJMenuBar() { return((JMenuBar)runMapping(new MapAction("getJMenuBar") { public Object map() { return(((JDialog)getSource()).getJMenuBar()); }}));} /**Maps JDialog.getLayeredPane() through queue*/ public JLayeredPane getLayeredPane() { return((JLayeredPane)runMapping(new MapAction("getLayeredPane") { public Object map() { return(((JDialog)getSource()).getLayeredPane()); }}));} /**Maps JDialog.getRootPane() through queue*/ public JRootPane getRootPane() { return((JRootPane)runMapping(new MapAction("getRootPane") { public Object map() { return(((JDialog)getSource()).getRootPane()); }}));} /**Maps JDialog.setContentPane(Container) through queue*/ public void setContentPane(final Container container) { runMapping(new MapVoidAction("setContentPane") { public void map() { ((JDialog)getSource()).setContentPane(container); }});} /**Maps JDialog.setDefaultCloseOperation(int) through queue*/ public void setDefaultCloseOperation(final int i) { runMapping(new MapVoidAction("setDefaultCloseOperation") { public void map() { ((JDialog)getSource()).setDefaultCloseOperation(i); }});} /**Maps JDialog.setGlassPane(Component) through queue*/ public void setGlassPane(final Component component) { runMapping(new MapVoidAction("setGlassPane") { public void map() { ((JDialog)getSource()).setGlassPane(component); }});} /**Maps JDialog.setJMenuBar(JMenuBar) through queue*/ public void setJMenuBar(final JMenuBar jMenuBar) { runMapping(new MapVoidAction("setJMenuBar") { public void map() { ((JDialog)getSource()).setJMenuBar(jMenuBar); }});} /**Maps JDialog.setLayeredPane(JLayeredPane) through queue*/ public void setLayeredPane(final JLayeredPane jLayeredPane) { runMapping(new MapVoidAction("setLayeredPane") { public void map() { ((JDialog)getSource()).setLayeredPane(jLayeredPane); }});} /**Maps JDialog.setLocationRelativeTo(Component) through queue*/ public void setLocationRelativeTo(final Component component) { runMapping(new MapVoidAction("setLocationRelativeTo") { public void map() { ((JDialog)getSource()).setLocationRelativeTo(component); }});} //End of mapping // //////////////////////////////////////////////////////// /** * A method to be used from subclasses. * Uses timeouts and output passed as parameters during the waiting. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @param timeouts timeouts to be used during the waiting. * @param output an output to be used during the waiting. * @return Component instance or null if component was not found. */ protected static JDialog waitJDialog(ComponentChooser chooser, int index, Timeouts timeouts, TestOut output) { try { DialogWaiter waiter = new DialogWaiter(); waiter.setTimeouts(timeouts); waiter.setOutput(output); return((JDialog)waiter. waitDialog(new JDialogFinder(chooser), index)); } catch(InterruptedException e) { output.printStackTrace(e); return(null); } } /** * A method to be used from subclasses. * Uses owner's timeouts and output during the waiting. * @param owner a window - dialog owner. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return Component instance or null if component was not found. * @throws TimeoutExpiredException */ protected static JDialog waitJDialog(WindowOperator owner, ComponentChooser chooser, int index) { return(waitJDialog((Window)owner.getSource(), chooser, index, owner.getTimeouts(), owner.getOutput())); } /** * A method to be used from subclasses. * Uses timeouts and output passed as parameters during the waiting. * @param owner a window - dialog owner. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @param timeouts timeouts to be used during the waiting. * @param output an output to be used during the waiting. * @return Component instance or null if component was not found. */ protected static JDialog waitJDialog(Window owner, ComponentChooser chooser, int index, Timeouts timeouts, TestOut output) { try { DialogWaiter waiter = new DialogWaiter(); waiter.setTimeouts(timeouts); waiter.setOutput(output); return((JDialog)waiter. waitDialog(owner, new JDialogFinder(chooser), index)); } catch(InterruptedException e) { JemmyProperties.getCurrentOutput().printStackTrace(e); return(null); } } /** * Checks component type. */ public static class JDialogFinder extends Finder { /** * Constructs JDialogFinder. * @param sf other searching criteria. */ public JDialogFinder(ComponentChooser sf) { super(JDialog.class, sf); } /** * Constructs JDialogFinder. */ public JDialogFinder() { super(JDialog.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JTextAreaOperator.java0000644000175000017500000004653111245712347023526 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Container; import java.util.Hashtable; import javax.swing.JTextArea; import javax.swing.text.BadLocationException; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; /** * * Class provides basic functions to operate with JTextArea * (selection, typing, deleting) * *

Timeouts used:
* JTextComponentOperator.PushKeyTimeout - time between key pressing and releasing during text typing
* JTextComponentOperator.BetweenKeysTimeout - time to sleep between two chars typing
* JTextComponentOperator.ChangeCaretPositionTimeout - maximum time to chenge caret position
* JTextComponentOperator.TypeTextTimeout - maximum time to type text
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.WaitFocusTimeout - time to wait component focus
* JScrollBarOperator.OneScrollClickTimeout - time for one scroll click
* JScrollBarOperator.WholeScrollTimeout - time for the whole scrolling
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class JTextAreaOperator extends JTextComponentOperator implements Timeoutable, Outputable { /** * Identifier for a "column count" property. * @see #getDump */ public static final String COLUMN_COUNT_DPROP = "Column count"; /** * Identifier for a "row count" property. * @see #getDump */ public static final String ROW_COUNT_DPROP = "Row count"; private Timeouts timeouts; private TestOut output; /** * Constructor. * @param b a component */ public JTextAreaOperator(JTextArea b) { super(b); } /** * Constructs a JTextAreaOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JTextAreaOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JTextArea)cont. waitSubComponent(new JTextAreaFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JTextAreaOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JTextAreaOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTextAreaOperator(ContainerOperator cont, String text, int index) { this((JTextArea) waitComponent(cont, new JTextAreaFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, cont.getComparator())), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JTextAreaOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JTextAreaOperator(ContainerOperator cont, int index) { this((JTextArea) waitComponent(cont, new JTextAreaFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JTextAreaOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JTextArea in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JTextArea instance or null if component was not found. */ public static JTextArea findJTextArea(Container cont, ComponentChooser chooser, int index) { return((JTextArea)findJTextComponent(cont, new JTextAreaFinder(chooser), index)); } /** * Searches JTextArea in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JTextArea instance or null if component was not found. */ public static JTextArea findJTextArea(Container cont, ComponentChooser chooser) { return(findJTextArea(cont, chooser, 0)); } /** * Searches JTextArea by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JTextArea instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTextArea findJTextArea(Container cont, String text, boolean ce, boolean ccs, int index) { return(findJTextArea(cont, new JTextAreaFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Searches JTextArea by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JTextArea instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JTextArea findJTextArea(Container cont, String text, boolean ce, boolean ccs) { return(findJTextArea(cont, text, ce, ccs, 0)); } /** * Waits JTextArea in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @param index Ordinal component index. * @return JTextArea instance. * @throws TimeoutExpiredException */ public static JTextArea waitJTextArea(Container cont, ComponentChooser chooser, int index) { return((JTextArea)waitJTextComponent(cont, new JTextAreaFinder(chooser), index)); } /** * Waits JTextArea in container. * @param cont Container to search component in. * @param chooser a component chooser specifying searching criteria. * @return JTextArea instance. * @throws TimeoutExpiredException */ public static JTextArea waitJTextArea(Container cont, ComponentChooser chooser) { return(waitJTextArea(cont, chooser, 0)); } /** * Waits JTextArea by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JTextArea instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JTextArea waitJTextArea(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitJTextArea(cont, new JTextAreaFinder(new JTextComponentOperator. JTextComponentByTextFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Waits JTextArea by text. * @param cont Container to search component in. * @param text Component text. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JTextArea instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JTextArea waitJTextArea(Container cont, String text, boolean ce, boolean ccs) { return(waitJTextArea(cont, text, ce, ccs, 0)); } public void setTimeouts(Timeouts times) { timeouts = times; super.setTimeouts(timeouts); } public Timeouts getTimeouts() { return(timeouts); } public void setOutput(TestOut out) { output = out; super.setOutput(output.createErrorOutput()); } public TestOut getOutput() { return(output); } /** * Notifies whether "PageUp" and "PageDown" should be used * to change caret position. If can be useful if text takes * some pages. * @param yesOrNo if page navigation keys need to be used. * @deprecated All text operations are performed by TextDriver regitered for this operator type. */ public void usePageNavigationKeys(boolean yesOrNo) { } /** * Moves caret to line. * @param row Line to move caret to. * @see JTextComponentOperator#changeCaretPosition(int) * @see #changeCaretPosition(int) * @see #changeCaretPosition(int, int) * @throws TimeoutExpiredException */ public void changeCaretRow(int row) { changeCaretPosition(row, getCaretPosition() - getLineStartOffset(getLineOfOffset(getCaretPosition()))); } /** * Moves caret. * @param row Line to move caret to. * @param column Column to move caret to. * @see JTextComponentOperator#changeCaretPosition(int) * @see #changeCaretRow(int) * @see #changeCaretPosition(int, int) * @throws TimeoutExpiredException */ public void changeCaretPosition(int row, int column) { int startOffset = getLineStartOffset(row); int endOffset = getLineEndOffset(row); super.changeCaretPosition(getLineStartOffset(row) + ((column <= (endOffset - startOffset)) ? column : (endOffset - startOffset))); } /** * Types text. * @param text Text to be typed. * @param row Line to type text in. * @param column Column to type text from. * @see JTextComponentOperator#typeText(String, int) * @throws TimeoutExpiredException */ public void typeText(String text, int row, int column) { if(!hasFocus()) { makeComponentVisible(); } changeCaretPosition(row, column); typeText(text); } /** * Select a part of text. * @param startRow Start position row. * @param startColumn Start position column. * @param endRow End position row. * @param endColumn End position column. * @see JTextComponentOperator#selectText(int, int) * @see #selectLines(int, int) * @throws TimeoutExpiredException */ public void selectText(int startRow, int startColumn, int endRow, int endColumn) { int startPos = 0; try { startPos = getLineStartOffset(startRow) + startColumn; } catch(JemmyException e) { if(!(e.getInnerException() instanceof BadLocationException)) { throw(e); } } int endPos = getText().length(); try { endPos = getLineStartOffset(endRow) + endColumn; } catch(JemmyException e) { if(!(e.getInnerException() instanceof BadLocationException)) { throw(e); } } selectText(startPos, endPos); } /** * Select some text lines. * @param startLine start selection * @param endLine end selection * @see JTextComponentOperator#selectText(int, int) * @see #selectText(int, int, int, int) * @throws TimeoutExpiredException */ public void selectLines(int startLine, int endLine) { if(!hasFocus()) { makeComponentVisible(); } selectText(startLine, 0, endLine + 1, 0); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); result.put(COLUMN_COUNT_DPROP, Integer.toString(((JTextArea)getSource()).getRows())); result.put(ROW_COUNT_DPROP, Integer.toString(((JTextArea)getSource()).getColumns())); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JTextArea.append(String) through queue*/ public void append(final String string) { runMapping(new MapVoidAction("append") { public void map() { ((JTextArea)getSource()).append(string); }});} /**Maps JTextArea.getColumns() through queue*/ public int getColumns() { return(runMapping(new MapIntegerAction("getColumns") { public int map() { return(((JTextArea)getSource()).getColumns()); }}));} /**Maps JTextArea.getLineCount() through queue*/ public int getLineCount() { return(runMapping(new MapIntegerAction("getLineCount") { public int map() { return(((JTextArea)getSource()).getLineCount()); }}));} /**Maps JTextArea.getLineEndOffset(int) through queue*/ public int getLineEndOffset(final int i) { return(runMapping(new MapIntegerAction("getLineEndOffset") { public int map() throws BadLocationException { return(((JTextArea)getSource()).getLineEndOffset(i)); }}));} /**Maps JTextArea.getLineOfOffset(int) through queue*/ public int getLineOfOffset(final int i) { return(runMapping(new MapIntegerAction("getLineOfOffset") { public int map() throws BadLocationException { return(((JTextArea)getSource()).getLineOfOffset(i)); }}));} /**Maps JTextArea.getLineStartOffset(int) through queue*/ public int getLineStartOffset(final int i) { return(runMapping(new MapIntegerAction("getLineStartOffset") { public int map() throws BadLocationException { return(((JTextArea)getSource()).getLineStartOffset(i)); }}));} /**Maps JTextArea.getLineWrap() through queue*/ public boolean getLineWrap() { return(runMapping(new MapBooleanAction("getLineWrap") { public boolean map() { return(((JTextArea)getSource()).getLineWrap()); }}));} /**Maps JTextArea.getRows() through queue*/ public int getRows() { return(runMapping(new MapIntegerAction("getRows") { public int map() { return(((JTextArea)getSource()).getRows()); }}));} /**Maps JTextArea.getTabSize() through queue*/ public int getTabSize() { return(runMapping(new MapIntegerAction("getTabSize") { public int map() { return(((JTextArea)getSource()).getTabSize()); }}));} /**Maps JTextArea.getWrapStyleWord() through queue*/ public boolean getWrapStyleWord() { return(runMapping(new MapBooleanAction("getWrapStyleWord") { public boolean map() { return(((JTextArea)getSource()).getWrapStyleWord()); }}));} /**Maps JTextArea.insert(String, int) through queue*/ public void insert(final String string, final int i) { runMapping(new MapVoidAction("insert") { public void map() { ((JTextArea)getSource()).insert(string, i); }});} /**Maps JTextArea.replaceRange(String, int, int) through queue*/ public void replaceRange(final String string, final int i, final int i1) { runMapping(new MapVoidAction("replaceRange") { public void map() { ((JTextArea)getSource()).replaceRange(string, i, i1); }});} /**Maps JTextArea.setColumns(int) through queue*/ public void setColumns(final int i) { runMapping(new MapVoidAction("setColumns") { public void map() { ((JTextArea)getSource()).setColumns(i); }});} /**Maps JTextArea.setLineWrap(boolean) through queue*/ public void setLineWrap(final boolean b) { runMapping(new MapVoidAction("setLineWrap") { public void map() { ((JTextArea)getSource()).setLineWrap(b); }});} /**Maps JTextArea.setRows(int) through queue*/ public void setRows(final int i) { runMapping(new MapVoidAction("setRows") { public void map() { ((JTextArea)getSource()).setRows(i); }});} /**Maps JTextArea.setTabSize(int) through queue*/ public void setTabSize(final int i) { runMapping(new MapVoidAction("setTabSize") { public void map() { ((JTextArea)getSource()).setTabSize(i); }});} /**Maps JTextArea.setWrapStyleWord(boolean) through queue*/ public void setWrapStyleWord(final boolean b) { runMapping(new MapVoidAction("setWrapStyleWord") { public void map() { ((JTextArea)getSource()).setWrapStyleWord(b); }});} //End of mapping // //////////////////////////////////////////////////////// /** * Checks component type. */ public static class JTextAreaFinder extends Finder { /** * Constructs JTextAreaFinder. * @param sf other searching criteria. */ public JTextAreaFinder(ComponentChooser sf) { super(JTextArea.class, sf); } /** * Constructs JTextAreaFinder. */ public JTextAreaFinder() { super(JTextArea.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JCheckBoxOperator.java0000644000175000017500000002417711245712237023477 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Container; import javax.swing.JCheckBox; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.TimeoutExpiredException; /** * *

Timeouts used:
* AbstractButtonOperator.PushButtonTimeout - time between button pressing and releasing
* ComponentOperator.WaitComponentTimeout - time to wait button displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait button enabled
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JCheckBoxOperator extends JToggleButtonOperator{ /** * Constructor. * @param b a component */ public JCheckBoxOperator(JCheckBox b) { super(b); } /** * Constructs a JCheckBoxOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JCheckBoxOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JCheckBox)cont. waitSubComponent(new JCheckBoxFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JCheckBoxOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JCheckBoxOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JCheckBoxOperator(ContainerOperator cont, String text, int index) { this((JCheckBox) waitComponent(cont, new JCheckBoxFinder(new AbstractButtonOperator. AbstractButtonByLabelFinder(text, cont.getComparator())), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Button text. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public JCheckBoxOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * @throws TimeoutExpiredException */ public JCheckBoxOperator(ContainerOperator cont, int index) { this((JCheckBox) waitComponent(cont, new JCheckBoxFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @throws TimeoutExpiredException */ public JCheckBoxOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JCheckBox in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JCheckBox instance or null if component was not found. */ public static JCheckBox findJCheckBox(Container cont, ComponentChooser chooser, int index) { return((JCheckBox)findJToggleButton(cont, new JCheckBoxFinder(chooser), index)); } /** * Searches 0'th JCheckBox in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JCheckBox instance or null if component was not found. */ public static JCheckBox findJCheckBox(Container cont, ComponentChooser chooser) { return(findJCheckBox(cont, chooser, 0)); } /** * Searches JCheckBox by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JCheckBox instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JCheckBox findJCheckBox(Container cont, String text, boolean ce, boolean ccs, int index) { return(findJCheckBox(cont, new JCheckBoxFinder(new AbstractButtonOperator. AbstractButtonByLabelFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Searches JCheckBox by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JCheckBox instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JCheckBox findJCheckBox(Container cont, String text, boolean ce, boolean ccs) { return(findJCheckBox(cont, text, ce, ccs, 0)); } /** * Waits JCheckBox in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JCheckBox instance. * @throws TimeoutExpiredException */ public static JCheckBox waitJCheckBox(Container cont, ComponentChooser chooser, int index) { return((JCheckBox)waitJToggleButton(cont, new JCheckBoxFinder(chooser), index)); } /** * Waits 0'th JCheckBox in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JCheckBox instance. * @throws TimeoutExpiredException */ public static JCheckBox waitJCheckBox(Container cont, ComponentChooser chooser) { return(waitJCheckBox(cont, chooser, 0)); } /** * Waits JCheckBox by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param index Ordinal component index. * @return JCheckBox instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JCheckBox waitJCheckBox(Container cont, String text, boolean ce, boolean ccs, int index) { return(waitJCheckBox(cont, new JCheckBoxFinder(new AbstractButtonOperator. AbstractButtonByLabelFinder(text, new DefaultStringComparator(ce, ccs))), index)); } /** * Waits JCheckBox by text. * @param cont Container to search component in. * @param text Button text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @return JCheckBox instance. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @throws TimeoutExpiredException */ public static JCheckBox waitJCheckBox(Container cont, String text, boolean ce, boolean ccs) { return(waitJCheckBox(cont, text, ce, ccs, 0)); } /** * Checks component type. */ public static class JCheckBoxFinder extends Finder { /** * Constructs JCheckBoxFinder. * @param sf other searching criteria. */ public JCheckBoxFinder(ComponentChooser sf) { super(JCheckBox.class, sf); } /** * Constructs JCheckBoxFinder. */ public JCheckBoxFinder() { super(JCheckBox.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/JListOperator.java0000644000175000017500000013755111245712237022725 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.util.Hashtable; import java.util.Vector; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.ListModel; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionListener; import javax.swing.plaf.ListUI; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.JemmyInputException; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.MultiSelListDriver; import org.netbeans.jemmy.util.EmptyVisualizer; /** *

Timeouts used:
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.WaitStateTimeout - time to wait for item, and for item to be selected
* JScrollBarOperator.OneScrollClickTimeout - time for one scroll click
* JScrollBarOperator.WholeScrollTimeout - time for the whole scrolling
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JListOperator extends JComponentOperator implements Outputable { /** * Identifier for a "item" properties. * @see #getDump */ public static final String ITEM_PREFIX_DPROP = "Item"; /** * Identifier for a "selected item" property. * @see #getDump */ public static final String SELECTED_ITEM_PREFIX_DPROP = "SelectedItem"; private TestOut output; private MultiSelListDriver driver; /** * Constructor. * @param b a component */ public JListOperator(JList b) { super(b); driver = DriverManager.getMultiSelListDriver(getClass()); } /** * Constructs a JListOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public JListOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this((JList)cont. waitSubComponent(new JListFinder(chooser), index)); copyEnvironment(cont); } /** * Constructs a JListOperator object. * @param cont a container * @param chooser a component chooser specifying searching criteria. */ public JListOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits item text first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of item which is currently selected. * @param itemIndex Item index. * @param index Ordinal component index. * */ public JListOperator(ContainerOperator cont, String text, int itemIndex, int index) { this((JList)waitComponent(cont, new JListByItemFinder(text, itemIndex, cont.getComparator()), index)); copyEnvironment(cont); } /** * Constructor. * Waits component by selected item text first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of item which is currently selected. * @param index Ordinal component index. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public JListOperator(ContainerOperator cont, String text, int index) { this(cont, text, -1, index); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param text Text of item which is currently selected. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public JListOperator(ContainerOperator cont, String text) { this(cont, text, 0); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * @param index Ordinal component index. * */ public JListOperator(ContainerOperator cont, int index) { this((JList) waitComponent(cont, new JListFinder(), index)); copyEnvironment(cont); } /** * Constructor. * Waits component in container first. * Uses cont's timeout and output for waiting and to init operator. * @param cont a container * */ public JListOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches JList in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JList instance or null if component was not found. */ public static JList findJList(Container cont, ComponentChooser chooser, int index) { return((JList)findComponent(cont, new JListFinder(chooser), index)); } /** * Searches 0'th JList in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JList instance or null if component was not found. */ public static JList findJList(Container cont, ComponentChooser chooser) { return(findJList(cont, chooser, 0)); } /** * Searches JList by item. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param itemIndex Index of item to compare text. If -1, selected item is checked. * @param index Ordinal component index. * @return JList instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JList findJList(Container cont, String text, boolean ce, boolean ccs, int itemIndex, int index) { return(findJList(cont, new JListByItemFinder(text, itemIndex, new DefaultStringComparator(ce, ccs)), index)); } /** * Searches JList by item. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param itemIndex Index of item to compare text. If -1, selected item is checked. * @return JList instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public static JList findJList(Container cont, String text, boolean ce, boolean ccs, int itemIndex) { return(findJList(cont, text, ce, ccs, itemIndex, 0)); } /** * Waits JList in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return JList instance or null if component was not found. * */ public static JList waitJList(Container cont, ComponentChooser chooser, int index) { return((JList)waitComponent(cont, new JListFinder(chooser), index)); } /** * Waits 0'th JList in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return JList instance or null if component was not found. * */ public static JList waitJList(Container cont, ComponentChooser chooser) { return(waitJList(cont, chooser, 0)); } /** * Waits JList by item. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param itemIndex Index of item to compare text. If -1, selected item is checked. * @param index Ordinal component index. * @return JList instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public static JList waitJList(Container cont, String text, boolean ce, boolean ccs, int itemIndex, int index) { return(waitJList(cont, new JListByItemFinder(text, itemIndex, new DefaultStringComparator(ce, ccs)), index)); } /** * Waits JList by item. * @param cont Container to search component in. * @param text Item text. If null, contents is not checked. * @param ce Compare text exactly. * @param ccs Compare text case sensitively. * @param itemIndex Index of item to compare text. If -1, selected item is checked. * @return JList instance or null if component was not found. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * */ public static JList waitJList(Container cont, String text, boolean ce, boolean ccs, int itemIndex) { return(waitJList(cont, text, ce, ccs, itemIndex, 0)); } public void setOutput(TestOut output) { super.setOutput(output.createErrorOutput()); this.output = output; } public TestOut getOutput() { return(output); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); driver = (MultiSelListDriver)DriverManager. getDriver(DriverManager.MULTISELLIST_DRIVER_ID, getClass(), anotherOperator.getProperties()); } /** * Gets point to click on itemIndex'th item. * @param itemIndex an index of an item to click. * @return a Point in component's coordinate system. */ public Point getClickPoint(int itemIndex) { Rectangle rect = getCellBounds(itemIndex, itemIndex); return(new Point(rect.x + rect.width / 2, rect.y + rect.height / 2)); } /** * Ask renderer for component to be displayed. * @param itemIndex Item index. * @param isSelected True if the specified cell was selected. * @param cellHasFocus True if the specified cell has the focus. * @return Component to be displayed. */ public Component getRenderedComponent(int itemIndex, boolean isSelected, boolean cellHasFocus) { return(getCellRenderer(). getListCellRendererComponent((JList)getSource(), getModel().getElementAt(itemIndex), itemIndex, isSelected, cellHasFocus)); } /** * Ask renderer for component to be displayed. * Uses isSelectedIndex(itemIndex) to determine whether item is selected. * Supposes item do not have focus. * @param itemIndex Item index. * @return Component to be displayed. */ public Component getRenderedComponent(int itemIndex) { return(getRenderedComponent(itemIndex, isSelectedIndex(itemIndex), false)); } /** * Searches for index'th item good from chooser's point of view. * @param chooser Item verifying object. * @param index Ordinal item index. * @return Item index or -1 if search was insuccessful. */ public int findItemIndex(ListItemChooser chooser, int index) { ListModel model = getModel(); int count = 0; for(int i = 0; i < model.getSize(); i++) { if(chooser.checkItem(this, i)) { if(count == index) { return(i); } else { count++; } } } return(-1); } /** * Searches for an item good from chooser's point of view. * @param chooser Item verifying object. * @return Item index or -1 if serch was insuccessful. * @see #findItemIndex(JListOperator.ListItemChooser, int) * @see #findItemIndex(String, boolean, boolean) */ public int findItemIndex(ListItemChooser chooser) { return(findItemIndex(chooser, 0)); } /** * Searches for an item good from chooser's point of view. * @param item a text pattern * @param comparator a string comparision algorithm * @param index Ordinal item index. * @return Item index or -1 if serch was insuccessful. * @see #findItemIndex(JListOperator.ListItemChooser, int) * @see #findItemIndex(String, boolean, boolean) */ public int findItemIndex(String item, StringComparator comparator, int index){ return(findItemIndex(new BySubStringListItemChooser(item, comparator), index)); } /** * Searched for index'th item by text. * @param item a text pattern * @param ce Compare text exactly. * @param cc Compare text case sensitively. * @param index Ordinal item index. * @return Item index or -1 if serch was insuccessful. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @deprecated Use findItemIndex(String, int) or findItemIndex(String, StringComparator, int) */ public int findItemIndex(String item, boolean ce, boolean cc, int index){ return(findItemIndex(item, new DefaultStringComparator(ce, cc), index)); } /** * Searched for index'th item by text. * Uses StringComparator assigned to this object. * @param item a text pattern * @param index Ordinal item index. * @return Item index or -1 if search was insuccessful. */ public int findItemIndex(String item, int index){ return(findItemIndex(item, getComparator(), index)); } /** * Searches for an item good from chooser's point of view. * @param item a text pattern * @param comparator a string comparision algorithm * @return Item index or -1 if serch was insuccessful. * @see #findItemIndex(JListOperator.ListItemChooser, int) * @see #findItemIndex(String, boolean, boolean) */ public int findItemIndex(String item, StringComparator comparator){ return(findItemIndex(item, comparator, 0)); } /** * Searched item by text. * @param item a text pattern * @param ce Compare text exactly. * @param cc Compare text case sensitively. * @return Item index or -1 if search was insuccessful. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) * @deprecated Use findItemIndex(String) or findItemIndex(String, StringComparator) */ public int findItemIndex(String item, boolean ce, boolean cc) { return(findItemIndex(item, ce, cc, 0)); } /** * Searched for first item by text. * Uses StringComparator assigned to this object. * @param item a text pattern * @return Item index or -1 if search was insuccessful. * @see ComponentOperator#isCaptionEqual(String, String, boolean, boolean) */ public int findItemIndex(String item){ return(findItemIndex(item, 0)); } /** * Searches for index'th item by rendered component. * @param chooser Component verifying object. * @param index Ordinal item index. * @return Item index or -1 if serch was insuccessful. * @see #getRenderedComponent(int, boolean, boolean) */ public int findItemIndex(ComponentChooser chooser, int index) { return(findItemIndex(new ByRenderedComponentListItemChooser(chooser), index)); } /** * Searches for an item by rendered component. * @param chooser Component verifying object. * @return Item index or -1 if serch was insuccessful. * @see #getRenderedComponent(int, boolean, boolean) */ public int findItemIndex(ComponentChooser chooser) { return(findItemIndex(chooser, 0)); } /** * Clicks on item by item index. * @param itemIndex Item index. * @param clickCount count click. * @return Click point or null if list does not contains itemIndex'th item. * @throws NoSuchItemException */ public Object clickOnItem(final int itemIndex, final int clickCount) { output.printLine("Click " + Integer.toString(clickCount) + " times on JList\n : " + toStringSource()); output.printGolden("Click " + Integer.toString(clickCount) + " times on JList"); checkIndex(itemIndex); try { scrollToItem(itemIndex); } catch(TimeoutExpiredException e) { output.printStackTrace(e); } if(((JList)getSource()).getModel().getSize() <= itemIndex) { output.printErrLine("JList " + toStringSource() + " does not contain " + Integer.toString(itemIndex) + "'th item"); return(null); } if(((JList)getSource()).getAutoscrolls()) { ((JList)getSource()).ensureIndexIsVisible(itemIndex); } return(getQueueTool().invokeSmoothly(new QueueTool.QueueAction("Path selecting") { public Object launch() { Rectangle rect = getCellBounds(itemIndex, itemIndex); if(rect == null) { output.printErrLine("Impossible to determine click point for " + Integer.toString(itemIndex) + "'th item"); return(null); } Point point = new Point((int)(rect.getX() + rect.getWidth() / 2), (int)(rect.getY() + rect.getHeight() / 2)); Object result = getModel().getElementAt(itemIndex); clickMouse(point.x, point.y, clickCount); return(result); } })); } /** * Finds item by item text, and do mouse click on it. * @param item Item text. * @param comparator a string comparision algorithm * @param clickCount count click. * @return Click point or null if list does not contains itemIndex'th item. * @throws NoSuchItemException */ public Object clickOnItem(final String item, final StringComparator comparator, final int clickCount) { scrollToItem(findItemIndex(item, comparator, 0)); return(getQueueTool().invokeSmoothly(new QueueTool.QueueAction("Path selecting") { public Object launch() { int index = findItemIndex(item, comparator, 0); if(index != -1) { return(clickOnItem(index, clickCount)); } else { throw(new NoSuchItemException(item)); } } })); } /** * Finds item by item text, and do mouse click on it. * @param item Item text. * @param ce Compare exactly. * @param cc Compare case sensitively. * @param clickCount count click. * @return Click point or null if list does not contains itemIndex'th item. * @throws NoSuchItemException * @deprecated Use clickOnItem(String, int) or clickOnItem(String, StringComparator, int) */ public Object clickOnItem(String item, boolean ce, boolean cc, int clickCount) { return(clickOnItem(item, new DefaultStringComparator(ce, cc), clickCount)); } /** * Finds item by item text, and do mouse click on it. * Uses StringComparator assigned to this object. * @param item Item text. * @param clickCount count click. * @return Click point or null if list does not contains itemIndex'th item. * @throws NoSuchItemException */ public Object clickOnItem(String item, int clickCount) { return(clickOnItem(item, getComparator(), clickCount)); } /** * Finds item by item text, and do simple mouse click on it. * Uses StringComparator assigned to this object. * @param item Item text. * @param comparator a string comparision algorithm * @return Click point or null if list does not contains itemIndex'th item. * @throws NoSuchItemException */ public Object clickOnItem(String item, StringComparator comparator) { return(clickOnItem(item, comparator, 1)); } /** * Finds item by item text, and do simple mouse click on it. * @param item Item text. * @param ce Compare exactly. * @param cc Compare case sensitively. * @return Click point or null if list does not contains itemIndex'th item. * @throws NoSuchItemException * @deprecated Use clickOnItem(String) or clickOnItem(String, StringComparator) */ public Object clickOnItem(String item, boolean ce, boolean cc) { return(clickOnItem(item, ce, cc, 1)); } /** * Finds item by item text, and do simple mouse click on it. * Uses StringComparator assigned to this object. * @param item Item text. * @return Click point or null if list does not contains itemIndex'th item. * @throws NoSuchItemException */ public Object clickOnItem(String item) { return(clickOnItem(item, 0)); } /** * Scrolls to an item if the list is on a JScrollPane component. * @param itemIndex an item index. * @see #scrollToItem(String, boolean, boolean) * * @throws NoSuchItemException */ public void scrollToItem(int itemIndex) { output.printTrace("Scroll JList to " + Integer.toString(itemIndex) + "'th item\n : " + toStringSource()); output.printGolden("Scroll JList to " + Integer.toString(itemIndex) + "'th item"); checkIndex(itemIndex); makeComponentVisible(); //try to find JScrollPane under. JScrollPane scroll = (JScrollPane)getContainer(new JScrollPaneOperator. JScrollPaneFinder(ComponentSearcher. getTrueChooser("JScrollPane"))); if(scroll == null) { return; } JScrollPaneOperator scroller = new JScrollPaneOperator(scroll); scroller.copyEnvironment(this); scroller.setVisualizer(new EmptyVisualizer()); Rectangle rect = getCellBounds(itemIndex, itemIndex); scroller.scrollToComponentRectangle(getSource(), (int)rect.getX(), (int)rect.getY(), (int)rect.getWidth(), (int)rect.getHeight()); } /** * Scrolls to an item if the list is on a JScrollPane component. * @param item Item text * @param comparator a string comparision algorithm * @see #scrollToItem(String, boolean, boolean) * */ public void scrollToItem(String item, StringComparator comparator) { scrollToItem(findItemIndex(item, comparator)); } /** * Scrolls to an item if the list is on a JScrollPane component. * @param item Item text * @param ce Compare exactly. * @param cc Compare case sensitively. * @see #scrollToItem(String, boolean, boolean) * * @deprecated Use scrollToItem(String) or scrollToItem(String, StringComparator) */ public void scrollToItem(String item, boolean ce, boolean cc) { scrollToItem(findItemIndex(item, ce, cc)); } /** * Selects an item by index. * @param index an item index. */ public void selectItem(int index) { checkIndex(index); driver.selectItem(this, index); if(getVerification()) { waitItemSelection(index, true); } } /** * Selects an item by text. * @param item an item text. */ public void selectItem(final String item) { scrollToItem(findItemIndex(item)); getQueueTool().invokeSmoothly(new QueueTool.QueueAction("Path selecting") { public Object launch() { driver.selectItem(JListOperator.this, findItemIndex(item)); return(null); } }); } /** * Selects items by indices. * @param indices item indices. */ public void selectItems(int[] indices) { checkIndices(indices); driver.selectItems(this, indices); if(getVerification()) { waitItemsSelection(indices, true); } } /** * Selects items by texts. * @param items item texts. */ public void selectItem(String[] items) { int[] indices = new int[items.length]; for(int i = 0; i < items.length; i++) { indices[i] = findItemIndex(items[i]); } selectItems(indices); } /** * Waits for items to be selected. * @param itemIndices item indices to be selected * @param selected Selected (true) or unselected (false). */ public void waitItemsSelection(final int[] itemIndices, final boolean selected) { getOutput().printLine("Wait items to be " + (selected ? "" : "un") + "selected in component \n : "+ toStringSource()); getOutput().printGolden("Wait items to be " + (selected ? "" : "un") + "selected"); waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { int[] indices = getSelectedIndices(); for(int i = 0; i < indices.length; i++) { if(indices[i] != itemIndices[i]) { return(false); } } return(true); } public String getDescription() { return("Item has been " + (selected ? "" : "un") + "selected"); } }); } /** * Waits for item to be selected. * @param itemIndex an item needs to be selected * @param selected Selected (true) or unselected (false). */ public void waitItemSelection(final int itemIndex, final boolean selected) { waitItemsSelection(new int[] {itemIndex}, selected); } /** * Waits for item. Uses getComparator() comparator. * @param item an item text * @param itemIndex Index of item to check or -1 to check selected item. */ public void waitItem(String item, int itemIndex) { getOutput().printLine("Wait \"" + item + "\" at the " + Integer.toString(itemIndex) + " position in component \n : "+ toStringSource()); getOutput().printGolden("Wait \"" + item + "\" at the " + Integer.toString(itemIndex) + " position"); waitState(new JListByItemFinder(item, itemIndex, getComparator())); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); String[] items = new String[((JList)getSource()).getModel().getSize()]; for(int i = 0; i < ((JList)getSource()).getModel().getSize(); i++) { items[i] = ((JList)getSource()).getModel().getElementAt(i).toString(); } int[] selectedIndices = ((JList)getSource()).getSelectedIndices(); String[] selectedItems = new String[selectedIndices.length]; for(int i = 0; i < selectedIndices.length; i++) { selectedItems[i] = items[selectedIndices[i]]; } addToDump(result, ITEM_PREFIX_DPROP, items); addToDump(result, SELECTED_ITEM_PREFIX_DPROP, selectedItems); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps JList.addListSelectionListener(ListSelectionListener) through queue*/ public void addListSelectionListener(final ListSelectionListener listSelectionListener) { runMapping(new MapVoidAction("addListSelectionListener") { public void map() { ((JList)getSource()).addListSelectionListener(listSelectionListener); }});} /**Maps JList.addSelectionInterval(int, int) through queue*/ public void addSelectionInterval(final int i, final int i1) { runMapping(new MapVoidAction("addSelectionInterval") { public void map() { ((JList)getSource()).addSelectionInterval(i, i1); }});} /**Maps JList.clearSelection() through queue*/ public void clearSelection() { runMapping(new MapVoidAction("clearSelection") { public void map() { ((JList)getSource()).clearSelection(); }});} /**Maps JList.ensureIndexIsVisible(int) through queue*/ public void ensureIndexIsVisible(final int i) { runMapping(new MapVoidAction("ensureIndexIsVisible") { public void map() { ((JList)getSource()).ensureIndexIsVisible(i); }});} /**Maps JList.getAnchorSelectionIndex() through queue*/ public int getAnchorSelectionIndex() { return(runMapping(new MapIntegerAction("getAnchorSelectionIndex") { public int map() { return(((JList)getSource()).getAnchorSelectionIndex()); }}));} /**Maps JList.getCellBounds(int, int) through queue*/ public Rectangle getCellBounds(final int i, final int i1) { return((Rectangle)runMapping(new MapAction("getCellBounds") { public Object map() { return(((JList)getSource()).getCellBounds(i, i1)); }}));} /**Maps JList.getCellRenderer() through queue*/ public ListCellRenderer getCellRenderer() { return((ListCellRenderer)runMapping(new MapAction("getCellRenderer") { public Object map() { return(((JList)getSource()).getCellRenderer()); }}));} /**Maps JList.getFirstVisibleIndex() through queue*/ public int getFirstVisibleIndex() { return(runMapping(new MapIntegerAction("getFirstVisibleIndex") { public int map() { return(((JList)getSource()).getFirstVisibleIndex()); }}));} /**Maps JList.getFixedCellHeight() through queue*/ public int getFixedCellHeight() { return(runMapping(new MapIntegerAction("getFixedCellHeight") { public int map() { return(((JList)getSource()).getFixedCellHeight()); }}));} /**Maps JList.getFixedCellWidth() through queue*/ public int getFixedCellWidth() { return(runMapping(new MapIntegerAction("getFixedCellWidth") { public int map() { return(((JList)getSource()).getFixedCellWidth()); }}));} /**Maps JList.getLastVisibleIndex() through queue*/ public int getLastVisibleIndex() { return(runMapping(new MapIntegerAction("getLastVisibleIndex") { public int map() { return(((JList)getSource()).getLastVisibleIndex()); }}));} /**Maps JList.getLeadSelectionIndex() through queue*/ public int getLeadSelectionIndex() { return(runMapping(new MapIntegerAction("getLeadSelectionIndex") { public int map() { return(((JList)getSource()).getLeadSelectionIndex()); }}));} /**Maps JList.getMaxSelectionIndex() through queue*/ public int getMaxSelectionIndex() { return(runMapping(new MapIntegerAction("getMaxSelectionIndex") { public int map() { return(((JList)getSource()).getMaxSelectionIndex()); }}));} /**Maps JList.getMinSelectionIndex() through queue*/ public int getMinSelectionIndex() { return(runMapping(new MapIntegerAction("getMinSelectionIndex") { public int map() { return(((JList)getSource()).getMinSelectionIndex()); }}));} /**Maps JList.getModel() through queue*/ public ListModel getModel() { return((ListModel)runMapping(new MapAction("getModel") { public Object map() { return(((JList)getSource()).getModel()); }}));} /**Maps JList.getPreferredScrollableViewportSize() through queue*/ public Dimension getPreferredScrollableViewportSize() { return((Dimension)runMapping(new MapAction("getPreferredScrollableViewportSize") { public Object map() { return(((JList)getSource()).getPreferredScrollableViewportSize()); }}));} /**Maps JList.getPrototypeCellValue() through queue*/ public Object getPrototypeCellValue() { return((Object)runMapping(new MapAction("getPrototypeCellValue") { public Object map() { return(((JList)getSource()).getPrototypeCellValue()); }}));} /**Maps JList.getScrollableBlockIncrement(Rectangle, int, int) through queue*/ public int getScrollableBlockIncrement(final Rectangle rectangle, final int i, final int i1) { return(runMapping(new MapIntegerAction("getScrollableBlockIncrement") { public int map() { return(((JList)getSource()).getScrollableBlockIncrement(rectangle, i, i1)); }}));} /**Maps JList.getScrollableTracksViewportHeight() through queue*/ public boolean getScrollableTracksViewportHeight() { return(runMapping(new MapBooleanAction("getScrollableTracksViewportHeight") { public boolean map() { return(((JList)getSource()).getScrollableTracksViewportHeight()); }}));} /**Maps JList.getScrollableTracksViewportWidth() through queue*/ public boolean getScrollableTracksViewportWidth() { return(runMapping(new MapBooleanAction("getScrollableTracksViewportWidth") { public boolean map() { return(((JList)getSource()).getScrollableTracksViewportWidth()); }}));} /**Maps JList.getScrollableUnitIncrement(Rectangle, int, int) through queue*/ public int getScrollableUnitIncrement(final Rectangle rectangle, final int i, final int i1) { return(runMapping(new MapIntegerAction("getScrollableUnitIncrement") { public int map() { return(((JList)getSource()).getScrollableUnitIncrement(rectangle, i, i1)); }}));} /**Maps JList.getSelectedIndex() through queue*/ public int getSelectedIndex() { return(runMapping(new MapIntegerAction("getSelectedIndex") { public int map() { return(((JList)getSource()).getSelectedIndex()); }}));} /**Maps JList.getSelectedIndices() through queue*/ public int[] getSelectedIndices() { return((int[])runMapping(new MapAction("getSelectedIndices") { public Object map() { return(((JList)getSource()).getSelectedIndices()); }}));} /**Maps JList.getSelectedValue() through queue*/ public Object getSelectedValue() { return((Object)runMapping(new MapAction("getSelectedValue") { public Object map() { return(((JList)getSource()).getSelectedValue()); }}));} /**Maps JList.getSelectedValues() through queue*/ public Object[] getSelectedValues() { return((Object[])runMapping(new MapAction("getSelectedValues") { public Object map() { return(((JList)getSource()).getSelectedValues()); }}));} /**Maps JList.getSelectionBackground() through queue*/ public Color getSelectionBackground() { return((Color)runMapping(new MapAction("getSelectionBackground") { public Object map() { return(((JList)getSource()).getSelectionBackground()); }}));} /**Maps JList.getSelectionForeground() through queue*/ public Color getSelectionForeground() { return((Color)runMapping(new MapAction("getSelectionForeground") { public Object map() { return(((JList)getSource()).getSelectionForeground()); }}));} /**Maps JList.getSelectionMode() through queue*/ public int getSelectionMode() { return(runMapping(new MapIntegerAction("getSelectionMode") { public int map() { return(((JList)getSource()).getSelectionMode()); }}));} /**Maps JList.getSelectionModel() through queue*/ public ListSelectionModel getSelectionModel() { return((ListSelectionModel)runMapping(new MapAction("getSelectionModel") { public Object map() { return(((JList)getSource()).getSelectionModel()); }}));} /**Maps JList.getUI() through queue*/ public ListUI getUI() { return((ListUI)runMapping(new MapAction("getUI") { public Object map() { return(((JList)getSource()).getUI()); }}));} /**Maps JList.getValueIsAdjusting() through queue*/ public boolean getValueIsAdjusting() { return(runMapping(new MapBooleanAction("getValueIsAdjusting") { public boolean map() { return(((JList)getSource()).getValueIsAdjusting()); }}));} /**Maps JList.getVisibleRowCount() through queue*/ public int getVisibleRowCount() { return(runMapping(new MapIntegerAction("getVisibleRowCount") { public int map() { return(((JList)getSource()).getVisibleRowCount()); }}));} /**Maps JList.indexToLocation(int) through queue*/ public Point indexToLocation(final int i) { return((Point)runMapping(new MapAction("indexToLocation") { public Object map() { return(((JList)getSource()).indexToLocation(i)); }}));} /**Maps JList.isSelectedIndex(int) through queue*/ public boolean isSelectedIndex(final int i) { return(runMapping(new MapBooleanAction("isSelectedIndex") { public boolean map() { return(((JList)getSource()).isSelectedIndex(i)); }}));} /**Maps JList.isSelectionEmpty() through queue*/ public boolean isSelectionEmpty() { return(runMapping(new MapBooleanAction("isSelectionEmpty") { public boolean map() { return(((JList)getSource()).isSelectionEmpty()); }}));} /**Maps JList.locationToIndex(Point) through queue*/ public int locationToIndex(final Point point) { return(runMapping(new MapIntegerAction("locationToIndex") { public int map() { return(((JList)getSource()).locationToIndex(point)); }}));} /**Maps JList.removeListSelectionListener(ListSelectionListener) through queue*/ public void removeListSelectionListener(final ListSelectionListener listSelectionListener) { runMapping(new MapVoidAction("removeListSelectionListener") { public void map() { ((JList)getSource()).removeListSelectionListener(listSelectionListener); }});} /**Maps JList.removeSelectionInterval(int, int) through queue*/ public void removeSelectionInterval(final int i, final int i1) { runMapping(new MapVoidAction("removeSelectionInterval") { public void map() { ((JList)getSource()).removeSelectionInterval(i, i1); }});} /**Maps JList.setCellRenderer(ListCellRenderer) through queue*/ public void setCellRenderer(final ListCellRenderer listCellRenderer) { runMapping(new MapVoidAction("setCellRenderer") { public void map() { ((JList)getSource()).setCellRenderer(listCellRenderer); }});} /**Maps JList.setFixedCellHeight(int) through queue*/ public void setFixedCellHeight(final int i) { runMapping(new MapVoidAction("setFixedCellHeight") { public void map() { ((JList)getSource()).setFixedCellHeight(i); }});} /**Maps JList.setFixedCellWidth(int) through queue*/ public void setFixedCellWidth(final int i) { runMapping(new MapVoidAction("setFixedCellWidth") { public void map() { ((JList)getSource()).setFixedCellWidth(i); }});} /**Maps JList.setListData(Vector) through queue*/ public void setListData(final Vector vector) { runMapping(new MapVoidAction("setListData") { public void map() { ((JList)getSource()).setListData(vector); }});} /**Maps JList.setListData(Object[]) through queue*/ public void setListData(final Object[] object) { runMapping(new MapVoidAction("setListData") { public void map() { ((JList)getSource()).setListData(object); }});} /**Maps JList.setModel(ListModel) through queue*/ public void setModel(final ListModel listModel) { runMapping(new MapVoidAction("setModel") { public void map() { ((JList)getSource()).setModel(listModel); }});} /**Maps JList.setPrototypeCellValue(Object) through queue*/ public void setPrototypeCellValue(final Object object) { runMapping(new MapVoidAction("setPrototypeCellValue") { public void map() { ((JList)getSource()).setPrototypeCellValue(object); }});} /**Maps JList.setSelectedIndex(int) through queue*/ public void setSelectedIndex(final int i) { runMapping(new MapVoidAction("setSelectedIndex") { public void map() { ((JList)getSource()).setSelectedIndex(i); }});} /**Maps JList.setSelectedIndices(int[]) through queue*/ public void setSelectedIndices(final int[] i) { runMapping(new MapVoidAction("setSelectedIndices") { public void map() { ((JList)getSource()).setSelectedIndices(i); }});} /**Maps JList.setSelectedValue(Object, boolean) through queue*/ public void setSelectedValue(final Object object, final boolean b) { runMapping(new MapVoidAction("setSelectedValue") { public void map() { ((JList)getSource()).setSelectedValue(object, b); }});} /**Maps JList.setSelectionBackground(Color) through queue*/ public void setSelectionBackground(final Color color) { runMapping(new MapVoidAction("setSelectionBackground") { public void map() { ((JList)getSource()).setSelectionBackground(color); }});} /**Maps JList.setSelectionForeground(Color) through queue*/ public void setSelectionForeground(final Color color) { runMapping(new MapVoidAction("setSelectionForeground") { public void map() { ((JList)getSource()).setSelectionForeground(color); }});} /**Maps JList.setSelectionInterval(int, int) through queue*/ public void setSelectionInterval(final int i, final int i1) { runMapping(new MapVoidAction("setSelectionInterval") { public void map() { ((JList)getSource()).setSelectionInterval(i, i1); }});} /**Maps JList.setSelectionMode(int) through queue*/ public void setSelectionMode(final int i) { runMapping(new MapVoidAction("setSelectionMode") { public void map() { ((JList)getSource()).setSelectionMode(i); }});} /**Maps JList.setSelectionModel(ListSelectionModel) through queue*/ public void setSelectionModel(final ListSelectionModel listSelectionModel) { runMapping(new MapVoidAction("setSelectionModel") { public void map() { ((JList)getSource()).setSelectionModel(listSelectionModel); }});} /**Maps JList.setUI(ListUI) through queue*/ public void setUI(final ListUI listUI) { runMapping(new MapVoidAction("setUI") { public void map() { ((JList)getSource()).setUI(listUI); }});} /**Maps JList.setValueIsAdjusting(boolean) through queue*/ public void setValueIsAdjusting(final boolean b) { runMapping(new MapVoidAction("setValueIsAdjusting") { public void map() { ((JList)getSource()).setValueIsAdjusting(b); }});} /**Maps JList.setVisibleRowCount(int) through queue*/ public void setVisibleRowCount(final int i) { runMapping(new MapVoidAction("setVisibleRowCount") { public void map() { ((JList)getSource()).setVisibleRowCount(i); }});} //End of mapping // //////////////////////////////////////////////////////// private void checkIndex(int index) { if(index < 0 || index >= getModel().getSize()) { throw(new NoSuchItemException(index)); } } private void checkIndices(int[] indices) { for(int i = 0; i < indices.length; i++) { checkIndex(indices[i]); } } /** * Iterface to choose list item. */ public interface ListItemChooser { /** * Should be true if item is good. * @param oper Operator used to search item. * @param index Index of an item be checked. * @return true if the item fits the criteria */ public boolean checkItem(JListOperator oper, int index); /** * Item description. * @return a description. */ public String getDescription(); } /** * Can be throught during item selecting if list does not have * item requested. */ public class NoSuchItemException extends JemmyInputException { /** * Constructor. * @param item an item's text */ public NoSuchItemException(String item) { super("No such item as \"" + item + "\"", getSource()); } /** * Constructor. * @param index an item's index */ public NoSuchItemException(int index) { super("List does not contain " + index + "'th item", getSource()); } } private class BySubStringListItemChooser implements ListItemChooser { String subString; StringComparator comparator; public BySubStringListItemChooser(String subString, StringComparator comparator) { this.subString = subString; this.comparator = comparator; } public boolean checkItem(JListOperator oper, int index) { return(comparator.equals(oper.getModel().getElementAt(index).toString(), subString)); } public String getDescription() { return("Item containing \"" + subString + "\" string"); } } private class ByRenderedComponentListItemChooser implements ListItemChooser { ComponentChooser chooser; public ByRenderedComponentListItemChooser(ComponentChooser chooser) { this.chooser = chooser; } public boolean checkItem(JListOperator oper, int index) { return(chooser.checkComponent(oper.getRenderedComponent(index))); } public String getDescription() { return(chooser.getDescription()); } } /** * Allows to find component by an item. */ public static class JListByItemFinder implements ComponentChooser { String label; int itemIndex; StringComparator comparator; /** * Constructs JListByItemFinder. * @param lb a text pattern * @param ii item index to check. If equal to -1, selected item is checked. * @param comparator specifies string comparision algorithm. */ public JListByItemFinder(String lb, int ii, StringComparator comparator) { label = lb; itemIndex = ii; this.comparator = comparator; } /** * Constructs JListByItemFinder. * @param lb a text pattern * @param ii item index to check. If equal to -1, selected item is checked. */ public JListByItemFinder(String lb, int ii) { this(lb, ii, Operator.getDefaultStringComparator()); } public boolean checkComponent(Component comp) { if(comp instanceof JList) { if(label == null) { return(true); } if(((JList)comp).getModel().getSize() > itemIndex) { int ii = itemIndex; if(ii == -1) { ii = ((JList)comp).getSelectedIndex(); if(ii == -1) { return(false); } } return(comparator.equals(((JList)comp).getModel().getElementAt(ii).toString(), label)); } } return(false); } public String getDescription() { return("JList with text \"" + label + "\" in " + (new Integer(itemIndex)).toString() + "'th item"); } } /** * Checks component type. */ public static class JListFinder extends Finder { /** * Constructs JListFinder. * @param sf other searching criteria. */ public JListFinder(ComponentChooser sf) { super(JList.class, sf); } /** * Constructs JListFinder. */ public JListFinder() { super(JList.class); } } } Jemmy2/src/org/netbeans/jemmy/operators/ComponentOperator.java0000644000175000017500000017725311245712447023650 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.operators; import java.awt.AWTEvent; import java.awt.Color; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import java.awt.MenuComponent; import java.awt.Point; import java.awt.PopupMenu; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Window; import java.awt.dnd.DropTarget; import java.awt.event.ComponentListener; import java.awt.event.FocusListener; import java.awt.event.InputMethodListener; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.im.InputContext; import java.awt.im.InputMethodRequests; import java.awt.image.ColorModel; import java.awt.image.ImageObserver; import java.awt.image.ImageProducer; import java.beans.PropertyChangeListener; import java.io.PrintStream; import java.io.PrintWriter; import java.util.Hashtable; import java.util.Locale; import org.netbeans.jemmy.CharBindingMap; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.ComponentSearcher; import org.netbeans.jemmy.EventDispatcher; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.TimeoutExpiredException; import org.netbeans.jemmy.Timeoutable; import org.netbeans.jemmy.Timeouts; import org.netbeans.jemmy.Waitable; import org.netbeans.jemmy.Waiter; import org.netbeans.jemmy.drivers.DriverManager; import org.netbeans.jemmy.drivers.FocusDriver; import org.netbeans.jemmy.drivers.KeyDriver; import org.netbeans.jemmy.drivers.MouseDriver; /** * Root class for all component operators. * * Provides basic methods to operate with mouse and keyboard.
*
* Almost all input methods can throw JemmyInputException or its subclass.
* * ComponentOperator and its subclasses has a lot of methods which name and parameters just like * consistent component has. In this case operator class just invokes consistent component method * through AWT Event Queue (invokeAndWait method). * *

Timeouts used:
* ComponentOperator.PushKeyTimeout - time between key pressing and releasing
* ComponentOperator.MouseClickTimeout - time between mouse pressing and releasing
* ComponentOperator.WaitComponentTimeout - time to wait component displayed
* ComponentOperator.WaitComponentEnabledTimeout - time to wait component enabled
* ComponentOperator.BeforeDragTimeout - time to sleep before grag'n'drop operations
* ComponentOperator.AfterDragTimeout - time to sleep after grag'n'drop operations
* ComponentOperator.WaitFocusTimeout - time to wait component focus
* ComponentOperator.WaitStateTimeout- time to wait component to be in some state. * Typically used from methods like Operator.wait"something happened"(*)
. * * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class ComponentOperator extends Operator implements Timeoutable, Outputable { /** * Identifier for a name property. * @see #getDump */ public static final String NAME_DPROP = "Name:"; /** * Identifier for a visible property. * @see #getDump */ public static final String IS_VISIBLE_DPROP = "Visible"; /** * Identifier for a showing property. * @see #getDump */ public static final String IS_SHOWING_DPROP = "Showing"; /** * Identifier for a x coordinate property. * @see #getDump */ public static final String X_DPROP = "X"; /** * Identifier for a y coordinate property. * @see #getDump */ public static final String Y_DPROP = "Y"; /** * Identifier for a width property. * @see #getDump */ public static final String WIDTH_DPROP = "Width"; /** * Identifier for a height property. * @see #getDump */ public static final String HEIGHT_DPROP = "Height"; private final static long PUSH_KEY_TIMEOUT = 0; private final static long MOUSE_CLICK_TIMEOUT = 0; private final static long BEFORE_DRAG_TIMEOUT = 0; private final static long AFTER_DRAG_TIMEOUT = 0; private final static long WAIT_COMPONENT_TIMEOUT = 60000; private final static long WAIT_COMPONENT_ENABLED_TIMEOUT = 60000; private final static long WAIT_FOCUS_TIMEOUT = 60000; private final static long WAIT_STATE_TIMEOUT = 60000; private Component source; private Timeouts timeouts; private TestOut output; private EventDispatcher dispatcher; private KeyDriver kDriver; private MouseDriver mDriver; private FocusDriver fDriver; /** * Constructor. * @param comp a component */ public ComponentOperator(Component comp) { super(); source = comp; kDriver = DriverManager.getKeyDriver(getClass()); mDriver = DriverManager.getMouseDriver(getClass()); fDriver = DriverManager.getFocusDriver(getClass()); setEventDispatcher(new EventDispatcher(comp)); } /** * Constructs a ComponentOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. * @param index an index between appropriate ones. */ public ComponentOperator(ContainerOperator cont, ComponentChooser chooser, int index) { this(waitComponent((Container)cont.getSource(), chooser, index, cont.getTimeouts(), cont.getOutput())); copyEnvironment(cont); } /** * Constructs a ComponentOperator object. * @param cont container * @param chooser a component chooser specifying searching criteria. */ public ComponentOperator(ContainerOperator cont, ComponentChooser chooser) { this(cont, chooser, 0); } /** * Constructor. * Waits for a component in a container to show. The component is * iis the index+1'th java.awt.Component * that shows and that lies below the container in the display * containment hierarchy. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator for a java.awt.Container. * @param index an index between appropriate ones. * @throws TimeoutExpiredException */ public ComponentOperator(ContainerOperator cont, int index) { this(cont, ComponentSearcher.getTrueChooser("Any component"), index); } /** * Constructor. * Waits for a component in a container to show. The component is * is the first java.awt.Component * that shows and that lies below the container in the display * containment hierarchy. * Uses cont's timeout and output for waiting and to init operator. * @param cont Operator for a java.awt.Container. * @throws TimeoutExpiredException */ public ComponentOperator(ContainerOperator cont) { this(cont, 0); } /** * Searches Component in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return Component instance or null if component was not found. */ public static Component findComponent(Container cont, ComponentChooser chooser, int index) { return(findComponent(cont, chooser, index, false)); } /** * Searches Component in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return Component instance or null if component was not found. */ public static Component findComponent(Container cont, ComponentChooser chooser) { return(findComponent(cont, chooser, 0)); } /** * Waits Component in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return Component instance or null if component was not found. * @throws TimeoutExpiredException */ public static Component waitComponent(Container cont, ComponentChooser chooser, int index) { return(waitComponent(cont, chooser, index, JemmyProperties.getCurrentTimeouts(), JemmyProperties.getCurrentOutput())); } /** * Waits Component in container. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @return Component instance or null if component was not found. * @throws TimeoutExpiredException */ public static Component waitComponent(Container cont, ComponentChooser chooser) { return(waitComponent(cont, chooser, 0)); } /** * A method to be used from subclasses. * Uses contOper's timeouts and output during the waiting. * @param contOper Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @return Component instance or null if component was not found. * @throws TimeoutExpiredException */ protected static Component waitComponent(ContainerOperator contOper, ComponentChooser chooser, int index) { return(waitComponent((Container)contOper.getSource(), chooser, index, contOper.getTimeouts(), contOper.getOutput())); } /** * A method to be used from subclasses. * Uses timeouts and output passed as parameters during the waiting. * @param cont Container to search component in. * @param chooser org.netbeans.jemmy.ComponentChooser implementation. * @param index Ordinal component index. * @param timeouts timeouts to be used during the waiting. * @param output an output to be used during the waiting. * @return Component instance or null if component was not found. * @throws TimeoutExpiredException */ protected static Component waitComponent(final Container cont, final ComponentChooser chooser, final int index, Timeouts timeouts, final TestOut output) { try { Waiter waiter = new Waiter(new Waitable() { public Object actionProduced(Object obj) { return(findComponent(cont, new VisibleComponentFinder(chooser), index, output.createErrorOutput())); } public String getDescription() { return("Wait " + chooser.getDescription() + " loaded"); } }); waiter.setTimeoutsToCloneOf(timeouts, "ComponentOperator.WaitComponentTimeout"); waiter.setOutput(output); return((Component)waiter.waitAction(null)); } catch(InterruptedException e) { return(null); } } private static Component findComponent(Container cont, ComponentChooser chooser, int index, TestOut output) { ComponentSearcher searcher= new ComponentSearcher(cont); searcher.setOutput(output); return(searcher.findComponent(new VisibleComponentFinder(chooser), index)); } private static Component findComponent(Container cont, ComponentChooser chooser, int index, boolean supressOutout) { return(findComponent(cont, chooser, index, JemmyProperties.getCurrentOutput().createErrorOutput())); } static { Timeouts.initDefault("ComponentOperator.PushKeyTimeout", PUSH_KEY_TIMEOUT); Timeouts.initDefault("ComponentOperator.MouseClickTimeout", MOUSE_CLICK_TIMEOUT); Timeouts.initDefault("ComponentOperator.BeforeDragTimeout", BEFORE_DRAG_TIMEOUT); Timeouts.initDefault("ComponentOperator.AfterDragTimeout", AFTER_DRAG_TIMEOUT); Timeouts.initDefault("ComponentOperator.WaitComponentTimeout", WAIT_COMPONENT_TIMEOUT); Timeouts.initDefault("ComponentOperator.WaitComponentEnabledTimeout", WAIT_COMPONENT_ENABLED_TIMEOUT); Timeouts.initDefault("ComponentOperator.WaitStateTimeout", WAIT_STATE_TIMEOUT); Timeouts.initDefault("ComponentOperator.WaitFocusTimeout", WAIT_FOCUS_TIMEOUT); } /** * Returns component. */ public Component getSource() { return(source); } /** * Returnes org.netbeans.jemmy.EventDispatcher instance which is * used to dispatch events. * @return the dispatcher. * @see org.netbeans.jemmy.EventDispatcher */ public EventDispatcher getEventDispatcher() { return(dispatcher); } //////////////////////////////////////////////////////// //Environment // //////////////////////////////////////////////////////// public void setOutput(TestOut out) { super.setOutput(out); this.output = out; if(dispatcher != null) { dispatcher.setOutput(output.createErrorOutput()); } } public TestOut getOutput() { return(output); } public void setTimeouts(Timeouts timeouts) { super.setTimeouts(timeouts); this.timeouts = timeouts; if(dispatcher != null) { dispatcher.setTimeouts(getTimeouts()); } } public Timeouts getTimeouts() { return(timeouts); } public void copyEnvironment(Operator anotherOperator) { super.copyEnvironment(anotherOperator); kDriver = (KeyDriver)DriverManager. getDriver(DriverManager.KEY_DRIVER_ID, getClass(), anotherOperator.getProperties()); mDriver = (MouseDriver)DriverManager. getDriver(DriverManager.MOUSE_DRIVER_ID, getClass(), anotherOperator.getProperties()); } //////////////////////////////////////////////////////// //Mouse operations //////////////////////////////////////////////////////// /** * Makes mouse click. * @param x Horizontal click coordinate * @param y Vertical click coordinate * @param clickCount Click count * @param mouseButton Mouse button (InputEvent.BUTTON1/2/3_MASK value) * @param modifiers Modifiers (combination of InputEvent.*_MASK values) * @param forPopup signals that click is intended to call popup. */ public void clickMouse(final int x, final int y, final int clickCount, final int mouseButton, final int modifiers, final boolean forPopup) { getQueueTool().invokeSmoothly(new QueueTool.QueueAction("Path selecting") { public Object launch() { mDriver.clickMouse(ComponentOperator.this, x, y, clickCount, mouseButton, modifiers, timeouts.create("ComponentOperator.MouseClickTimeout")); return(null); } }); } /** * Makes mouse click. * @param x Horizontal click coordinate * @param y Vertical click coordinate * @param clickCount Click count * @param mouseButton Mouse button (InputEvent.BUTTON1/2/3_MASK value) * @param modifiers Modifiers (combination of InputEvent.*_MASK values) * @see #clickMouse(int, int, int, int, int, boolean) */ public void clickMouse(int x, int y, int clickCount, int mouseButton, int modifiers) { clickMouse(x, y, clickCount, mouseButton, modifiers, false); } /** * Makes mouse click with 0 modifiers. * @param x Horizontal click coordinate * @param y Vertical click coordinate * @param clickCount Click count * @param mouseButton Mouse button (InputEvent.BUTTON1/2/3_MASK value) * @see #clickMouse(int, int, int, int, int) */ public void clickMouse(int x, int y, int clickCount, int mouseButton) { clickMouse(x, y, clickCount, mouseButton, 0); } /** * Makes mouse click by default mouse button with 0 modifiers. * @param x Horizontal click coordinate * @param y Vertical click coordinate * @param clickCount Click count * @see #clickMouse(int, int, int, int) * @see #getDefaultMouseButton() */ public void clickMouse(int x, int y, int clickCount) { clickMouse(x, y, clickCount, getDefaultMouseButton()); } /** * Press mouse. * @param x Horizontal click coordinate * @param y Vertical click coordinate */ public void pressMouse(int x, int y) { mDriver.pressMouse(this, x, y, getDefaultMouseButton(), 0); } /** * Releases mouse. * @param x Horizontal click coordinate * @param y Vertical click coordinate */ public void releaseMouse(int x, int y) { mDriver.releaseMouse(this, x, y, getDefaultMouseButton(), 0); } /** * Move mouse over the component. * @param x Horisontal destination coordinate. * @param y Vertical destination coordinate. */ public void moveMouse(int x, int y) { mDriver.moveMouse(this, x, y); } /** * Drag mouse over the component. * @param x Horisontal destination coordinate. * @param y Vertical destination coordinate. * @param mouseButton Mouse button * @param modifiers Modifiers */ public void dragMouse(int x, int y, int mouseButton, int modifiers) { mDriver.dragMouse(this, x, y, getDefaultMouseButton(), 0); } /** * Drag mouse over the component with 0 modifiers. * @param x Horisontal destination coordinate. * @param y Vertical destination coordinate. * @param mouseButton Mouse button * @see #dragMouse(int, int, int, int) */ public void dragMouse(int x, int y, int mouseButton) { dragMouse(x, y, mouseButton, 0); } /** * Drag mouse over the component with 0 modifiers and default mose button pressed. * @param x Horisontal destination coordinate. * @param y Vertical destination coordinate. * @see #dragMouse(int, int, int) * @see #getDefaultMouseButton() */ public void dragMouse(int x, int y) { dragMouse(x, y, getDefaultMouseButton()); } /** * Makes drag'n'drop operation. * @param start_x Start horizontal coordinate * @param start_y Start vertical coordinate * @param end_x End horizontal coordinate * @param end_y End vertical coordinate * @param mouseButton Mouse button * @param modifiers Modifiers */ public void dragNDrop(int start_x, int start_y, int end_x, int end_y, int mouseButton, int modifiers) { mDriver.dragNDrop(this, start_x, start_y, end_x, end_y, mouseButton, modifiers, timeouts.create("ComponentOperator.BeforeDragTimeout"), timeouts.create("ComponentOperator.AfterDragTimeout")); } /** * Makes drag'n'drop operation with 0 modifiers. * @param start_x Start horizontal coordinate * @param start_y Start vertical coordinate * @param end_x End horizontal coordinate * @param end_y End vertical coordinate * @param mouseButton Mouse button * @see #dragNDrop(int, int, int, int, int, int) */ public void dragNDrop(int start_x, int start_y, int end_x, int end_y, int mouseButton) { dragNDrop(start_x, start_y, end_x, end_y, mouseButton, 0); } /** * Makes drag'n'drop operation by default mouse buttons with 0 modifiers. * @param start_x Start horizontal coordinate * @param start_y Start vertical coordinate * @param end_x End horizontal coordinate * @param end_y End vertical coordinate * @see #dragNDrop(int, int, int, int, int) * @see #getDefaultMouseButton() */ public void dragNDrop(int start_x, int start_y, int end_x, int end_y) { dragNDrop(start_x, start_y, end_x, end_y, getDefaultMouseButton(), 0); } /** * Clicks for popup. * @param x Horizontal click coordinate. * @param y Vertical click coordinate. * @param mouseButton Mouse button. * @see #clickMouse(int, int, int, int, int, boolean) */ public void clickForPopup(int x, int y, int mouseButton) { makeComponentVisible(); clickMouse(x, y, 1, mouseButton, 0, true); } /** * Clicks for popup by popup mouse button. * @param x Horizontal click coordinate. * @param y Vertical click coordinate. * @see #clickForPopup(int, int, int) * @see #getPopupMouseButton() */ public void clickForPopup(int x, int y) { clickForPopup(x, y, getPopupMouseButton()); } /** * Makes mouse click on the component center with 0 modifiers. * @param clickCount Click count * @param mouseButton Mouse button (InputEvent.BUTTON1/2/3_MASK value) * @see #clickMouse(int, int, int, int) */ public void clickMouse(final int clickCount, final int mouseButton) { getQueueTool().invokeSmoothly(new QueueTool.QueueAction("Choise expanding") { public Object launch() { clickMouse(getCenterXForClick(), getCenterYForClick(), clickCount, mouseButton); return(null); } }); } /** * Makes mouse click on the component center by default mouse button with 0 modifiers. * @param clickCount Click count * @see #clickMouse(int, int) * @see #getDefaultMouseButton() */ public void clickMouse(int clickCount) { clickMouse(clickCount, getDefaultMouseButton()); } /** * Makes siple mouse click on the component center by default mouse button with 0 modifiers. * @see #clickMouse(int) * @see #getDefaultMouseButton() */ public void clickMouse() { clickMouse(1); } /** * Move mouse inside the component. */ public void enterMouse() { mDriver.enterMouse(this); } /** * Move mouse outside the component. */ public void exitMouse() { mDriver.exitMouse(this); } /** * Press mouse. */ public void pressMouse() { getQueueTool().invokeSmoothly(new QueueTool.QueueAction("Choise expanding") { public Object launch() { pressMouse(getCenterXForClick(), getCenterYForClick()); return(null); } }); } /** * Releases mouse. */ public void releaseMouse() { getQueueTool().invokeSmoothly(new QueueTool.QueueAction("Choise expanding") { public Object launch() { releaseMouse(getCenterXForClick(), getCenterYForClick()); return(null); } }); } /** * Clicks for popup at the component center. * @param mouseButton Mouse button. * @see #clickForPopup(int, int) */ public void clickForPopup(int mouseButton) { clickForPopup(getCenterXForClick(), getCenterYForClick(), mouseButton); } /** * Clicks for popup by popup mouse button at the component center. * @see #clickForPopup(int) * @see #getPopupMouseButton() */ public void clickForPopup() { clickForPopup(getPopupMouseButton()); } //////////////////////////////////////////////////////// //Keyboard operations //////////////////////////////////////////////////////// /** * Press key. * @param keyCode Key code (KeyEvent.VK_* value) * @param modifiers Modifiers (combination of InputEvent.*_MASK fields) */ public void pressKey(int keyCode, int modifiers) { kDriver.pressKey(this, keyCode, modifiers); } /** * Press key with no modifiers. * @param keyCode Key code (KeyEvent.VK_* value) */ public void pressKey(int keyCode) { pressKey(keyCode, 0); } /** * Releases key. * @param keyCode Key code (KeyEvent.VK_* value) * @param modifiers Modifiers (combination of InputEvent.*_MASK fields) */ public void releaseKey(int keyCode, int modifiers) { kDriver.releaseKey(this, keyCode, modifiers); } /** * Releases key with no modifiers. * @param keyCode Key code (KeyEvent.VK_* value) */ public void releaseKey(int keyCode) { releaseKey(keyCode, 0); } /** * Pushs key. * @param keyCode Key code (KeyEvent.VK_* value) * @param modifiers Modifiers (combination of InputEvent.*_MASK fields) */ public void pushKey(int keyCode, int modifiers) { kDriver.pushKey(this, keyCode, modifiers, timeouts.create("ComponentOperator.PushKeyTimeout")); } /** * Pushs key. * @param keyCode Key code (KeyEvent.VK_* value) */ public void pushKey(int keyCode) { pushKey(keyCode, 0); } /** * Types one char. * @param keyCode Key code (KeyEvent.VK_* value) * @param keyChar Char to be typed. * @param modifiers Modifiers (combination of InputEvent.*_MASK fields) */ public void typeKey(int keyCode, char keyChar, int modifiers) { kDriver.typeKey(this, keyCode, keyChar, modifiers, timeouts.create("ComponentOperator.PushKeyTimeout")); } /** * Types one char. * Uses map defined by setCharBindingMap(CharBindingMap) method to find a key should be pressed. * @param keyChar Char to be typed. * @param modifiers Modifiers (combination of InputEvent.*_MASK fields) * @see org.netbeans.jemmy.CharBindingMap * @see #setCharBindingMap(CharBindingMap) * @see #typeKey(int, char, int) */ public void typeKey(char keyChar, int modifiers) { typeKey(getCharKey(keyChar), keyChar, modifiers | getCharModifiers(keyChar)); } /** * Types one char. * Uses map defined by setCharBindingMap(CharBindingMap) method * to find a key and modifiers should be pressed. * @param keyChar Char to be typed. * @see #setCharBindingMap(CharBindingMap) * @see #typeKey(char, int) */ public void typeKey(char keyChar) { typeKey(keyChar, 0); } //////////////////////////////////////////////////////// //Util //////////////////////////////////////////////////////// /** * Activates component's window. * @deprecated Use makeComponentVisible() instead. * @see #makeComponentVisible() */ public void activateWindow() { getVisualizer().makeVisible((ComponentOperator)this); } /** * Prepares component for user input. * Uses visualizer defined by setVisualiser() method. */ public void makeComponentVisible() { getVisualizer().makeVisible((ComponentOperator)this); /* final ComponentOperator compOper = (ComponentOperator)this; runMapping(new MapVoidAction("add") { public void map() { getVisualizer().makeVisible(compOper); } }); */ } /** * Gives input focus to the component. */ public void getFocus() { fDriver.giveFocus(this); } /** * Return the center x coordinate. * @return the center x coordinate. */ public int getCenterX() { return(getWidth() / 2); } /** * Return the center y coordinate. * @return the center y coordinate. */ public int getCenterY() { return(getHeight() / 2); } /** * Return the x coordinate which should be used * for mouse operations by default. * @return the center x coordinate of the visible component part. */ public int getCenterXForClick() { return(getCenterX()); } /** * Return the y coordinate which should be used * for mouse operations by default. * @return the center y coordinate of the visible component part. */ public int getCenterYForClick() { return(getCenterY()); } /** * Waits for the component to be enabled. * @throws TimeoutExpiredException * @throws InterruptedException */ public void waitComponentEnabled() throws InterruptedException{ Waiter waiter = new Waiter(new Waitable() { public Object actionProduced(Object obj) { if(((Component)obj).isEnabled()) { return(obj); } else { return(null); } } public String getDescription() { return("Component enabled: " + getSource().getClass().toString()); } }); waiter.setOutput(output); waiter.setTimeoutsToCloneOf(timeouts, "ComponentOperator.WaitComponentEnabledTimeout"); waiter.waitAction(getSource()); } /** * Waits for the component to be enabled. * per request: 37831 * @throws TimeoutExpiredException */ public void wtComponentEnabled() { try { waitComponentEnabled(); } catch(InterruptedException e) { throw(new JemmyException("Interrupted!", e)); } } /** * Returns an array of containers for this component. * @return an array of containers */ public Container[] getContainers() { int counter = 0; Container cont = getSource().getParent(); if(cont == null) { return(new Container[0]); } do { counter++; } while((cont = cont.getParent()) != null); Container[] res = new Container[counter]; cont = getSource().getParent(); counter = 0; do { counter++; res[counter - 1] = cont; } while((cont = cont.getParent()) != null); return(res); } /** * Searches a container. * @param chooser a chooser specifying the searching criteria. * @return a containers specified by searching criteria. */ public Container getContainer(ComponentChooser chooser) { int counter = 0; Container cont = getSource().getParent(); if(cont == null) { return(null); } do { if(chooser.checkComponent(cont)) { return(cont); } counter++; } while((cont = cont.getParent()) != null); return(null); } /** * Searches the window under component. * @return the component window. */ public Window getWindow() { if(getSource() instanceof Window) { return((Window)getSource()); } Window window = (Window)getContainer(new ComponentChooser() { public boolean checkComponent(Component comp) { return(comp instanceof Window); } public String getDescription() { return(""); } }); if(window == null && getSource() instanceof Window) { return((Window)getSource()); } else { return(window); } } /** * Waits for this Component has the keyboard focus. * @throws TimeoutExpiredException */ public void waitHasFocus() { Waiter focusWaiter = new Waiter(new Waitable() { public Object actionProduced(Object obj) { return(hasFocus() ? "" : null); } public String getDescription() { return("Wait component has focus"); } }); focusWaiter.setTimeoutsToCloneOf(timeouts, "ComponentOperator.WaitFocusTimeout"); focusWaiter.setOutput(output.createErrorOutput()); try { focusWaiter.waitAction(null); } catch(InterruptedException e) { output.printStackTrace(e); } } /** * Waits for the component to be visible or unvisible. * @param visibility required visiblity. * @throws TimeoutExpiredException */ public void waitComponentVisible(final boolean visibility) { waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(isVisible() == visibility); } public String getDescription() { return("Component is " + (visibility ? "" : " not ") + "visible"); } }); } public void waitComponentShowing(final boolean visibility) { waitState(new ComponentChooser() { public boolean checkComponent(Component comp) { return(isShowing() == visibility); } public String getDescription() { return("Component is " + (visibility ? "" : " not ") + "showing"); } }); } /** * Returns information about component. */ public Hashtable getDump() { Hashtable result = super.getDump(); if(getSource().getName() != null) { result.put(NAME_DPROP, getSource().getName()); } result.put(IS_VISIBLE_DPROP, getSource().isVisible() ? "true" : "false"); result.put(IS_SHOWING_DPROP, getSource().isShowing() ? "true" : "false"); result.put(X_DPROP, Integer.toString(getSource().getX())); result.put(Y_DPROP, Integer.toString(getSource().getY())); result.put(WIDTH_DPROP, Integer.toString(getSource().getWidth())); result.put(HEIGHT_DPROP, Integer.toString(getSource().getHeight())); return(result); } //////////////////////////////////////////////////////// //Mapping // /**Maps Component.add(PopupMenu) through queue*/ public void add(final PopupMenu popupMenu) { runMapping(new MapVoidAction("add") { public void map() { ((Component)getSource()).add(popupMenu); }});} /**Maps Component.addComponentListener(ComponentListener) through queue*/ public void addComponentListener(final ComponentListener componentListener) { runMapping(new MapVoidAction("addComponentListener") { public void map() { ((Component)getSource()).addComponentListener(componentListener); }});} /**Maps Component.addFocusListener(FocusListener) through queue*/ public void addFocusListener(final FocusListener focusListener) { runMapping(new MapVoidAction("addFocusListener") { public void map() { ((Component)getSource()).addFocusListener(focusListener); }});} /**Maps Component.addInputMethodListener(InputMethodListener) through queue*/ public void addInputMethodListener(final InputMethodListener inputMethodListener) { runMapping(new MapVoidAction("addInputMethodListener") { public void map() { ((Component)getSource()).addInputMethodListener(inputMethodListener); }});} /**Maps Component.addKeyListener(KeyListener) through queue*/ public void addKeyListener(final KeyListener keyListener) { runMapping(new MapVoidAction("addKeyListener") { public void map() { ((Component)getSource()).addKeyListener(keyListener); }});} /**Maps Component.addMouseListener(MouseListener) through queue*/ public void addMouseListener(final MouseListener mouseListener) { runMapping(new MapVoidAction("addMouseListener") { public void map() { ((Component)getSource()).addMouseListener(mouseListener); }});} /**Maps Component.addMouseMotionListener(MouseMotionListener) through queue*/ public void addMouseMotionListener(final MouseMotionListener mouseMotionListener) { runMapping(new MapVoidAction("addMouseMotionListener") { public void map() { ((Component)getSource()).addMouseMotionListener(mouseMotionListener); }});} /**Maps Component.addNotify() through queue*/ public void addNotify() { runMapping(new MapVoidAction("addNotify") { public void map() { ((Component)getSource()).addNotify(); }});} /**Maps Component.addPropertyChangeListener(PropertyChangeListener) through queue*/ public void addPropertyChangeListener(final PropertyChangeListener propertyChangeListener) { runMapping(new MapVoidAction("addPropertyChangeListener") { public void map() { ((Component)getSource()).addPropertyChangeListener(propertyChangeListener); }});} /**Maps Component.addPropertyChangeListener(String, PropertyChangeListener) through queue*/ public void addPropertyChangeListener(final String string, final PropertyChangeListener propertyChangeListener) { runMapping(new MapVoidAction("addPropertyChangeListener") { public void map() { ((Component)getSource()).addPropertyChangeListener(string, propertyChangeListener); }});} /**Maps Component.checkImage(Image, int, int, ImageObserver) through queue*/ public int checkImage(final Image image, final int i, final int i1, final ImageObserver imageObserver) { return(runMapping(new MapIntegerAction("checkImage") { public int map() { return(((Component)getSource()).checkImage(image, i, i1, imageObserver)); }}));} /**Maps Component.checkImage(Image, ImageObserver) through queue*/ public int checkImage(final Image image, final ImageObserver imageObserver) { return(runMapping(new MapIntegerAction("checkImage") { public int map() { return(((Component)getSource()).checkImage(image, imageObserver)); }}));} /**Maps Component.contains(int, int) through queue*/ public boolean contains(final int i, final int i1) { return(runMapping(new MapBooleanAction("contains") { public boolean map() { return(((Component)getSource()).contains(i, i1)); }}));} /**Maps Component.contains(Point) through queue*/ public boolean contains(final Point point) { return(runMapping(new MapBooleanAction("contains") { public boolean map() { return(((Component)getSource()).contains(point)); }}));} /**Maps Component.createImage(int, int) through queue*/ public Image createImage(final int i, final int i1) { return((Image)runMapping(new MapAction("createImage") { public Object map() { return(((Component)getSource()).createImage(i, i1)); }}));} /**Maps Component.createImage(ImageProducer) through queue*/ public Image createImage(final ImageProducer imageProducer) { return((Image)runMapping(new MapAction("createImage") { public Object map() { return(((Component)getSource()).createImage(imageProducer)); }}));} /**Maps Component.dispatchEvent(AWTEvent) through queue*/ public void dispatchEvent(final AWTEvent aWTEvent) { runMapping(new MapVoidAction("dispatchEvent") { public void map() { ((Component)getSource()).dispatchEvent(aWTEvent); }});} /**Maps Component.doLayout() through queue*/ public void doLayout() { runMapping(new MapVoidAction("doLayout") { public void map() { ((Component)getSource()).doLayout(); }});} /**Maps Component.enableInputMethods(boolean) through queue*/ public void enableInputMethods(final boolean b) { runMapping(new MapVoidAction("enableInputMethods") { public void map() { ((Component)getSource()).enableInputMethods(b); }});} /**Maps Component.getAlignmentX() through queue*/ public float getAlignmentX() { return(runMapping(new MapFloatAction("getAlignmentX") { public float map() { return(((Component)getSource()).getAlignmentX()); }}));} /**Maps Component.getAlignmentY() through queue*/ public float getAlignmentY() { return(runMapping(new MapFloatAction("getAlignmentY") { public float map() { return(((Component)getSource()).getAlignmentY()); }}));} /**Maps Component.getBackground() through queue*/ public Color getBackground() { return((Color)runMapping(new MapAction("getBackground") { public Object map() { return(((Component)getSource()).getBackground()); }}));} /**Maps Component.getBounds() through queue*/ public Rectangle getBounds() { return((Rectangle)runMapping(new MapAction("getBounds") { public Object map() { return(((Component)getSource()).getBounds()); }}));} /**Maps Component.getBounds(Rectangle) through queue*/ public Rectangle getBounds(final Rectangle rectangle) { return((Rectangle)runMapping(new MapAction("getBounds") { public Object map() { return(((Component)getSource()).getBounds(rectangle)); }}));} /**Maps Component.getColorModel() through queue*/ public ColorModel getColorModel() { return((ColorModel)runMapping(new MapAction("getColorModel") { public Object map() { return(((Component)getSource()).getColorModel()); }}));} /**Maps Component.getComponentAt(int, int) through queue*/ public Component getComponentAt(final int i, final int i1) { return((Component)runMapping(new MapAction("getComponentAt") { public Object map() { return(((Component)getSource()).getComponentAt(i, i1)); }}));} /**Maps Component.getComponentAt(Point) through queue*/ public Component getComponentAt(final Point point) { return((Component)runMapping(new MapAction("getComponentAt") { public Object map() { return(((Component)getSource()).getComponentAt(point)); }}));} /**Maps Component.getComponentOrientation() through queue*/ public ComponentOrientation getComponentOrientation() { return((ComponentOrientation)runMapping(new MapAction("getComponentOrientation") { public Object map() { return(((Component)getSource()).getComponentOrientation()); }}));} /**Maps Component.getCursor() through queue*/ public Cursor getCursor() { return((Cursor)runMapping(new MapAction("getCursor") { public Object map() { return(((Component)getSource()).getCursor()); }}));} /**Maps Component.getDropTarget() through queue*/ public DropTarget getDropTarget() { return((DropTarget)runMapping(new MapAction("getDropTarget") { public Object map() { return(((Component)getSource()).getDropTarget()); }}));} /**Maps Component.getFont() through queue*/ public Font getFont() { return((Font)runMapping(new MapAction("getFont") { public Object map() { return(((Component)getSource()).getFont()); }}));} /**Maps Component.getFontMetrics(Font) through queue*/ public FontMetrics getFontMetrics(final Font font) { return((FontMetrics)runMapping(new MapAction("getFontMetrics") { public Object map() { return(((Component)getSource()).getFontMetrics(font)); }}));} /**Maps Component.getForeground() through queue*/ public Color getForeground() { return((Color)runMapping(new MapAction("getForeground") { public Object map() { return(((Component)getSource()).getForeground()); }}));} /**Maps Component.getGraphics() through queue*/ public Graphics getGraphics() { return((Graphics)runMapping(new MapAction("getGraphics") { public Object map() { return(((Component)getSource()).getGraphics()); }}));} /**Maps Component.getHeight() through queue*/ public int getHeight() { return(runMapping(new MapIntegerAction("getHeight") { public int map() { return(((Component)getSource()).getHeight()); }}));} /**Maps Component.getInputContext() through queue*/ public InputContext getInputContext() { return((InputContext)runMapping(new MapAction("getInputContext") { public Object map() { return(((Component)getSource()).getInputContext()); }}));} /**Maps Component.getInputMethodRequests() through queue*/ public InputMethodRequests getInputMethodRequests() { return((InputMethodRequests)runMapping(new MapAction("getInputMethodRequests") { public Object map() { return(((Component)getSource()).getInputMethodRequests()); }}));} /**Maps Component.getLocale() through queue*/ public Locale getLocale() { return((Locale)runMapping(new MapAction("getLocale") { public Object map() { return(((Component)getSource()).getLocale()); }}));} /**Maps Component.getLocation() through queue*/ public Point getLocation() { return((Point)runMapping(new MapAction("getLocation") { public Object map() { return(((Component)getSource()).getLocation()); }}));} /**Maps Component.getLocation(Point) through queue*/ public Point getLocation(final Point point) { return((Point)runMapping(new MapAction("getLocation") { public Object map() { return(((Component)getSource()).getLocation(point)); }}));} /**Maps Component.getLocationOnScreen() through queue*/ public Point getLocationOnScreen() { return((Point)runMapping(new MapAction("getLocationOnScreen") { public Object map() { return(((Component)getSource()).getLocationOnScreen()); }}));} /**Maps Component.getMaximumSize() through queue*/ public Dimension getMaximumSize() { return((Dimension)runMapping(new MapAction("getMaximumSize") { public Object map() { return(((Component)getSource()).getMaximumSize()); }}));} /**Maps Component.getMinimumSize() through queue*/ public Dimension getMinimumSize() { return((Dimension)runMapping(new MapAction("getMinimumSize") { public Object map() { return(((Component)getSource()).getMinimumSize()); }}));} /**Maps Component.getName() through queue*/ public String getName() { return((String)runMapping(new MapAction("getName") { public Object map() { return(((Component)getSource()).getName()); }}));} /**Maps Component.getParent() through queue*/ public Container getParent() { return((Container)runMapping(new MapAction("getParent") { public Object map() { return(((Component)getSource()).getParent()); }}));} /**Maps Component.getPreferredSize() through queue*/ public Dimension getPreferredSize() { return((Dimension)runMapping(new MapAction("getPreferredSize") { public Object map() { return(((Component)getSource()).getPreferredSize()); }}));} /**Maps Component.getSize() through queue*/ public Dimension getSize() { return((Dimension)runMapping(new MapAction("getSize") { public Object map() { return(((Component)getSource()).getSize()); }}));} /**Maps Component.getSize(Dimension) through queue*/ public Dimension getSize(final Dimension dimension) { return((Dimension)runMapping(new MapAction("getSize") { public Object map() { return(((Component)getSource()).getSize(dimension)); }}));} /**Maps Component.getToolkit() through queue*/ public Toolkit getToolkit() { return((Toolkit)runMapping(new MapAction("getToolkit") { public Object map() { return(((Component)getSource()).getToolkit()); }}));} /**Maps Component.getTreeLock() through queue*/ public Object getTreeLock() { return((Object)runMapping(new MapAction("getTreeLock") { public Object map() { return(((Component)getSource()).getTreeLock()); }}));} /**Maps Component.getWidth() through queue*/ public int getWidth() { return(runMapping(new MapIntegerAction("getWidth") { public int map() { return(((Component)getSource()).getWidth()); }}));} /**Maps Component.getX() through queue*/ public int getX() { return(runMapping(new MapIntegerAction("getX") { public int map() { return(((Component)getSource()).getX()); }}));} /**Maps Component.getY() through queue*/ public int getY() { return(runMapping(new MapIntegerAction("getY") { public int map() { return(((Component)getSource()).getY()); }}));} /**Maps Component.hasFocus() through queue*/ public boolean hasFocus() { return(runMapping(new MapBooleanAction("hasFocus") { public boolean map() { return(((Component)getSource()).hasFocus()); }}));} /**Maps Component.imageUpdate(Image, int, int, int, int, int) through queue*/ public boolean imageUpdate(final Image image, final int i, final int i1, final int i2, final int i3, final int i4) { return(runMapping(new MapBooleanAction("imageUpdate") { public boolean map() { return(((Component)getSource()).imageUpdate(image, i, i1, i2, i3, i4)); }}));} /**Maps Component.invalidate() through queue*/ public void invalidate() { runMapping(new MapVoidAction("invalidate") { public void map() { ((Component)getSource()).invalidate(); }});} /**Maps Component.isDisplayable() through queue*/ public boolean isDisplayable() { return(runMapping(new MapBooleanAction("isDisplayable") { public boolean map() { return(((Component)getSource()).isDisplayable()); }}));} /**Maps Component.isDoubleBuffered() through queue*/ public boolean isDoubleBuffered() { return(runMapping(new MapBooleanAction("isDoubleBuffered") { public boolean map() { return(((Component)getSource()).isDoubleBuffered()); }}));} /**Maps Component.isEnabled() through queue*/ public boolean isEnabled() { return(runMapping(new MapBooleanAction("isEnabled") { public boolean map() { return(((Component)getSource()).isEnabled()); }}));} /**Maps Component.isFocusTraversable() through queue*/ public boolean isFocusTraversable() { return(runMapping(new MapBooleanAction("isFocusTraversable") { public boolean map() { return(((Component)getSource()).isFocusTraversable()); }}));} /**Maps Component.isLightweight() through queue*/ public boolean isLightweight() { return(runMapping(new MapBooleanAction("isLightweight") { public boolean map() { return(((Component)getSource()).isLightweight()); }}));} /**Maps Component.isOpaque() through queue*/ public boolean isOpaque() { return(runMapping(new MapBooleanAction("isOpaque") { public boolean map() { return(((Component)getSource()).isOpaque()); }}));} /**Maps Component.isShowing() through queue*/ public boolean isShowing() { return(runMapping(new MapBooleanAction("isShowing") { public boolean map() { return(((Component)getSource()).isShowing()); }}));} /**Maps Component.isValid() through queue*/ public boolean isValid() { return(runMapping(new MapBooleanAction("isValid") { public boolean map() { return(((Component)getSource()).isValid()); }}));} /**Maps Component.isVisible() through queue*/ public boolean isVisible() { return(runMapping(new MapBooleanAction("isVisible") { public boolean map() { return(((Component)getSource()).isVisible()); }}));} /**Maps Component.list() through queue*/ public void list() { runMapping(new MapVoidAction("list") { public void map() { ((Component)getSource()).list(); }});} /**Maps Component.list(PrintStream) through queue*/ public void list(final PrintStream printStream) { runMapping(new MapVoidAction("list") { public void map() { ((Component)getSource()).list(printStream); }});} /**Maps Component.list(PrintStream, int) through queue*/ public void list(final PrintStream printStream, final int i) { runMapping(new MapVoidAction("list") { public void map() { ((Component)getSource()).list(printStream, i); }});} /**Maps Component.list(PrintWriter) through queue*/ public void list(final PrintWriter printWriter) { runMapping(new MapVoidAction("list") { public void map() { ((Component)getSource()).list(printWriter); }});} /**Maps Component.list(PrintWriter, int) through queue*/ public void list(final PrintWriter printWriter, final int i) { runMapping(new MapVoidAction("list") { public void map() { ((Component)getSource()).list(printWriter, i); }});} /**Maps Component.paint(Graphics) through queue*/ public void paint(final Graphics graphics) { runMapping(new MapVoidAction("paint") { public void map() { ((Component)getSource()).paint(graphics); }});} /**Maps Component.paintAll(Graphics) through queue*/ public void paintAll(final Graphics graphics) { runMapping(new MapVoidAction("paintAll") { public void map() { ((Component)getSource()).paintAll(graphics); }});} /**Maps Component.prepareImage(Image, int, int, ImageObserver) through queue*/ public boolean prepareImage(final Image image, final int i, final int i1, final ImageObserver imageObserver) { return(runMapping(new MapBooleanAction("prepareImage") { public boolean map() { return(((Component)getSource()).prepareImage(image, i, i1, imageObserver)); }}));} /**Maps Component.prepareImage(Image, ImageObserver) through queue*/ public boolean prepareImage(final Image image, final ImageObserver imageObserver) { return(runMapping(new MapBooleanAction("prepareImage") { public boolean map() { return(((Component)getSource()).prepareImage(image, imageObserver)); }}));} /**Maps Component.print(Graphics) through queue*/ public void print(final Graphics graphics) { runMapping(new MapVoidAction("print") { public void map() { ((Component)getSource()).print(graphics); }});} /**Maps Component.printAll(Graphics) through queue*/ public void printAll(final Graphics graphics) { runMapping(new MapVoidAction("printAll") { public void map() { ((Component)getSource()).printAll(graphics); }});} /**Maps Component.remove(MenuComponent) through queue*/ public void remove(final MenuComponent menuComponent) { runMapping(new MapVoidAction("remove") { public void map() { ((Component)getSource()).remove(menuComponent); }});} /**Maps Component.removeComponentListener(ComponentListener) through queue*/ public void removeComponentListener(final ComponentListener componentListener) { runMapping(new MapVoidAction("removeComponentListener") { public void map() { ((Component)getSource()).removeComponentListener(componentListener); }});} /**Maps Component.removeFocusListener(FocusListener) through queue*/ public void removeFocusListener(final FocusListener focusListener) { runMapping(new MapVoidAction("removeFocusListener") { public void map() { ((Component)getSource()).removeFocusListener(focusListener); }});} /**Maps Component.removeInputMethodListener(InputMethodListener) through queue*/ public void removeInputMethodListener(final InputMethodListener inputMethodListener) { runMapping(new MapVoidAction("removeInputMethodListener") { public void map() { ((Component)getSource()).removeInputMethodListener(inputMethodListener); }});} /**Maps Component.removeKeyListener(KeyListener) through queue*/ public void removeKeyListener(final KeyListener keyListener) { runMapping(new MapVoidAction("removeKeyListener") { public void map() { ((Component)getSource()).removeKeyListener(keyListener); }});} /**Maps Component.removeMouseListener(MouseListener) through queue*/ public void removeMouseListener(final MouseListener mouseListener) { runMapping(new MapVoidAction("removeMouseListener") { public void map() { ((Component)getSource()).removeMouseListener(mouseListener); }});} /**Maps Component.removeMouseMotionListener(MouseMotionListener) through queue*/ public void removeMouseMotionListener(final MouseMotionListener mouseMotionListener) { runMapping(new MapVoidAction("removeMouseMotionListener") { public void map() { ((Component)getSource()).removeMouseMotionListener(mouseMotionListener); }});} /**Maps Component.removeNotify() through queue*/ public void removeNotify() { runMapping(new MapVoidAction("removeNotify") { public void map() { ((Component)getSource()).removeNotify(); }});} /**Maps Component.removePropertyChangeListener(PropertyChangeListener) through queue*/ public void removePropertyChangeListener(final PropertyChangeListener propertyChangeListener) { runMapping(new MapVoidAction("removePropertyChangeListener") { public void map() { ((Component)getSource()).removePropertyChangeListener(propertyChangeListener); }});} /**Maps Component.removePropertyChangeListener(String, PropertyChangeListener) through queue*/ public void removePropertyChangeListener(final String string, final PropertyChangeListener propertyChangeListener) { runMapping(new MapVoidAction("removePropertyChangeListener") { public void map() { ((Component)getSource()).removePropertyChangeListener(string, propertyChangeListener); }});} /**Maps Component.repaint() through queue*/ public void repaint() { runMapping(new MapVoidAction("repaint") { public void map() { ((Component)getSource()).repaint(); }});} /**Maps Component.repaint(int, int, int, int) through queue*/ public void repaint(final int i, final int i1, final int i2, final int i3) { runMapping(new MapVoidAction("repaint") { public void map() { ((Component)getSource()).repaint(i, i1, i2, i3); }});} /**Maps Component.repaint(long) through queue*/ public void repaint(final long l) { runMapping(new MapVoidAction("repaint") { public void map() { ((Component)getSource()).repaint(l); }});} /**Maps Component.repaint(long, int, int, int, int) through queue*/ public void repaint(final long l, final int i, final int i1, final int i2, final int i3) { runMapping(new MapVoidAction("repaint") { public void map() { ((Component)getSource()).repaint(l, i, i1, i2, i3); }});} /**Maps Component.requestFocus() through queue*/ public void requestFocus() { runMapping(new MapVoidAction("requestFocus") { public void map() { ((Component)getSource()).requestFocus(); }});} /**Maps Component.setBackground(Color) through queue*/ public void setBackground(final Color color) { runMapping(new MapVoidAction("setBackground") { public void map() { ((Component)getSource()).setBackground(color); }});} /**Maps Component.setBounds(int, int, int, int) through queue*/ public void setBounds(final int i, final int i1, final int i2, final int i3) { runMapping(new MapVoidAction("setBounds") { public void map() { ((Component)getSource()).setBounds(i, i1, i2, i3); }});} /**Maps Component.setBounds(Rectangle) through queue*/ public void setBounds(final Rectangle rectangle) { runMapping(new MapVoidAction("setBounds") { public void map() { ((Component)getSource()).setBounds(rectangle); }});} /**Maps Component.setComponentOrientation(ComponentOrientation) through queue*/ public void setComponentOrientation(final ComponentOrientation componentOrientation) { runMapping(new MapVoidAction("setComponentOrientation") { public void map() { ((Component)getSource()).setComponentOrientation(componentOrientation); }});} /**Maps Component.setCursor(Cursor) through queue*/ public void setCursor(final Cursor cursor) { runMapping(new MapVoidAction("setCursor") { public void map() { ((Component)getSource()).setCursor(cursor); }});} /**Maps Component.setDropTarget(DropTarget) through queue*/ public void setDropTarget(final DropTarget dropTarget) { runMapping(new MapVoidAction("setDropTarget") { public void map() { ((Component)getSource()).setDropTarget(dropTarget); }});} /**Maps Component.setEnabled(boolean) through queue*/ public void setEnabled(final boolean b) { runMapping(new MapVoidAction("setEnabled") { public void map() { ((Component)getSource()).setEnabled(b); }});} /**Maps Component.setFont(Font) through queue*/ public void setFont(final Font font) { runMapping(new MapVoidAction("setFont") { public void map() { ((Component)getSource()).setFont(font); }});} /**Maps Component.setForeground(Color) through queue*/ public void setForeground(final Color color) { runMapping(new MapVoidAction("setForeground") { public void map() { ((Component)getSource()).setForeground(color); }});} /**Maps Component.setLocale(Locale) through queue*/ public void setLocale(final Locale locale) { runMapping(new MapVoidAction("setLocale") { public void map() { ((Component)getSource()).setLocale(locale); }});} /**Maps Component.setLocation(int, int) through queue*/ public void setLocation(final int i, final int i1) { runMapping(new MapVoidAction("setLocation") { public void map() { ((Component)getSource()).setLocation(i, i1); }});} /**Maps Component.setLocation(Point) through queue*/ public void setLocation(final Point point) { runMapping(new MapVoidAction("setLocation") { public void map() { ((Component)getSource()).setLocation(point); }});} /**Maps Component.setName(String) through queue*/ public void setName(final String string) { runMapping(new MapVoidAction("setName") { public void map() { ((Component)getSource()).setName(string); }});} /**Maps Component.setSize(int, int) through queue*/ public void setSize(final int i, final int i1) { runMapping(new MapVoidAction("setSize") { public void map() { ((Component)getSource()).setSize(i, i1); }});} /**Maps Component.setSize(Dimension) through queue*/ public void setSize(final Dimension dimension) { runMapping(new MapVoidAction("setSize") { public void map() { ((Component)getSource()).setSize(dimension); }});} /**Maps Component.setVisible(boolean) through queue*/ public void setVisible(final boolean b) { runMapping(new MapVoidAction("setVisible") { public void map() { ((Component)getSource()).setVisible(b); }});} /**Maps Component.transferFocus() through queue*/ public void transferFocus() { runMapping(new MapVoidAction("transferFocus") { public void map() { ((Component)getSource()).transferFocus(); }});} /**Maps Component.update(Graphics) through queue*/ public void update(final Graphics graphics) { runMapping(new MapVoidAction("update") { public void map() { ((Component)getSource()).update(graphics); }});} /**Maps Component.validate() through queue*/ public void validate() { runMapping(new MapVoidAction("validate") { public void map() { ((Component)getSource()).validate(); }});} //End of mapping // //////////////////////////////////////////////////////// private void setEventDispatcher(EventDispatcher dispatcher) { dispatcher.setOutput(getOutput().createErrorOutput()); dispatcher.setTimeouts(getTimeouts()); this.dispatcher = dispatcher; } static class VisibleComponentFinder implements ComponentChooser { ComponentChooser subFinder; public VisibleComponentFinder(ComponentChooser sf) { subFinder = sf; } public boolean checkComponent(Component comp) { if(comp.isShowing()) { return(subFinder.checkComponent(comp)); } return(false); } public String getDescription() { return(subFinder.getDescription()); } } } Jemmy2/src/org/netbeans/jemmy/ActionProducer.java0000644000175000017500000002405611245712447021065 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; /** * * Runs actions with or without waiting. * *

Timeouts used:
* ActionProducer.MaxActionTime - time action should be finished in.
* * @see Action * @see Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class ActionProducer extends Thread implements Action, Waitable, Timeoutable{ private final static long ACTION_TIMEOUT = 10000; private Action action; private boolean needWait = true; private Object parameter; private boolean finished; private Object result = null; private Timeouts timeouts; private Waiter waiter; private TestOut output; private Throwable exception; /** * Creates a producer for an action. * @param a Action implementation. */ public ActionProducer(Action a) { super(); waiter = new Waiter(this); action = a; setTimeouts(JemmyProperties.getProperties().getTimeouts()); setOutput(JemmyProperties.getProperties().getOutput()); finished = false; exception = null; } /** * Creates a producer for an action. * @param a Action implementation. * @param nw Defines if produceAction * method should wait for the end of action. */ public ActionProducer(Action a, boolean nw) { super(); waiter = new Waiter(this); action = a; needWait = nw; setTimeouts(JemmyProperties.getProperties().getTimeouts()); setOutput(JemmyProperties.getProperties().getOutput()); finished = false; exception = null; } /** * Creates a producer. * produceAction must be overridden. */ protected ActionProducer() { super(); waiter = new Waiter(this); setTimeouts(JemmyProperties.getProperties().getTimeouts()); setOutput(JemmyProperties.getProperties().getOutput()); finished = false; exception = null; } /** * Creates a producer. * produceAction must be overridden. * @param nw Defines if produceAction * method should wait for the end of action. */ protected ActionProducer(boolean nw) { super(); waiter = new Waiter(this); needWait = nw; setTimeouts(JemmyProperties.getProperties().getTimeouts()); setOutput(JemmyProperties.getProperties().getOutput()); finished = false; exception = null; } static { Timeouts.initDefault("ActionProducer.MaxActionTime", ACTION_TIMEOUT); } /** * Set all the time outs used by sleeps or waits used by the launched action. * @param ts An object containing timeout information. * @see org.netbeans.jemmy.Timeouts * @see org.netbeans.jemmy.Timeoutable * @see #getTimeouts */ public void setTimeouts(Timeouts ts) { timeouts = ts; } /** * Get all the time outs used by sleeps or waits used by the launched action. * @return an object containing information about timeouts. * @see org.netbeans.jemmy.Timeouts * @see org.netbeans.jemmy.Timeoutable * @see #setTimeouts */ public Timeouts getTimeouts() { return(timeouts); } /** * Identity of the streams or writers used for print output. * @param out An object containing print output assignments for * output and error streams. * @see org.netbeans.jemmy.TestOut * @see org.netbeans.jemmy.Outputable */ public void setOutput(TestOut out) { output = out; waiter.setOutput(output); } /** * Returns the exception value. * @return a Throwable object representing the exception value */ public Throwable getException() { return(exception); } /** * Defines action priority in terms of thread priority. * Increase (decrease) parameter value to Thread.MIN_PRIORITY(MAX_PRIORITY) * in case if it is less(more) then it. * * @param newPriority New thread priority. */ public void setActionPriority(int newPriority) { int priority; if(newPriority < Thread.MIN_PRIORITY) { priority = MIN_PRIORITY; } else if(newPriority > Thread.MAX_PRIORITY) { priority = MAX_PRIORITY; } else { priority = newPriority; } try { setPriority(priority); } catch(IllegalArgumentException e) { } catch(SecurityException e) { } } /** * Get the result of a launched action. * @return a launched action's result. * without waiting in case if getFinished() * @see #getFinished() */ public Object getResult() { return(result); } /** * Check if a launched action has finished. * @return true if the launched action has completed, * either normally or with an exception; false otherwise. */ public boolean getFinished() { synchronized(this) { return(finished); } } /** * Does nothing; the method should be overridden by inheritors. * @param obj An object used to modify execution. This might be a * java.lang.String[] that lists a test's command line * arguments. * @return An object - result of the action. * @see org.netbeans.jemmy.Action */ public Object launch(Object obj) { return(null); } /** * @return this ActionProducer's description. * @see Action */ public String getDescription() { if(action != null) { return(action.getDescription()); } else { return("Unknown action"); } } /** * Starts execution. * Uses ActionProducer.MaxActionTime timeout. * * @param obj Parameter to be passed into action's launch(Object) method. * This parameter might be a java.lang.String[] that lists a test's * command line arguments. * @return launch(Object) result. * @throws TimeoutExpiredException * @exception InterruptedException */ public Object produceAction(Object obj) throws InterruptedException{ parameter =obj; synchronized(this) { finished = false; } start(); if(needWait) { waiter.setTimeoutsToCloneOf(timeouts, "ActionProducer.MaxActionTime"); try { waiter.waitAction(null); } catch(TimeoutExpiredException e) { output.printError("Timeout for \"" + getDescription() + "\" action has been expired. Thread has been interrupted."); interrupt(); throw(e); } } return(result); } /** * Launch an action in a separate thread of execution. * When the action finishes, record that fact. If the action finishes * normally, store it's result. Use getFinished() * and getResult to answer questions about test * completion and return value, respectively. * @see #getFinished() * @see #getResult() * @see java.lang.Runnable */ public final void run() { result = null; try { result = launchAction(parameter); } catch(Throwable e) { exception = e; } synchronized(this) { finished = true; } } /** * Inquire for a reference to the object returned by a launched action. * @param obj Not used. * @return the result returned when a launched action finishes * normally. * @see org.netbeans.jemmy.Waitable */ public final Object actionProduced(Object obj) { synchronized(this) { if(finished) { if(result == null) { return(new Integer(0)); } else { return(result); } } else { return(null); } } } /** * Launch some action. * Pass the action parameters and get it's return value, too. * @param obj Parameter used to configure the execution of whatever * this ActionProducer puts into execution. * This parameter might be a java.lang.String[] that lists a * test's command line arguments. * @return the return value of the action. This might be a * java.lang.Integer wrapped around a status code. */ private Object launchAction(Object obj) { if(action != null) { return(action.launch(obj)); } else { return(launch(obj)); } } } Jemmy2/src/org/netbeans/jemmy/Test.java0000644000175000017500000003422611245712347017062 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.io.PrintStream; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; /** * * Jemmy itself provides a way to create tests. * Test should implement org.netbeans.jemmy.Scenario interface. * * Test can be executed from command line:
* java [application options] [jemmy options] org.netbeans.jemmy.Test [full name of test class] [test args]
* Test elso can be executed by one of the run(...) methods or by
* new Test([test class name]).startTest([test args]);
* *

Timeouts used:
* Test.WholeTestTimeout - time for the whole test
* * @author Alexandre Iline (alexandre.iline@sun.com) */ public class Test extends ActionProducer implements Timeoutable, Outputable, Scenario { private final static long WHOLE_TEST_TIMEOUT = 3600000; /** * Status returned by test if wrong parameter was passed. */ public static int WRONG_PARAMETERS_STATUS = 101; /** * Status returned by test if exception appeared inside scenario. */ public static int SCENARIO_EXCEPTION_STATUS = 102; /** * Positive test status. */ public static int TEST_PASSED_STATUS = 0; /** Test timeouts. */ protected Timeouts timeouts; /** Test output. */ protected TestOut output; private Scenario scenario; private static int TEST_FAILED_STATUS = 1; /** * Constructor for tests requiring only a class instance. * Creates a subclass of ActionProducer and java.lang.Thread * that runs in a separate thread of execution and waits for execution to finish. * The current output stream assignments and timeouts are used. * @param testClassName Full test class name */ public Test(String testClassName) { super(true); setOutput(JemmyProperties.getCurrentOutput()); setTimeouts(JemmyProperties.getCurrentTimeouts()); scenario = testForName(testClassName); } /** * Constructor for scenarios that require an instance and might require an argument. * Creates a subclass of ActionProducer and java.lang.Thread * that runs in a separate thread of execution and waits for execution to finish. * The current output stream assignments and timeouts are used. * @param scenario a test scenario * @see org.netbeans.jemmy.Scenario */ public Test(Scenario scenario) { super(true); setOutput(JemmyProperties.getCurrentOutput()); setTimeouts(JemmyProperties.getCurrentTimeouts()); this.scenario = scenario; } /** * No argument constructor. * Used by subclasses of this Test class. * Creates a subclass of ActionProducer and java.lang.Thread * that runs in a separate thread of execution and waits for execution to finish. * The current output stream assignments and timeouts are used. */ protected Test() { super(true); setOutput(JemmyProperties.getCurrentOutput()); setTimeouts(JemmyProperties.getCurrentTimeouts()); } /** * Throws TestCompletedException exception. * The exception thrown contains a pass/fail status and a short * status java.lang.String. * Can by invoked from test to abort test execution. * @param status If 0 - test passed, otherwise failed. * @throws TestCompletedException all of the time. */ public static void closeDown(int status) { if(status == 0) { throw(new TestCompletedException(status, "Test passed")); } else { throw(new TestCompletedException(status, "Test failed with status " + Integer.toString(status))); } } /** * Executes a test. * @param argv First element should be a test class name, * all others - test args. * @return test status. */ public static int run(String[] argv) { String[] args = argv; JemmyProperties.getProperties().init(); if(argv.length < 1) { JemmyProperties.getCurrentOutput(). printErrLine("First element of String array should be test classname"); return(WRONG_PARAMETERS_STATUS); } JemmyProperties.getCurrentOutput().printLine("Executed test " + argv[0]); Test test = new Test(argv[0]); if(argv.length >= 1) { args = shiftArray(args); } if(argv.length >= 2) { JemmyProperties.getCurrentOutput().printLine("Work directory: " + argv[1]); System.setProperty("user.dir", argv[1]); args = shiftArray(args); } int status = TEST_FAILED_STATUS; if(test != null) { status = test.startTest(args); } JemmyProperties.getCurrentOutput().flush(); return(status); } /** * Executes a test. * @param argv First element should be a test class name, * all others - test args. * @param output Stream to put test output and errput into. * @return test status. */ public static int run(String[] argv, PrintStream output) { JemmyProperties.setCurrentOutput(new TestOut(System.in, output, output)); return(run(argv)); } /** * Executes a test. * @param argv First element should be a test class name, * all others - test args. * @param output Stream to put test output into. * @param errput Stream to put test errput into. * @return test status. */ public static int run(String[] argv, PrintStream output, PrintStream errput) { JemmyProperties.setCurrentOutput(new TestOut(System.in, output, errput)); return(run(argv)); } /** * Executes a test. * @param argv First element should be a test class name, * all others - test args. * @param output Writer to put test output and errput into. * @return test status. */ public static int run(String[] argv, PrintWriter output) { JemmyProperties.setCurrentOutput(new TestOut(System.in, output, output)); return(run(argv)); } /** * Executes a test. * @param argv First element should be a test class name, * all others - test args. * @param output Writer to put test output into. * @param errput Writer to put test errput into. * @return test status. */ public static int run(String[] argv, PrintWriter output, PrintWriter errput) { JemmyProperties.setCurrentOutput(new TestOut(System.in, output, errput)); return(run(argv)); } /** * Invoke this Test. * The call might be directly from the command line. * @param argv First element should be a test class name, * all others - test args. */ public static void main(String[] argv) { System.exit(run(argv, System.out)); } static { Timeouts.initDefault("Test.WholeTestTimeout", WHOLE_TEST_TIMEOUT); } /** * Creates an instance of a class named by the parameter. * @param testName Full test class name * @return an instance of the test Scenario to launch. * @see org.netbeans.jemmy.Scenario */ public Scenario testForName(String testName) { try { return((Scenario)( Class.forName(testName). getConstructor(new Class[0]). newInstance(new Object[0]))); } catch (ClassNotFoundException e) { output.printErrLine("Class " + testName + " does not exist!"); output.printStackTrace(e); } catch (NoSuchMethodException e) { output.printErrLine("Class " + testName + " has not constructor!"); output.printStackTrace(e); } catch (InvocationTargetException e) { output.printErrLine("Exception inside " + testName + " constructor:"); output.printStackTrace(e.getTargetException()); } catch (IllegalAccessException e) { output.printErrLine("Cannot access to " + testName + " constructor!"); output.printStackTrace(e); } catch (InstantiationException e) { output.printErrLine("Cannot instantiate " + testName + " class!"); output.printStackTrace(e); } return(null); } /** * Set the timeouts used by this Test. * @param timeouts A collection of timeout assignments. * @see org.netbeans.jemmy.Timeoutable * @see org.netbeans.jemmy.Timeouts * @see #getTimeouts */ public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; Timeouts times = timeouts.cloneThis(); times.setTimeout("ActionProducer.MaxActionTime", timeouts.getTimeout("Test.WholeTestTimeout")); super.setTimeouts(times); } /** * Get the timeouts used by this Test. * @see org.netbeans.jemmy.Timeoutable * @see org.netbeans.jemmy.Timeouts * @see #setTimeouts */ public Timeouts getTimeouts() { return(timeouts); } /** * Set the streams or writers used for print output. * @param out An object used to identify both output and error * print streams. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #getOutput */ public void setOutput(TestOut out) { output = out; super.setOutput(out); } /** * Get the streams or writers used for print output. * @return an object containing references to both output and error print * streams. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #setOutput */ public TestOut getOutput() { return(output); } /** * Executes test. * @param param Object to be passed into this test's launch(Object) method. * @return test status. */ public int startTest(Object param) { if(scenario != null) { output.printLine("Test " + scenario.getClass().getName() + " has been started"); } else { output.printLine("Test " + getClass().getName() + " has been started"); } try { return(((Integer)produceAction(param)).intValue()); } catch (InterruptedException e) { output.printErrLine("Test was interrupted."); output.printStackTrace(e); } catch (TimeoutExpiredException e) { output.printErrLine("Test was not finished in " + Long.toString(timeouts.getTimeout("Test.WholeTestTimeout")) + " milliseconds"); output.printStackTrace(e); } catch (Exception e) { output.printStackTrace(e); } return(1); } /** * Launch an action. * Pass arguments to and execute a test Scenario. * @param obj An argument object that controls test execution. * This might be a java.lang.String[] containing * command line arguments. * @see org.netbeans.jemmy.Action * @return an Integer containing test status. */ public final Object launch(Object obj) { setTimeouts(timeouts); try { if(scenario != null) { closeDown(scenario.runIt(obj)); } else { closeDown(runIt(obj)); } } catch(TestCompletedException e) { output.printStackTrace(e); return(new Integer(e.getStatus())); } catch(Throwable e) { output.printStackTrace(e); return(new Integer(SCENARIO_EXCEPTION_STATUS)); } return(new Integer(TEST_PASSED_STATUS)); } /** * Supposed to be overridden to print a synopsys into test output. */ public void printSynopsis() { output.printLine("Here should be a test synopsis."); } /** * @see org.netbeans.jemmy.Action */ public final String getDescription() { return("Test " + scenario.getClass().getName() + " finished"); } /** * Defines a way to execute this Test. * @param param An object passed to configure the test scenario * execution. For example, this parameter might be a * java.lang.String[] object that lists the * command line arguments to the Java application corresponding * to a test. * @return an int that tells something about the execution. * For, example, a status code. * @see org.netbeans.jemmy.Scenario */ public int runIt(Object param){ return(0); } /** * Sleeps. * @param time The sleep time in milliseconds. */ protected void doSleep(long time) { try { Thread.currentThread().sleep(time); } catch(InterruptedException e) { } } private static String[] shiftArray(String[] orig) { String[] result = new String[orig.length - 1]; for(int i = 0; i < result.length; i++) { result[i] = orig[i+1]; } return(result); } } Jemmy2/src/org/netbeans/jemmy/TimeoutExpiredException.java0000644000175000017500000000472711064436407022773 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; /** * * Exception is supposed to be used to notice that some * waiting was expired. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class TimeoutExpiredException extends JemmyException{ /** * Constructor. * @param description Waiting description. */ public TimeoutExpiredException(String description) { super(description); } } Jemmy2/src/org/netbeans/jemmy/debug.timeouts0000644000175000017500000000141111064436407020146 0ustar tonytonyAbstractButtonOperator.PushButtonTimeout=100 ComponentOperator.AfterDragTimeout=100 ComponentOperator.BeforeDragTimeout=100 ComponentOperator.MouseClickTimeout=100 ComponentOperator.PushKeyTimeout=100 DialogWaiter.AfterDialogTimeout=3000 EventDispatcher.RobotAutoDelay=100 FrameWaiter.AfterFrameTimeout=3000 JComboBoxOperator.BeforeSelectingTimeout=100 JComponentOperator.ShowToolTipTimeout=1000 JMenuItemOperator.PushMenuTimeout=100 JMenuOperator.WaitBeforePopupTimeout=100 JScrollBarOperator.OneScrollClickTimeout=10 JSplitPaneOperator.ScrollClickTimeout=10 JTextComponentOperator.BetweenKeysTimeout=100 JTextComponentOperator.PushKeyTimeout=100 JTextComponentOperator.TypeTextTimeout=60000 JTreeOperator.WaitAfterNodeExpandedTimeout=100 WindowWaiter.AfterWindowTimeout=3000 Jemmy2/src/org/netbeans/jemmy/EventDispatcher.java0000644000175000017500000011200411245712447021223 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.awt.AWTEvent; import java.awt.Component; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.AWTEventListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.WindowEvent; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; /** * Provides low level functions for reproducing user actions. * One dispatch model uses the managed component's event queue to dispatch * events. The other dispatch model uses java.awt.Robot to * generate native events. It is an option in the Robot dispatch model * to wait for the managed component's event queue to empty before dispatching * events. * * Timeouts used:
* EventDispatcher.WaitQueueEmptyTimeout - to wait event queue empty.
* EventDispatcher.RobotAutoDelay - param for java.awt.Robot.setAutoDelay method.
* EventDispatcher.WaitComponentUnderMouseTimeout - time to wait component under mouse.
* * @see org.netbeans.jemmy.Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class EventDispatcher implements Outputable, Timeoutable { private final static long WAIT_QUEUE_EMPTY_TIMEOUT = 180000; private final static long ROBOT_AUTO_DELAY = 10; private final static long WAIT_COMPONENT_UNDER_MOUSE_TIMEOUT = 60000; private static Field[] keyFields; private static MotionListener motionListener = null; /** * Component to dispatch events to. */ protected Component component; private TestOut output; private Timeouts timeouts; private ClassReference reference; private int model; private ClassReference robotReference = null; private boolean outsider = false; private QueueTool queueTool; /** * Constructor. * @param comp Component to operate with. */ public EventDispatcher(Component comp) { super(); component = comp; reference = new ClassReference(comp); queueTool = new QueueTool(); setOutput(JemmyProperties.getProperties().getOutput()); setTimeouts(JemmyProperties.getProperties().getTimeouts()); setDispatchingModel(JemmyProperties.getProperties().getDispatchingModel()); } /** * Waits for the managed component's java.awt.EventQueue to empty. * The timeout for this wait is EventDispatcher.WaitQueueEmptyTimeout. * @param output Output to print exception into. * @param timeouts A collection of timeout assignments. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.QueueTool */ public static void waitQueueEmpty(TestOut output, Timeouts timeouts) { QueueTool qt = new QueueTool(); qt.setTimeouts(timeouts.cloneThis()); qt.getTimeouts(). setTimeout("QueueTool.WaitQueueEmptyTimeout", JemmyProperties. getCurrentTimeout("EventDispatcher.WaitQueueEmptyTimeout")); qt.setOutput(output); qt.waitEmpty(); } /** * Waits for the managed component's java.awt.EventQueue to empty. * Uses default output and timeouts. The timeout for this wait is * EventDispatcher.WaitQueueEmptyTimeout. * @see QueueTool * @throws TimeoutExpiredException */ public static void waitQueueEmpty() { waitQueueEmpty(JemmyProperties.getCurrentOutput(), JemmyProperties.getCurrentTimeouts()); } /** * Waits for the managed component's java.awt.EventQueue to stay empty. * The timeout for this wait is EventDispatcher.WaitQueueEmptyTimeout. * @param emptyTime The time that the event queue has to stay empty to avoid * a TimeoutExpiredException. * @param output Output to print exception into * @param timeouts A collection of timeout assignments. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.QueueTool */ public static void waitQueueEmpty(long emptyTime, TestOut output, Timeouts timeouts) { QueueTool qt = new QueueTool(); qt.setTimeouts(timeouts.cloneThis()); qt.getTimeouts(). setTimeout("QueueTool.WaitQueueEmptyTimeout", JemmyProperties. getCurrentTimeout("EventDispatcher.WaitQueueEmptyTimeout")); qt.setOutput(output); qt.waitEmpty(emptyTime); } /** * Waits for the managed component's java.awt.EventQueue to stay empty. * Uses default output and timeouts. The timeout for this wait is * EventDispatcher.WaitQueueEmptyTimeout. * @param emptyTime The time that the event queue has to stay empty to avoid * a TimeoutExpiredException. * @throws TimeoutExpiredException * @see org.netbeans.jemmy.QueueTool */ public static void waitQueueEmpty(long emptyTime) { waitQueueEmpty(emptyTime, JemmyProperties.getCurrentOutput(), JemmyProperties.getCurrentTimeouts()); } /** * Get a string representation for key modifiers. * Used to print trace. * @param modifiers Bit mask of keyboard event modifiers. * @return a string representation for the keyboard event modifiers. */ public static String getModifiersString(int modifiers) { String result = ""; if((modifiers & InputEvent.CTRL_MASK) != 0) { result = result + "CTRL_MASK | "; } if((modifiers & InputEvent.META_MASK) != 0) { result = result + "META_MASK | "; } if((modifiers & InputEvent.ALT_MASK) != 0) { result = result + "ALT_MASK | "; } if((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) { result = result + "ALT_GRAPH_MASK | "; } if((modifiers & InputEvent.SHIFT_MASK) != 0) { result = result + "SHIFT_MASK | "; } if(result.length() > 0) { return(result.substring(0, result.length() - 3)); } return(result); } /** * Returns a string representation for a keyboard event. * Used to print trace. * @param keyCode Key code (KeyEvent.VK_* value) * @return the KeyEvent field name. */ public static String getKeyDescription(int keyCode) { for(int i = 0; i < keyFields.length; i++) { try { if(keyFields[i].getName().startsWith("VK_") && keyFields[i].getInt(null) == keyCode) { return(keyFields[i].getName()); } } catch(IllegalAccessException e) { JemmyProperties.getCurrentOutput().printStackTrace(e); } } return("VK_UNKNOWN"); } /** * Returns a mouse button string representation. * Used to print trace. * @param button Mouse button (InputEvent.BUTTON1/2/3_MASK value). * @return InputEvent field name. */ public static String getMouseButtonDescription(int button) { String result; if ((button & InputEvent.BUTTON1_MASK) != 0) { result = "BUTTON1"; } else if((button & InputEvent.BUTTON2_MASK) != 0) { result = "BUTTON2"; } else if((button & InputEvent.BUTTON3_MASK) != 0) { result = "BUTTON3"; } else { result = "UNKNOWN_BUTTON"; } return(result); } public static void performInit() { Timeouts.initDefault("EventDispatcher.WaitQueueEmptyTimeout", WAIT_QUEUE_EMPTY_TIMEOUT); Timeouts.initDefault("EventDispatcher.RobotAutoDelay", ROBOT_AUTO_DELAY); Timeouts.initDefault("EventDispatcher.WaitComponentUnderMouseTimeout", WAIT_COMPONENT_UNDER_MOUSE_TIMEOUT); try { keyFields = Class.forName("java.awt.event.KeyEvent").getFields(); } catch(ClassNotFoundException e) { JemmyProperties.getCurrentOutput().printStackTrace(e); } } static { performInit(); } /** * Wait (or not) for the mouse to move over a Java component before pressing. * This option is relevant when using java.awt.Robot to generate * mouse events. If a mouse press occurs at a position not occupied by a * known Java component then a NoComponentUnderMouseException * will be thrown. * @param yesOrNo if true then the test system will wait for * the mouse to move over a Java component before pressing. * therwise, mouse presses can take place anywhere on the screen. */ public void checkComponentUnderMouse(boolean yesOrNo) { outsider = !yesOrNo; } /** * Defines print output streams or writers. * @param out Identify the streams or writers used for print output. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #getOutput */ public void setOutput(TestOut out) { output = out; queueTool.setOutput(out); } /** * Returns print output streams or writers. * @return an object that contains references to objects for * printing to output and err streams. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #setOutput */ public TestOut getOutput() { return(output); } /** * Defines current timeouts. * @param timeouts A collection of timeout assignments. * @see org.netbeans.jemmy.Timeoutable * @see org.netbeans.jemmy.Timeouts * @see #getTimeouts */ public void setTimeouts(Timeouts timeouts) { this.timeouts = timeouts; queueTool.setTimeouts(timeouts); queueTool.getTimeouts(). setTimeout("QueueTool.WaitQueueEmptyTimeout", timeouts. getTimeout("EventDispatcher.WaitQueueEmptyTimeout")); if(robotReference != null) { try { Object[] params = {new Integer((int)timeouts.getTimeout("EventDispatcher.RobotAutoDelay"))}; Class[] paramClasses = {Integer.TYPE}; robotReference.invokeMethod("setAutoDelay", params, paramClasses); } catch(InvocationTargetException e) { output.printStackTrace(e); } catch(IllegalStateException e) { output.printStackTrace(e); } catch(NoSuchMethodException e) { output.printStackTrace(e); } catch(IllegalAccessException e) { output.printStackTrace(e); } } } /** * Return current timeouts. * @return the collection of current timeout assignments. * @see org.netbeans.jemmy.Timeoutable * @see org.netbeans.jemmy.Timeouts * @see #setTimeouts */ public Timeouts getTimeouts() { return(timeouts); } /** * Defines dispatching model. * @param m New model value. * @see #getDispatchingModel() * @see org.netbeans.jemmy.JemmyProperties#QUEUE_MODEL_MASK * @see org.netbeans.jemmy.JemmyProperties#ROBOT_MODEL_MASK * @see org.netbeans.jemmy.JemmyProperties#getCurrentDispatchingModel() * @see org.netbeans.jemmy.JemmyProperties#setCurrentDispatchingModel(int) * @see org.netbeans.jemmy.JemmyProperties#initDispatchingModel(boolean, boolean) * @see org.netbeans.jemmy.JemmyProperties#initDispatchingModel() */ public void setDispatchingModel(int m) { model = m; if((model & JemmyProperties.ROBOT_MODEL_MASK) != 0) { createRobot(); try { Object[] params = { (model & JemmyProperties.QUEUE_MODEL_MASK) != 0 ? Boolean.TRUE : Boolean.FALSE }; Class[] paramClasses = {Boolean.TYPE}; robotReference.invokeMethod("setAutoWaitForIdle", params, paramClasses); } catch(InvocationTargetException e) { output.printStackTrace(e); } catch(IllegalStateException e) { output.printStackTrace(e); } catch(NoSuchMethodException e) { output.printStackTrace(e); } catch(IllegalAccessException e) { output.printStackTrace(e); } } } /** * Gets the dispatching model value. * @return the model value. * @see #setDispatchingModel(int) * @see org.netbeans.jemmy.JemmyProperties#QUEUE_MODEL_MASK * @see org.netbeans.jemmy.JemmyProperties#ROBOT_MODEL_MASK * @see org.netbeans.jemmy.JemmyProperties#getCurrentDispatchingModel() * @see org.netbeans.jemmy.JemmyProperties#setCurrentDispatchingModel(int) * @see org.netbeans.jemmy.JemmyProperties#initDispatchingModel(boolean, boolean) * @see org.netbeans.jemmy.JemmyProperties#initDispatchingModel() */ public int getDispatchingModel() { return(model); } /** * Dispatches AWTEvent to component passed in constructor. * If (getDispatchingModel & JemmyProperties.QUEUE_MODEL_MASK) == 0 * dispatched event directly, otherwise uses * javax.swing.SwingUtilities.invokeAndWait(Runnable)
* @param event AWTEvent instance to be dispatched. * @throws ComponentIsNotVisibleException * @throws ComponentIsNotFocusedException */ public void dispatchEvent(final AWTEvent event) { // run in dispatch thread String eventToString = (String)queueTool.invokeSmoothly( new QueueTool.QueueAction("event.toString()") { public Object launch() { return event.toString(); } } ); output.printLine("Dispatch event " + eventToString); output.printGolden("Dispatch event " + event.getClass().toString()); Dispatcher disp = new Dispatcher(event); queueTool.invokeAndWait(disp); } /** * Dispatches a MouseEvent. * @see #dispatchEvent(AWTEvent) * @param id MouseEvent.MOUSE_* value * @param mods InputEvent.MOUSE1/2/3_BUTTON | (modiviers value) * @param clickCount Click count * @param x Horizontal click point coordinate. * @param y vertical click point coordinate. * @param popup Difines if mouse event is popup event. */ public void dispatchMouseEvent(int id, int mods, int clickCount, int x, int y, boolean popup) { MouseEvent event = new MouseEvent(component, id, System.currentTimeMillis(), mods, x, y, clickCount, popup); dispatchEvent(event); } /** * Dispatches MouseEvent at the center of component. * @see #dispatchEvent(AWTEvent) * @param id MouseEvent.MOUSE_* value * @param mods InputEvent.MOUSE1/2/3_BUTTON | (modiviers value) * @param clickCount Click count * @param popup Difines if mouse event is popup event. */ public void dispatchMouseEvent(int id, int mods, int clickCount, boolean popup) { int x = component.getWidth() /2; int y = component.getHeight()/2; dispatchMouseEvent(id, mods, clickCount, x, y, popup); } /** * Dispatches WindowEvent. * @see #dispatchEvent(AWTEvent) * @param id WindowEvent.WINDOW_* value */ public void dispatchWindowEvent(int id) { WindowEvent event = new WindowEvent((Window)component, id); dispatchEvent(event); } /** * Dispatches KeyEvent. * @see #dispatchEvent(AWTEvent) * @param id KeyEvent.KEY_PRESSED or KeyEvent.KEY_RELEASED value. * @param mods Modifiers. * @param keyCode Key code, */ public void dispatchKeyEvent(int id, int mods, int keyCode) { KeyEvent event = new KeyEvent(component, id, System.currentTimeMillis() , mods, keyCode); dispatchEvent(event); } /** * Dispatches KeyEvent. * @see #dispatchEvent(AWTEvent) * @param id KeyEvent.KEY_TYPED value. * @param mods Modifiers. * @param keyCode Key code, * @param keyChar Char to be tiped */ public void dispatchKeyEvent(int id, int mods, int keyCode, char keyChar) { KeyEvent event = new KeyEvent(component, id, System.currentTimeMillis(), mods, keyCode, keyChar); dispatchEvent(event); } /** * Waits until all events currently on the event queue have been processed. */ public void waitForIdle() { makeRobotOperation("waitForIdle", null, null); } /** * Bind horizontal relative cursor coordinate to screen coordinate. * @param x Relative coordinate * @return Absolute coordinate */ protected int getAbsoluteX(int x) { return((int)component.getLocationOnScreen().getX() + x); } /** * Bind vertical relative cursor coordinate to screen coordinate. * @param y Relative coordinate * @return Absolute coordinate */ protected int getAbsoluteY(int y) { return((int)component.getLocationOnScreen().getY() + y); } /** * Delays robot. * @param time Time to dalay robot for. */ public void delayRobot(long time) { Object[] params = {new Integer((int)time)}; Class[] paramClasses = {Integer.TYPE}; makeRobotOperation("delay", params, paramClasses); } /** * Moves mouse by robot. * @param x Component relative horizontal coordinate. * @param y Component relative vertical coordinate. * @throws ComponentIsNotVisibleException */ public void robotMoveMouse(int x, int y) { if(motionListener == null) { initMotionListener(); } output.printLine("Move mouse to (" + Integer.toString(x) + "," + Integer.toString(y) + ")"); Object[] params = {new Integer(getAbsoluteX(x)), new Integer(getAbsoluteY(y))}; Class[] paramClasses = {Integer.TYPE, Integer.TYPE}; makeRobotOperation("mouseMove", params, paramClasses); } /** * Press mouse button by robot. * @param button Mouse button (InputEvent.MOUSE1/2/3_BUTTON value) * @param modifiers Modifiers * @throws ComponentIsNotVisibleException */ public void robotPressMouse(int button, int modifiers) { if(!outsider) { waitMouseOver(); } robotPressModifiers(modifiers); output.printLine("Press " + getMouseButtonDescription(button) + " mouse button"); Object[] params = {new Integer(button)}; Class[] paramClasses = {Integer.TYPE}; makeRobotOperation("mousePress", params, paramClasses); } /** * Press mouse button with 0 modifiers. * @param button Mouse button (InputEvent.MOUSE1/2/3_BUTTON value) * @see #robotPressMouse(int, int) */ public void robotPressMouse(int button) { robotPressMouse(button, 0); } /** * Releases mouse button by robot. * @param button Mouse button (InputEvent.MOUSE1/2/3_BUTTON value) * @param modifiers Modifiers * @throws ComponentIsNotVisibleException */ public void robotReleaseMouse(int button, int modifiers) { output.printLine("Release " + getMouseButtonDescription(button) + " mouse button"); Object[] params = {new Integer(button)}; Class[] paramClasses = {Integer.TYPE}; makeRobotOperation("mouseRelease", params, paramClasses); robotReleaseModifiers(modifiers); } /** * Releases mouse button with 0 modifiers. * @param button Mouse button (InputEvent.MOUSE1/2/3_BUTTON value) * @see #robotReleaseMouse(int, int) */ public void robotReleaseMouse(int button) { robotReleaseMouse(button, 0); } /** * Press a key using java.awt.Robot. * @param keyCode Key (KeyEvent.VK_* value) * @param modifiers Mask of KeyEvent modifiers. * @throws ComponentIsNotVisibleException * @throws ComponentIsNotFocusedException */ public void robotPressKey(int keyCode, int modifiers) { robotPressModifiers(modifiers); output.printLine("Press " + getKeyDescription(keyCode) + " key"); Object[] params = {new Integer(keyCode)}; Class[] paramClasses = {Integer.TYPE}; makeRobotOperation("keyPress", params, paramClasses); } /** * Press key with no modifiers using java.awt.Robot. * @param keyCode Key (KeyEvent.VK_* value) * @see #robotPressKey(int, int) */ public void robotPressKey(int keyCode) { robotPressKey(keyCode, 0); } /** * Releases key by robot. * @param keyCode Key (KeyEvent.VK_* value) * @param modifiers Mask of KeyEvent modifiers. * @throws ComponentIsNotVisibleException * @throws ComponentIsNotFocusedException */ public void robotReleaseKey(int keyCode, int modifiers) { output.printLine("Release " + getKeyDescription(keyCode) + " key"); Object[] params = {new Integer(keyCode)}; Class[] paramClasses = {Integer.TYPE}; makeRobotOperation("keyRelease", params, paramClasses); robotReleaseModifiers(modifiers); } /** * Releases key with 0 modifiers. * @param keyCode Key (KeyEvent.VK_* value) * @see #robotPressKey(int, int) */ public void robotReleaseKey(int keyCode) { robotReleaseKey(keyCode, 0); } /** * Invokes component method through SwingUtilities.invokeAndWait(Runnable). * * @param method_name Name of a method to be invoked * @param params Method params * @param params_classes Method params' classes * @return an Object - methods result. * @see org.netbeans.jemmy.ClassReference * @exception IllegalAccessException * @exception NoSuchMethodException * @exception IllegalStateException * @exception InvocationTargetException */ public Object invokeMethod(String method_name, Object[] params, Class[] params_classes) throws InvocationTargetException, IllegalStateException, NoSuchMethodException, IllegalAccessException { Invoker invk = new Invoker(method_name, params, params_classes); try { return(queueTool.invokeAndWait(invk)); } catch(JemmyException e) { if(invk.getException() != null) { if(invk.getException() instanceof InvocationTargetException) { throw((InvocationTargetException)invk.getException()); } else if(invk.getException() instanceof IllegalStateException) { throw((IllegalStateException)invk.getException()); } else if(invk.getException() instanceof NoSuchMethodException) { throw((NoSuchMethodException)invk.getException()); } else if(invk.getException() instanceof IllegalAccessException) { throw((IllegalAccessException)invk.getException()); } } throw(e); } } /** * Gets component field value through SwingUtilities.invokeAndWait(Runnable). * * @param field_name Name of a field * @see #setField(String, Object) * @see org.netbeans.jemmy.ClassReference * @return an Object - field value * @exception IllegalAccessException * @exception IllegalStateException * @exception InvocationTargetException * @exception NoSuchFieldException */ public Object getField(String field_name) throws InvocationTargetException, IllegalStateException, NoSuchFieldException, IllegalAccessException { Getter gtr = new Getter(field_name); try { return(queueTool.invokeAndWait(gtr)); } catch(JemmyException e) { if(gtr.getException() != null) { if(gtr.getException() instanceof InvocationTargetException) { throw((InvocationTargetException)gtr.getException()); } else if(gtr.getException() instanceof IllegalStateException) { throw((IllegalStateException)gtr.getException()); } else if(gtr.getException() instanceof NoSuchFieldException) { throw((NoSuchFieldException)gtr.getException()); } else if(gtr.getException() instanceof IllegalAccessException) { throw((IllegalAccessException)gtr.getException()); } } throw(e); } } /** * Sets component field value through SwingUtilities.invokeAndWait(Runnable). * * @param field_name Name of a field * @param newValue New field value * @see #getField(String) * @see org.netbeans.jemmy.ClassReference * @exception IllegalAccessException * @exception IllegalStateException * @exception InvocationTargetException * @exception NoSuchFieldException */ public void setField(String field_name, Object newValue) throws InvocationTargetException, IllegalStateException, NoSuchFieldException, IllegalAccessException { Setter str = new Setter(field_name, newValue); try { queueTool.invokeAndWait(str); } catch(JemmyException e) { if(str.getException() != null) { if(str.getException() instanceof InvocationTargetException) { throw((InvocationTargetException)str.getException()); } else if(str.getException() instanceof IllegalStateException) { throw((IllegalStateException)str.getException()); } else if(str.getException() instanceof NoSuchFieldException) { throw((NoSuchFieldException)str.getException()); } else if(str.getException() instanceof IllegalAccessException) { throw((IllegalAccessException)str.getException()); } } throw(e); } } /** * Invokes component method through SwingUtilities.invokeAndWait(Runnable). * and catch all exceptions. * @param method_name Name of a method to be invoked * @param params Method params * @param params_classes Method params' classes * @param out TestOut instance to print exceptions stack trace to. * @return an Object - method result * @see #invokeMethod(String, Object[], Class[]) * @see org.netbeans.jemmy.ClassReference */ public Object invokeExistingMethod(String method_name, Object[] params, Class[] params_classes, TestOut out) { try { return(invokeMethod(method_name, params, params_classes)); } catch(InvocationTargetException e) { out.printStackTrace(e); } catch(IllegalStateException e) { out.printStackTrace(e); } catch(NoSuchMethodException e) { out.printStackTrace(e); } catch(IllegalAccessException e) { out.printStackTrace(e); } return(null); } /** * Gets component field value through SwingUtilities.invokeAndWait(Runnable). * and catch all exceptions. * @param field_name Name of a field * @param out TestOut instance to print exceptions stack trace to. * @return an Object - fields value * @see #getField(String) * @see #setExistingField(String, Object, TestOut) * @see org.netbeans.jemmy.ClassReference */ public Object getExistingField(String field_name, TestOut out) { try { return(getField(field_name)); } catch(InvocationTargetException e) { out.printStackTrace(e); } catch(IllegalStateException e) { out.printStackTrace(e); } catch(NoSuchFieldException e) { out.printStackTrace(e); } catch(IllegalAccessException e) { out.printStackTrace(e); } return(null); } /** * Sets component field value through SwingUtilities.invokeAndWait(Runnable). * and catch all exceptions. * @param field_name Name of a field * @param newValue New field value * @param out TestOut instance to print exceptions stack trace to. * @see #setField(String, Object) * @see #getExistingField(String, TestOut) * @see org.netbeans.jemmy.ClassReference */ public void setExistingField(String field_name, Object newValue, TestOut out) { try { setField(field_name, newValue); } catch(InvocationTargetException e) { out.printStackTrace(e); } catch(IllegalStateException e) { out.printStackTrace(e); } catch(NoSuchFieldException e) { out.printStackTrace(e); } catch(IllegalAccessException e) { out.printStackTrace(e); } } /** * Invokes component method through SwingUtilities.invokeAndWait(Runnable). * and catch all exceptions. * Exceptions are printed into TestOut object defined * by setOutput(TestOut) method. * @param method_name Name of a method to be invoked * @param params Method params * @param params_classes Method params' classes * @return an Object - method result * @see #invokeExistingMethod(String, Object[], Class[], TestOut) * @see org.netbeans.jemmy.ClassReference */ public Object invokeExistingMethod(String method_name, Object[] params, Class[] params_classes) { return(invokeExistingMethod(method_name, params, params_classes, output)); } /** * Gets component field value through SwingUtilities.invokeAndWait(Runnable). * and catch all exceptions. * Exceptions are printed into TestOut object defined * by setOutput(TestOut) method. * @param field_name Name of a field * @return an Object - fields value * @see #getExistingField(String, TestOut) * @see #setExistingField(String, Object) * @see org.netbeans.jemmy.ClassReference */ public Object getExistingField(String field_name) { return(getExistingField(field_name, output)); } /** * Sets component field value through SwingUtilities.invokeAndWait(Runnable). * and catch all exceptions. * Exceptions are printed into TestOut object defined * by setOutput(TestOut) method. * @param field_name Name of a field * @param newValue New field value * @see #setExistingField(String, Object, TestOut) * @see #getExistingField(String) * @see org.netbeans.jemmy.ClassReference */ public void setExistingField(String field_name, Object newValue) { setExistingField(field_name, output); } //recursivelly releases all modifiers keys private void robotReleaseModifiers(int modifiers) { if ((modifiers & InputEvent.SHIFT_MASK) != 0) { robotReleaseKey(KeyEvent.VK_SHIFT, modifiers - (InputEvent.SHIFT_MASK & modifiers)); } else if((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) { robotReleaseKey(KeyEvent.VK_ALT_GRAPH, modifiers - (InputEvent.ALT_GRAPH_MASK & modifiers)); } else if((modifiers & InputEvent.ALT_MASK) != 0) { robotReleaseKey(KeyEvent.VK_ALT, modifiers - (InputEvent.ALT_MASK & modifiers)); } else if((modifiers & InputEvent.META_MASK) != 0) { robotReleaseKey(KeyEvent.VK_META, modifiers - (InputEvent.META_MASK & modifiers)); } else if((modifiers & InputEvent.CTRL_MASK) != 0) { robotReleaseKey(KeyEvent.VK_CONTROL, modifiers - (InputEvent.CTRL_MASK & modifiers)); } } //throws ComponentIsNotVisibleException if component is not visible private void checkVisibility() { if(!component.isVisible()) { throw(new ComponentIsNotVisibleException(component)); } } //throws ComponentIsNotFocusedException if component has not focus private void checkFocus() { if(!component.hasFocus()) { throw(new ComponentIsNotFocusedException(component)); } } //creates java.awt.Robot instance private void createRobot() { try { ClassReference robotClassReverence = new ClassReference("java.awt.Robot"); robotReference = new ClassReference(robotClassReverence.newInstance(null, null)); } catch(ClassNotFoundException e) { output.printStackTrace(e); } catch(InstantiationException e) { output.printStackTrace(e); } catch(InvocationTargetException e) { output.printStackTrace(e); } catch(IllegalStateException e) { output.printStackTrace(e); } catch(NoSuchMethodException e) { output.printStackTrace(e); } catch(IllegalAccessException e) { output.printStackTrace(e); } } private void waitMouseOver() { try { Waiter wt = new Waiter(new Waitable() { public Object actionProduced(Object obj) { if(motionListener.getComponent() != null) { return(""); } else { return(null); } } public String getDescription() { return("Mouse over component"); } }); wt.setTimeoutsToCloneOf(timeouts, "EventDispatcher.WaitComponentUnderMouseTimeout"); wt.setOutput(output.createErrorOutput()); wt.waitAction(component); } catch(InterruptedException e) { output.printStackTrace(e); } catch(TimeoutExpiredException e) { throw(new NoComponentUnderMouseException()); } } //produce a robot operations through reflection private void makeRobotOperation(String method, Object[] params, Class[] paramClasses) { try { robotReference.invokeMethod(method, params, paramClasses); } catch(InvocationTargetException e) { output.printStackTrace(e); } catch(IllegalStateException e) { output.printStackTrace(e); } catch(NoSuchMethodException e) { output.printStackTrace(e); } catch(IllegalAccessException e) { output.printStackTrace(e); } if ((model & JemmyProperties.QUEUE_MODEL_MASK) != 0) { try { waitQueueEmpty(output.createErrorOutput(), timeouts); } catch(TimeoutExpiredException e) { output.printStackTrace(e); } } } //recursivelly presses all modifiers keys private void robotPressModifiers(int modifiers) { if ((modifiers & InputEvent.SHIFT_MASK) != 0) { robotPressKey(KeyEvent.VK_SHIFT, modifiers & ~InputEvent.SHIFT_MASK); } else if((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) { robotPressKey(KeyEvent.VK_ALT_GRAPH, modifiers & ~InputEvent.ALT_GRAPH_MASK); } else if((modifiers & InputEvent.ALT_MASK) != 0) { robotPressKey(KeyEvent.VK_ALT, modifiers & ~InputEvent.ALT_MASK); } else if((modifiers & InputEvent.META_MASK) != 0) { robotPressKey(KeyEvent.VK_META, modifiers & ~InputEvent.META_MASK); } else if((modifiers & InputEvent.CTRL_MASK) != 0) { robotPressKey(KeyEvent.VK_CONTROL, modifiers & ~InputEvent.CTRL_MASK); } } private void initMotionListener() { if(motionListener == null) { motionListener = new MotionListener(); Toolkit.getDefaultToolkit().addAWTEventListener(motionListener, AWTEvent.MOUSE_EVENT_MASK); Object[] params = new Object[2]; Class[] paramClasses = {Integer.TYPE, Integer.TYPE}; params[0] = new Integer(getAbsoluteX(-1)); params[1] = new Integer(getAbsoluteX(-1)); makeRobotOperation("mouseMove", params, paramClasses); params[0] = new Integer(getAbsoluteX(0)); params[1] = new Integer(getAbsoluteX(0)); makeRobotOperation("mouseMove", params, paramClasses); } } private class Dispatcher extends QueueTool.QueueAction { AWTEvent event; public Dispatcher(AWTEvent e) { super(e.getClass().getName() + " event dispatching"); event = e; } public Object launch() { if(event instanceof MouseEvent || event instanceof KeyEvent) { checkVisibility(); } component.dispatchEvent(event); return(null); } } private class Invoker extends QueueTool.QueueAction { protected String methodName; protected Object[] params; protected Class[] paramClasses; public Invoker(String mn, Object[] p, Class[] pc) { super(mn + " method invocation"); methodName = mn; params = p; paramClasses = pc; } public Object launch() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { checkVisibility(); if(methodName.equals("keyPress") || methodName.equals("keyRelease")) { checkFocus(); } return(reference.invokeMethod(methodName, params, paramClasses)); } } private class Getter extends QueueTool.QueueAction { String fieldName; public Getter(String fn) { super(fn + " field receiving"); fieldName = fn; } public Object launch() throws InvocationTargetException, NoSuchFieldException, IllegalAccessException { return(reference.getField(fieldName)); } } private class Setter extends QueueTool.QueueAction { String fieldName; Object newValue; public Setter(String fn, Object nv) { super(fn + " field changing"); fieldName = fn; newValue = nv; } public Object launch() throws InvocationTargetException, NoSuchFieldException, IllegalAccessException { reference.setField(fieldName, newValue); return(null); } } private static class MotionListener implements AWTEventListener { private Component mouseComponent; public void eventDispatched(AWTEvent event) { if(event instanceof MouseEvent) { MouseEvent e = (MouseEvent)event; if (e.getID() == MouseEvent.MOUSE_ENTERED) { mouseComponent = e.getComponent(); } else if(e.getID() == MouseEvent.MOUSE_EXITED) { mouseComponent = null; } } } public Component getComponent() { return(mouseComponent); } } } Jemmy2/src/org/netbeans/jemmy/explorer/0000755000175000017500000000000011572745223017133 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/explorer/package.html0000644000175000017500000000046211064436407021413 0ustar tonytony Package org.netbeans.jemmy.explorer

Package org.netbeans.jemmy.explorer

Contains auxiliary classes to explore tested application.
@since 23 Feb 2002
Jemmy2/src/org/netbeans/jemmy/explorer/TrialListenerManager.java0000644000175000017500000001313211245712237024046 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.explorer; import java.awt.AWTEvent; import java.awt.Component; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import org.netbeans.jemmy.JemmyProperties; import org.netbeans.jemmy.Outputable; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.TestOut; /** * Auxiliary class to find an event sequence which should be posted * to reproduce user actions. * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class TrialListenerManager implements Outputable { Component comp; TrialMouseListener mListener; TrialMouseMotionListener mmListener; TrialKeyListener kListener; TestOut output; /** * Contructor. * @param comp Component to display event sequence for. */ public TrialListenerManager(Component comp) { this.comp = comp; mListener = new TrialMouseListener(); mmListener = new TrialMouseMotionListener(); kListener = new TrialKeyListener(); output = JemmyProperties.getCurrentOutput(); } public void setOutput(TestOut output) { this.output = output; } public TestOut getOutput() { return(output); } /** * Removes mouse listener. * @see #addMouseListener */ public void removeMouseListener() { comp.removeMouseListener(mListener); } /** * Adds mouse listener. * @see #removeMouseListener */ public void addMouseListener() { removeMouseListener(); comp.addMouseListener(mListener); } /** * Removes mouse motion listener. * @see #addMouseMotionListener */ public void removeMouseMotionListener() { comp.removeMouseMotionListener(mmListener); } /** * Adds mouse motion listener. * @see #removeMouseMotionListener */ public void addMouseMotionListener() { removeMouseMotionListener(); comp.addMouseMotionListener(mmListener); } /** * Removes key listener. * @see #addKeyListener */ public void removeKeyListener() { comp.removeKeyListener(kListener); } /** * Adds key listener. * @see #removeKeyListener */ public void addKeyListener() { removeKeyListener(); comp.addKeyListener(kListener); } void printEvent(final AWTEvent event) { // if event != null run toString in dispatch thread String eventToString = (String)new QueueTool().invokeSmoothly( new QueueTool.QueueAction("event.toString()") { public Object launch() { return event.toString(); } } ); output.printLine(eventToString); } private class TrialMouseListener implements MouseListener { public void mouseClicked(MouseEvent e) { printEvent(e); } public void mouseEntered(MouseEvent e) { printEvent(e); } public void mouseExited(MouseEvent e) { printEvent(e); } public void mousePressed(MouseEvent e) { printEvent(e); } public void mouseReleased(MouseEvent e) { printEvent(e); } } private class TrialMouseMotionListener implements MouseMotionListener { public void mouseDragged(MouseEvent e) { printEvent(e); } public void mouseMoved(MouseEvent e) { printEvent(e); } } private class TrialKeyListener implements KeyListener { public void keyPressed(KeyEvent e) { printEvent(e); } public void keyReleased(KeyEvent e) { printEvent(e); } public void keyTyped(KeyEvent e) { printEvent(e); } } } Jemmy2/src/org/netbeans/jemmy/explorer/GUIBrowser.java0000644000175000017500000015070011301504166021756 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.explorer; import java.awt.AWTEvent; import java.awt.AWTException; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Hashtable; import java.util.Properties; import java.util.Vector; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.ListCellRenderer; import javax.swing.border.BevelBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TreeModelListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.filechooser.FileFilter; import javax.swing.table.DefaultTableModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import org.netbeans.jemmy.ClassReference; import org.netbeans.jemmy.QueueTool; import org.netbeans.jemmy.TestOut; import org.netbeans.jemmy.operators.Operator; import org.netbeans.jemmy.util.Dumper; /** * An application allowing to explore a Java GUI application. * Could be executed by command:
*
 * java "application java options" \
 *   org.netbeans.jemmy.explorer.GUIBrowser \
 *   "application main class" \
 *   "application parameters"
 * 
* or from java code by GUIBrowser.showBrowser() method using. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class GUIBrowser extends JFrame{ private static String WINDOWS_TAB = "Subwindows"; private static String COMPONENTS_TAB = "Hierarchy"; private static String PROPERTIES_TAB = "Properties"; private static String REFLECTION_TAB = "Reflection"; private static String EVENT_TAB = "Events"; private static String IMAGE_TAB = "Image"; boolean exit; PropertyDialog propDialog; RootNode root; QueueTool qt; JTextField refreshDelay; JTree mainTree; JLabel status; JButton viewButton; JButton expandButton; JSplitPane split; ByteArrayOutputStream dumpData; PrintWriter dumpWriter; private GUIBrowser(boolean exitNecessary) { super("GUI Browser"); dumpData = new ByteArrayOutputStream(); dumpWriter = new PrintWriter(new OutputStreamWriter(dumpData)); exit = exitNecessary; propDialog = new PropertyDialog(this); qt = new QueueTool(); qt.setOutput(TestOut.getNullOutput()); root = new RootNode(); mainTree = new JTree(root.getWindowModel()); mainTree.setCellRenderer(new WindowRenderer()); mainTree.setEditable(false); refreshDelay = new JTextField(3); refreshDelay.setText("0"); viewButton = new JButton("View"); viewButton.setEnabled(false); viewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new ComponentBrowser(getOwnr(), (ComponentNode)mainTree.getSelectionPath(). getLastPathComponent()). show(); } }); expandButton = new JButton("Expand All"); expandButton.setEnabled(false); expandButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { expandAll(mainTree, mainTree.getSelectionPath()); } }); JButton refreshButton = new JButton("Reload in ..."); refreshButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { reload(new Integer(refreshDelay.getText()).intValue()); } }); JButton dumpButton = new JButton("Dump"); dumpButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(System.getProperty("user.home")); chooser.addChoosableFileFilter(new FileFilter() { public boolean accept(File f) { return(f.getName().endsWith(".xml")); } public String getDescription() { return("xml files"); } }); chooser.showSaveDialog(GUIBrowser.this); try { File file = chooser.getSelectedFile(); OutputStream output = new FileOutputStream(file); output.write(dumpData.toByteArray()); } catch(IOException ee) { ee.printStackTrace(); } } }); JPanel refreshPane = new JPanel(); refreshPane.add(viewButton); refreshPane.add(expandButton); refreshPane.add(new JLabel("")); refreshPane.add(new JLabel("")); refreshPane.add(new JLabel("")); refreshPane.add(new JLabel("")); refreshPane.add(new JLabel("")); refreshPane.add(new JLabel("")); refreshPane.add(refreshButton); refreshPane.add(refreshDelay); refreshPane.add(new JLabel("seconds ")); refreshPane.add(dumpButton); split = createUnderPane(mainTree); JPanel nonStatusPane = new JPanel(); nonStatusPane.setLayout(new BorderLayout()); nonStatusPane.add(refreshPane, BorderLayout.SOUTH); nonStatusPane.add(split, BorderLayout.CENTER); split.setDividerLocation(0.8); status = new JLabel("Reloaded"); JPanel statusPane = new JPanel(); statusPane.setLayout(new BorderLayout()); statusPane.add(status, BorderLayout.CENTER); statusPane.setBorder(new BevelBorder(BevelBorder.LOWERED)); JPanel bottomPane = new JPanel(); bottomPane.setLayout(new BorderLayout()); bottomPane.add(statusPane, BorderLayout.NORTH); bottomPane.add(statusPane, BorderLayout.CENTER); getContentPane().setLayout(new BorderLayout()); getContentPane().add(bottomPane, BorderLayout.SOUTH); getContentPane().add(nonStatusPane, BorderLayout.CENTER); Component[] cpss = {viewButton, expandButton}; mainTree.addTreeSelectionListener(new SelectionManager(cpss)); addWindowListener(new WindowListener() { public void windowActivated(WindowEvent e) {} public void windowClosed(WindowEvent e) { setVisible(false); if(exit) { System.exit(0); } } public void windowClosing(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent e) {} }); addComponentListener(new ComponentListener() { public void componentHidden(ComponentEvent e) {} public void componentMoved(ComponentEvent e) {} public void componentResized(ComponentEvent e) { split.setDividerLocation(0.8); } public void componentShown(ComponentEvent e) {} }); setSize(800, 400); } boolean shown = false; public void show() { super.show(); viewButton.setEnabled(false); if(!shown) { split.setDividerLocation(0.8); shown = true; } } /** * Specifies a status text. * @param st a status text. */ public void setStatus(String st) { status.setText(st); } /** * Method to invoke GUIBrowser from java code. */ public static void showBrowser() { showBrowser(new String[0], false); } /** * Method to invoke GUIBrowser as java application. * @param argv Argument array. If not empty, first element should be
* main class of an aplication to be browsed.
* Other elements are application parameters. */ public static void main(String[] argv) { showBrowser(argv, true); } private static void showBrowser(String[] argv, boolean exitNecessary) { if(argv.length >= 1) { String[] newArgv = new String[argv.length -1]; for(int i = 1; i < argv.length; i++) { newArgv[i-1] = argv[i]; } try { new ClassReference(argv[0]).startApplication(newArgv); } catch (ClassNotFoundException e) { e.printStackTrace(); return; } catch (InvocationTargetException e) { e.printStackTrace(); return; } catch (NoSuchMethodException e) { e.printStackTrace(); return; } } new GUIBrowser(exitNecessary).show(); } private void reload(final int delay) { viewButton.setEnabled(false); expandButton.setEnabled(false); new Thread(new Runnable() { public void run() { try { for(int i = delay - 1; i >= 0 ; i--) { setStatus("Reloading after " + Integer.toString(i) + " second"); Thread.sleep(1000); } setStatus("Reloading ..."); Dumper.dumpAll(dumpWriter); //qt.lock(); root = new RootNode(); //qt.unlock(); mainTree.setModel(root.getWindowModel()); setStatus("Reloaded"); } catch(InterruptedException e) { } } }).start(); } private JFrame getOwnr() { return(this); } private class ClassNode { Class clzz; protected ClassNode() { clzz = null; } public ClassNode(Class clzz) { this.clzz = clzz; } public ClassNode[] getSuperClasses() { int count = 0; Class parent = clzz; while((parent = parent.getSuperclass()) != null) { count++; } Class[] interfaces = clzz.getInterfaces(); ClassNode[] result = new ClassNode[count + interfaces.length + 1]; result[0] = new SuperClassNode(clzz); count = 1; parent = clzz; while((parent = parent.getSuperclass()) != null) { result[count] = new SuperClassNode(parent); count++; } for(int i = count; i < count + interfaces.length; i++) { result[i] = new InterfaceNode(interfaces[i - count]); } return(result); } public String toString() { if(clzz.isArray()) { return(clzz.getComponentType().getName() + "[]"); } else { return(clzz.getName()); } } public TreeModel getMethodsModel() { return(new ClassModel(this)); } public ClassNode[] getSubNodes() { Vector res = new Vector(); Field[] fields = clzz.getFields(); Arrays.sort(fields, new Comparator() { public int compare(Object o1, Object o2) { return(((Field)o1).getName().compareTo(((Field)o2).getName())); } }); Method[] mtds = clzz.getMethods(); Arrays.sort(mtds, new Comparator() { public int compare(Object o1, Object o2) { return(((Method)o1).getName().compareTo(((Method)o2).getName())); } }); for(int i = 0; i < fields.length; i++) { if(fields[i].getDeclaringClass().getName().equals(clzz.getName())) { res.add(new FieldNode(fields[i])); } } for(int i = 0; i < mtds.length; i++) { if(mtds[i].getDeclaringClass().getName().equals(clzz.getName())) { res.add(new MethodNode(mtds[i])); } } ClassNode[] result = new ClassNode[res.size()]; for(int i = 0; i < result.length; i++) { result[i] = (ClassNode)res.get(i); } return(result); } } private class SuperClassNode extends ClassNode { public SuperClassNode(Class clzz) { super(clzz); } public String toString() { return("Class: " + super.toString()); } } private class InterfaceNode extends ClassNode { public InterfaceNode(Class clzz) { super(clzz); } public String toString() { return("Interfac: " + super.toString()); } } private class FieldNode extends ClassNode { Field field; public FieldNode(Field fld) { super(fld.getType()); field = fld; } public String toString() { return("Field: " + Modifier.toString(field.getModifiers()) + " " + super.toString() + " " + field.getName()); } } private class MethodNode extends ClassNode { Method method; public MethodNode(Method mtd) { super(mtd.getReturnType()); method = mtd; } public String toString() { return("Method: " + Modifier.toString(method.getModifiers()) + " " + super.toString() + " " + method.getName()); } public ClassNode[] getParameters() { Class[] ptps = method.getParameterTypes(); ClassNode[] result = new ClassNode[ptps.length]; for(int i = 0; i < ptps.length; i++) { result[i] = new ClassNode(ptps[i]); } return(result); } } private class ComponentNode extends ClassNode { protected Hashtable props; protected String clss = ""; protected String compToString = ""; Component comp; ComponentImageProvider image; protected int x, y, w, h; protected ComponentNode() { props = new Hashtable(); } public ComponentNode(Component comp) { super(comp.getClass()); try { props = Operator.createOperator(comp).getDump(); } catch (Exception e) { props = new Hashtable(); } clss = comp.getClass().getName(); compToString = comp.toString(); this.comp = comp; x = comp.getLocationOnScreen().x; y = comp.getLocationOnScreen().y; w = comp.getWidth(); h = comp.getHeight(); } public String toString() { return(clss); } public Hashtable getProperties() { return(props); } public String getToString() { return(compToString); } public void setComponentImageProvider(ComponentImageProvider provider) { image = provider; } public BufferedImage getImage() { if(image != null) { return(image.getImage(x, y, w, h)); } else { return(null); } } } private class ContainerNode extends ComponentNode { protected ComponentNode[] comps; protected ContainerNode() { super(); comps = new ComponentNode[0]; } public ContainerNode(Container comp) { super(comp); Component[] cmps = comp.getComponents(); Vector wwns = new Vector(); for(int i = 0; i < cmps.length; i++) { if(cmps[i] != null && (propDialog.showAll || cmps[i].isVisible())) { if(cmps[i] instanceof Container) { wwns.add(new ContainerNode((Container)cmps[i])); } else { wwns.add(new ComponentNode(cmps[i])); } } } comps = new ComponentNode[wwns.size()]; for(int i = 0; i < wwns.size(); i++) { comps[i] = (ComponentNode)wwns.get(i); } } public ComponentNode[] getComponents() { return(comps); } public int getComponentIndex(ComponentNode comp) { for(int i = 0; i < comps.length; i++) { if(comps[i].equals(comp)) { return(i); } } return(-1); } public void setComponentImageProvider(ComponentImageProvider provider) { super.setComponentImageProvider(provider); for(int i = 0; i < comps.length; i++) { comps[i].setComponentImageProvider(provider); } } public ComponentModel getComponentModel() { return(new ComponentModel(this)); } } private class WindowNode extends ContainerNode { protected WindowNode[] wins; String title; protected WindowNode() { super(); wins = new WindowNode[0]; title = "All Frames"; clss = ""; } public WindowNode(Window win) { super(win); Window[] wns = win.getOwnedWindows(); Vector wwns = new Vector(); for(int i = 0; i < wns.length; i++) { if(propDialog.showAll || wns[i].isVisible()) { wwns.add(new WindowNode(wns[i])); } } wins = new WindowNode[wwns.size()]; for(int i = 0; i < wwns.size(); i++) { wins[i] = (WindowNode)wwns.get(i); } title = win.toString(); clss = win.getClass().getName(); BufferedImage image = null; try { image = new Robot(). createScreenCapture(new Rectangle(win.getLocationOnScreen(), win.getSize())); } catch(AWTException e) { e.printStackTrace(); } setComponentImageProvider(new ComponentImageProvider(image, x, y)); } public WindowNode[] getWindows() { return(wins); } public int getWindowIndex(WindowNode node) { for(int i = 0; i < wins.length; i++) { if(wins[i].equals(node)) { return(i); } } return(-1); } public WindowModel getWindowModel() { return(new WindowModel(this)); } public String toString() { return(clss + " \"" + title + "\""); } } private class RootNode extends WindowNode { public RootNode() { super(); Window[] wns = Frame.getFrames(); wins = new WindowNode[wns.length]; int count = 0; for(int i = 0; i < wns.length; i++) { if(propDialog.showAll || wns[i].isVisible()) { count++; } } wins = new WindowNode[count]; count = 0; for(int i = 0; i < wns.length; i++) { if(propDialog.showAll || wns[i].isVisible()) { wins[count] = new WindowNode(wns[i]); count++; } } } } private class ClassModel implements TreeModel { ClassNode clsn; ClassModel(ClassNode clsn) { this.clsn = clsn; } public void addTreeModelListener(TreeModelListener l) {} public Object getChild(Object parent, int index) { if(parent == clsn) { return(clsn.getSuperClasses()[index]); } else if(parent instanceof SuperClassNode || parent instanceof InterfaceNode) { return(((ClassNode)parent).getSubNodes()[index]); } else if(parent instanceof MethodNode) { return(((MethodNode)parent).getParameters()[index]); } return(null); } public int getChildCount(Object parent) { if(parent == clsn) { return(clsn.getSuperClasses().length); } else if(parent instanceof SuperClassNode || parent instanceof InterfaceNode) { return(((ClassNode)parent).getSubNodes().length); } else if(parent instanceof MethodNode) { return(((MethodNode)parent).getParameters().length); } return(0); } public int getIndexOfChild(Object parent, Object child) { if(parent == clsn || parent instanceof MethodNode || parent instanceof SuperClassNode || parent instanceof InterfaceNode) { Object[] children; if(parent instanceof SuperClassNode || parent instanceof InterfaceNode) { children = ((ClassNode)parent).getSuperClasses(); } else if(parent instanceof MethodNode) { children = ((MethodNode)parent).getParameters(); } else { children = clsn.getSuperClasses(); } for(int i = 0; i < children.length; i++) { if(children.equals(child)) { return(i); } } } return(0); } public Object getRoot() { return(clsn); } public boolean isLeaf(Object node) { return(getChildCount(node) == 0); } public void removeTreeModelListener(TreeModelListener l) {} public void valueForPathChanged(TreePath path, Object newValue) {} } private class WindowModel implements TreeModel { WindowNode win; WindowModel(WindowNode win) { this.win = win; } public void addTreeModelListener(TreeModelListener l) {} public Object getChild(Object parent, int index) { return(((WindowNode)parent).getWindows()[index]); } public int getChildCount(Object parent) { return(((WindowNode)parent).getWindows().length); } public int getIndexOfChild(Object parent, Object child) { return(((WindowNode)parent).getWindowIndex((WindowNode)child)); } public Object getRoot() { return(win); } public boolean isLeaf(Object node) { return(((WindowNode)node).getWindows().length == 0); } public void removeTreeModelListener(TreeModelListener l) {} public void valueForPathChanged(TreePath path, Object newValue) {} } private class ComponentModel implements TreeModel { ContainerNode cont; ComponentModel(ContainerNode cont) { this.cont = cont; } public void addTreeModelListener(TreeModelListener l) {} public Object getChild(Object parent, int index) { if(parent instanceof ContainerNode) { return(((ContainerNode)parent).getComponents()[index]); } else { return(""); } } public int getChildCount(Object parent) { if(parent instanceof ContainerNode) { return(((ContainerNode)parent).getComponents().length); } else { return(0); } } public int getIndexOfChild(Object parent, Object child) { if(parent instanceof ContainerNode) { return(((ContainerNode)parent).getComponentIndex((ComponentNode)child)); } else { return(-1); } } public Object getRoot() { return(cont); } public boolean isLeaf(Object node) { if(node instanceof ContainerNode) { return(((ContainerNode)node).getComponents().length == 0); } else { return(true); } } public void removeTreeModelListener(TreeModelListener l) {} public void valueForPathChanged(TreePath path, Object newValue) {} } private class WindowRenderer implements TreeCellRenderer, ListCellRenderer { public WindowRenderer() { } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { return(get(value, selected)); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { return(get(value, isSelected)); } private Component get(Object value, boolean selected) { Component result = new JLabel(((ClassNode)value).toString()); if(selected) { result.setBackground(Color.blue); result.setForeground(Color.white); JPanel resPane = new JPanel(); resPane.setLayout(new BorderLayout()); resPane.add(result, BorderLayout.CENTER); return(resPane); } else { return(result); } } } private class PropertyDialog extends JDialog { public boolean showAll = false; JComboBox visibleCombo; JCheckBox showToString; JCheckBox showReflection; JCheckBox showEvents; DefaultListModel viewTabs; JList orderList; JButton up; JButton down; Properties props; File propFile; public PropertyDialog(JFrame owner) { super(owner, "Properties", true); propFile = new File(System.getProperty("user.home") + System.getProperty("file.separator") + ".guibrowser"); props = new Properties(); String[] cpItems = {"Showing", "All"}; visibleCombo = new JComboBox(cpItems); visibleCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showAll = (visibleCombo.getSelectedIndex() == 1); } }); JPanel visiblePane = new JPanel(); visiblePane.add(new JLabel("Show ")); visiblePane.add(visibleCombo); showToString = new JCheckBox("Show toString() method result"); showToString.setSelected(true); JPanel compTreePane = new JPanel(); compTreePane.add(visiblePane); viewTabs = new DefaultListModel(); viewTabs.addElement(WINDOWS_TAB); viewTabs.addElement(COMPONENTS_TAB); viewTabs.addElement(PROPERTIES_TAB); viewTabs.addElement(REFLECTION_TAB); viewTabs.addElement(IMAGE_TAB); orderList = new JList(viewTabs); orderList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { up.setEnabled(orderList.getSelectedIndex() > -1); down.setEnabled(orderList.getSelectedIndex() > -1); } }); showReflection = new JCheckBox("Show reflection tab"); showReflection.setSelected(true); showReflection.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(showReflection.isSelected()) { viewTabs.addElement(REFLECTION_TAB); } else { viewTabs.remove(viewTabs.indexOf(REFLECTION_TAB)); } up.setEnabled(orderList.getSelectedIndex() > -1); down.setEnabled(orderList.getSelectedIndex() > -1); } }); showEvents = new JCheckBox("Show event tab"); showEvents.setSelected(true); showEvents.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(showEvents.isSelected()) { viewTabs.addElement(EVENT_TAB); } else { viewTabs.remove(viewTabs.indexOf(EVENT_TAB)); } up.setEnabled(orderList.getSelectedIndex() > -1); down.setEnabled(orderList.getSelectedIndex() > -1); } }); up = new JButton("Move Up"); up.setEnabled(false); up.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int index = orderList.getSelectedIndex(); if(index > 0) { viewTabs.add(index - 1, viewTabs.remove(index)); orderList.setSelectedIndex(index - 1); } } }); down = new JButton("Move Down"); down.setEnabled(false); down.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int index = orderList.getSelectedIndex(); if(index < viewTabs.size() - 1) { viewTabs.add(index + 1, viewTabs.remove(index)); orderList.setSelectedIndex(index + 1); } } }); JPanel movePane = new JPanel(); movePane.add(showEvents); movePane.add(showReflection); movePane.add(up); movePane.add(down); JPanel compViewPane = new JPanel(); compViewPane.setLayout(new BorderLayout()); compViewPane.add(new JLabel("Tab order:"), BorderLayout.NORTH); compViewPane.add(movePane, BorderLayout.SOUTH); compViewPane.add(orderList, BorderLayout.CENTER); JTabbedPane tbpn = new JTabbedPane(); tbpn.add("Component Tree", compTreePane); tbpn.add("Component View", compViewPane); JButton okBUtton = new JButton("OK"); okBUtton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { save(); setVisible(false); } }); JButton cnBUtton = new JButton("Cancel"); cnBUtton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); load(); } }); JPanel pn = new JPanel(); pn.add(okBUtton); pn.add(cnBUtton); getContentPane().setLayout(new BorderLayout()); getContentPane().add(pn, BorderLayout.SOUTH); getContentPane().add(tbpn, BorderLayout.CENTER); load(); setSize(400, 400); } private void save() { try { props.setProperty("guibrowser.showall", showAll ? "on" : "off"); for(int i = 0; i < viewTabs.size(); i++) { props.setProperty("guibrowser.viewpage_" + Integer.toString(i), (String)viewTabs.elementAt(i)); } props.store(new FileOutputStream(propFile), "Jemmy GUIBrowser"); } catch(IOException e) { e.printStackTrace(); } } private void load() { if(propFile.exists()) { try { props.load(new FileInputStream(propFile)); showAll = props.getProperty("guibrowser.showall") == null || props.getProperty("guibrowser.showall").equals("") || props.getProperty("guibrowser.showall").equals("on"); visibleCombo.setSelectedIndex(showAll ? 1 : 0); if( props.getProperty("guibrowser.viewpage_0") != null && !props.getProperty("guibrowser.viewpage_0").equals("")) { viewTabs.removeAllElements(); viewTabs.addElement(props.getProperty("guibrowser.viewpage_0")); viewTabs.addElement(props.getProperty("guibrowser.viewpage_1")); viewTabs.addElement(props.getProperty("guibrowser.viewpage_2")); if( props.getProperty("guibrowser.viewpage_3") != null && !props.getProperty("guibrowser.viewpage_3").equals("")) { viewTabs.addElement(props.getProperty("guibrowser.viewpage_3")); } if( props.getProperty("guibrowser.viewpage_4") != null && !props.getProperty("guibrowser.viewpage_4").equals("")) { viewTabs.addElement(props.getProperty("guibrowser.viewpage_4")); } } } catch(IOException e) { e.printStackTrace(); } showReflection.setSelected(viewTabs.indexOf(REFLECTION_TAB) > -1); showEvents.setSelected(viewTabs.indexOf(EVENT_TAB) > -1); } } } private class ComponentBrowser extends JFrame { JTree winTree; JTree componentTree; JTree methodTree; ClassNode compNode; JTabbedPane tbd; JButton viewButton; JButton expandButton; JSplitPane winSplit = null; JSplitPane componentSplit = null; WindowRenderer renderer; SelectionManager selManager; JList eventList; ListListener listListener; DefaultListModel eventModel; JCheckBox mouseEvents; JCheckBox mouseMotionEvents; JCheckBox keyEvents; public ComponentBrowser(JFrame owner, ClassNode componentNode) { super("Component " + componentNode.toString()); fill(componentNode); } private void fill(ClassNode componentNode) { compNode = componentNode; viewButton = new JButton("View"); viewButton.setEnabled(false); viewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new ComponentBrowser(getOwnr(), getSelectedNode()). show(); } }); expandButton = new JButton("Expand All"); expandButton.setEnabled(false); expandButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { expandAll(getSelectedTree(), getSelectionPath()); } }); JPanel buttonPane = new JPanel(); buttonPane.add(viewButton); buttonPane.add(expandButton); Component[] cpss = {viewButton, expandButton}; selManager = new SelectionManager(cpss); renderer = new WindowRenderer(); tbd = new JTabbedPane(); for(int i = 0; i < propDialog.viewTabs.size(); i++) { String next = (String)propDialog.viewTabs.elementAt(i); if (next.equals(PROPERTIES_TAB)) { addPropertiesTab(); } else if(next.equals(WINDOWS_TAB)) { addWindowTab(); } else if(next.equals(COMPONENTS_TAB)) { addComponentTab(); } else if(next.equals(REFLECTION_TAB)) { addReflectionTab(); } else if(next.equals(EVENT_TAB)) { addEventTab(); } else if(next.equals(IMAGE_TAB)) { addImageTab(); } } tbd.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { viewButton.setEnabled(getSelectedNode() != null); } }); getContentPane().setLayout(new BorderLayout()); getContentPane().add(buttonPane, BorderLayout.SOUTH); getContentPane().add(tbd, BorderLayout.CENTER); addComponentListener(new ComponentListener() { public void componentHidden(ComponentEvent e) {} public void componentMoved(ComponentEvent e) {} public void componentResized(ComponentEvent e) { if(winSplit != null) { winSplit.setDividerLocation(0.8); } if(componentSplit != null) { componentSplit.setDividerLocation(0.8); } } public void componentShown(ComponentEvent e) {} }); setSize(800, 400); } private void addImageTab() { BufferedImage image = null; if(compNode instanceof ComponentNode) { image = ((ComponentNode)compNode).getImage(); } if(image != null) { JPanel imagePane = new ImagePane(image); imagePane.prepareImage(image, imagePane); JScrollPane pane = new JScrollPane(imagePane); tbd.add(IMAGE_TAB, pane); } } private void addWindowTab() { if(compNode instanceof WindowNode && ((WindowNode)compNode).getWindows().length > 0) { winTree = new JTree(((WindowNode)compNode).getWindowModel()); winTree.setCellRenderer(renderer); winTree.setEditable(false); winTree.addTreeSelectionListener(selManager); winSplit = createUnderPane(winTree); tbd.add(WINDOWS_TAB, winSplit); } } private void addComponentTab() { if(compNode instanceof ContainerNode && ((ContainerNode)compNode).getComponents().length > 0) { componentTree = new JTree(((ContainerNode)compNode).getComponentModel()); componentTree.setCellRenderer(renderer); componentTree.setEditable(false); componentTree.addTreeSelectionListener(selManager); componentSplit = createUnderPane(componentTree); tbd.add(COMPONENTS_TAB, componentSplit); } } private void addReflectionTab() { methodTree = new JTree(compNode.getMethodsModel()); methodTree.setCellRenderer(renderer); methodTree.setEditable(false); methodTree.addTreeSelectionListener(selManager); tbd.add(REFLECTION_TAB, new JScrollPane(methodTree)); } private void addPropertiesTab() { if(compNode instanceof ComponentNode) { Hashtable props = ((ContainerNode)compNode).getProperties(); if(props.size() > 0) { JTable propTable = new JTable(new MyModel(props)); propTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); tbd.add(PROPERTIES_TAB, new JScrollPane(propTable)); /* propTable.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { new ComponentBrowser(getOwnr(), getSelectedNode()). show(); } public void mouseExited(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } }); */ } } } private void addEventTab() { if(compNode instanceof ComponentNode) { eventModel = new DefaultListModel(); eventList = new JList(eventModel); listListener = new ListListener(eventModel, ((ComponentNode)compNode).comp); mouseEvents = new JCheckBox("Mouse events"); mouseEvents.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(mouseEvents.isSelected()) { listListener.addMouseListener(); } else { listListener.removeMouseListener(); } } }); mouseMotionEvents = new JCheckBox("Mouse motion events"); mouseMotionEvents.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(mouseMotionEvents.isSelected()) { listListener.addMouseMotionListener(); } else { listListener.removeMouseMotionListener(); } } }); keyEvents = new JCheckBox("Key events"); keyEvents.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(keyEvents.isSelected()) { listListener.addKeyListener(); } else { listListener.removeKeyListener(); } } }); JButton clear = new JButton("Clear list"); clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { eventModel.removeAllElements(); } }); JPanel checkPane = new JPanel(); checkPane.add(mouseEvents); checkPane.add(mouseMotionEvents); checkPane.add(keyEvents); checkPane.add(clear); JPanel subPane = new JPanel(); subPane.setLayout(new BorderLayout()); subPane.add(checkPane, BorderLayout.SOUTH); subPane.add(new JScrollPane(eventList), BorderLayout.CENTER); tbd.add(EVENT_TAB, subPane); } } private JFrame getOwnr() { return(this); } private JTree getSelectedTree() { String title = tbd.getTitleAt(tbd.getSelectedIndex()); if(title.equals(WINDOWS_TAB)) { return(winTree); } else if(title.equals(COMPONENTS_TAB)) { return(componentTree); } else if(title.equals(REFLECTION_TAB)) { return(methodTree); } return(null); } private TreePath getSelectionPath() { JTree tree = getSelectedTree(); if(tree != null) { return(tree.getSelectionPath()); } else { return(null); } } private ClassNode getSelectedNode() { TreePath path = getSelectionPath(); if(path != null) { return((ClassNode)path.getLastPathComponent()); } else { return(null); } } } private class SelectionManager implements TreeSelectionListener, ListSelectionListener { Component[] comps; public SelectionManager(Component[] comps) { this.comps = comps; } public void valueChanged(TreeSelectionEvent e) { for(int i = 0; i < comps.length; i++) { comps[i].setEnabled(e.getPath() != null); } } public void valueChanged(ListSelectionEvent e) { for(int i = 0; i < comps.length; i++) { comps[i].setEnabled(e.getFirstIndex() != -1); } } } private void expandAll(JTree tree, TreePath path) { tree.expandPath(path); TreeModel model = tree.getModel(); Object lastComponent = path.getLastPathComponent(); for(int i = 0; i < model.getChildCount(lastComponent); i++) { expandAll(tree, path.pathByAddingChild(model.getChild(lastComponent, i))); } } private class ToStringListener implements TreeSelectionListener{ JTextArea area; public ToStringListener(JTextArea area) { this.area = area; } public void valueChanged(TreeSelectionEvent e) { if(e.getPath() != null && e.getPath().getLastPathComponent() instanceof ComponentNode) { area.setText("toString(): " + ((ComponentNode)e.getPath().getLastPathComponent()). getToString()); } else { area.setText(""); } } } private JSplitPane createUnderPane(JTree tree) { JTextArea toStringArea = new JTextArea(); toStringArea.setLineWrap(true); toStringArea.setEditable(false); tree.addTreeSelectionListener(new ToStringListener(toStringArea)); JSplitPane result = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(tree), new JScrollPane(toStringArea)); result.setOneTouchExpandable(true); result.setDividerSize(8); result.setDividerLocation(0.8); return(result); } private class MyModel extends DefaultTableModel { public MyModel(Hashtable props) { super(); Object[] keys = props.keySet().toArray(); if(keys.length > 0) { addColumn("Name"); addColumn("Value"); setNumRows(keys.length); for(int i = 0; i < keys.length; i++) { setValueAt(keys[i].toString(), i, 0); setValueAt(props.get(keys[i]).toString(), i, 1); } Collections.sort(getDataVector(), new Comparator() { public int compare(Object o1, Object o2) { return(((Vector)o1).get(0).toString().compareTo(((Vector)o2).get(0).toString())); } public boolean equals(Object obj) { return(false); } }); } } public boolean isCellEditable(int x, int y) { return(false); } } private class ListListener extends TrialListenerManager { DefaultListModel model; public ListListener(DefaultListModel m, Component comp) { super(comp); model = m; } void printEvent(AWTEvent e) { model.addElement(e); } } private class ImagePane extends JPanel { BufferedImage image; public ImagePane(BufferedImage image) { super(); this.image = image; setPreferredSize(new Dimension(image.getWidth(), image.getHeight())); } public void paint(Graphics g) { g.drawImage(image, 0, 0, null); } } private class ComponentImageProvider { BufferedImage image; int x; int y; public ComponentImageProvider(BufferedImage image, int x, int y) { this.image = image; this.x = x; this.y = y; } public BufferedImage getImage(int x, int y, int w, int h) { /* BufferedImage newImage = image.getSubimage(0, 0, image.getWidth(), image.getHeight()); Graphics g = newImage.getGraphics(); g.setColor(Color.RED); g.drawRect(x - this.x, y - this.y, w, h); return(newImage); */ int realW = Math.min(image.getWidth() - x, w); int realH = Math.min(image.getHeight() - y, h); return(image.getSubimage(x - this.x, y - this.y, realW, realH)); } } } Jemmy2/src/org/netbeans/jemmy/accessibility/0000755000175000017500000000000011572745222020121 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/accessibility/AccessibleDescriptionChooser.java0000644000175000017500000000573211064436407026555 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.accessibility; import javax.accessibility.AccessibleContext; import org.netbeans.jemmy.operators.Operator; import org.netbeans.jemmy.operators.Operator.StringComparator; public class AccessibleDescriptionChooser extends AccessibilityChooser { String description; StringComparator comparator; public AccessibleDescriptionChooser(String description, StringComparator comparator) { this.description = description; this.comparator = comparator; } public AccessibleDescriptionChooser(String description) { this(description, Operator.getDefaultStringComparator()); } public final boolean checkContext(AccessibleContext context) { return(comparator.equals(context.getAccessibleDescription(), description)); } public String getDescription() { return("JComponent with \"" + description + "\" accessible description"); } } Jemmy2/src/org/netbeans/jemmy/accessibility/AccessibilityChooser.java0000644000175000017500000000600511245712237025074 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.accessibility; import java.awt.Component; import javax.accessibility.AccessibleContext; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JWindow; import org.netbeans.jemmy.ComponentChooser; public abstract class AccessibilityChooser implements ComponentChooser { public final boolean checkComponent(Component comp) { if(comp instanceof JComponent) { return(checkContext(comp.getAccessibleContext())); } else if(comp instanceof JDialog) { return(checkContext(comp.getAccessibleContext())); } else if(comp instanceof JFrame) { return(checkContext(comp.getAccessibleContext())); } else if(comp instanceof JWindow) { return(checkContext(comp.getAccessibleContext())); } else { return(false); } } public abstract boolean checkContext(AccessibleContext context); } Jemmy2/src/org/netbeans/jemmy/accessibility/AccessibleNameChooser.java0000644000175000017500000000557711064436407025161 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.accessibility; import javax.accessibility.AccessibleContext; import org.netbeans.jemmy.operators.Operator; import org.netbeans.jemmy.operators.Operator.StringComparator; public class AccessibleNameChooser extends AccessibilityChooser { String name; StringComparator comparator; public AccessibleNameChooser(String name, StringComparator comparator) { this.name = name; this.comparator = comparator; } public AccessibleNameChooser(String name) { this(name, Operator.getDefaultStringComparator()); } public final boolean checkContext(AccessibleContext context) { return(comparator.equals(context.getAccessibleName(), name)); } public String getDescription() { return("JComponent with \"" + name + "\" accessible name"); } } Jemmy2/src/org/netbeans/jemmy/JemmyProperties.java0000644000175000017500000007462511245712237021306 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.util.Enumeration; import java.util.Hashtable; import java.util.Properties; import java.util.Stack; import java.util.StringTokenizer; import org.netbeans.jemmy.drivers.APIDriverInstaller; import org.netbeans.jemmy.drivers.DefaultDriverInstaller; import org.netbeans.jemmy.drivers.DriverInstaller; import org.netbeans.jemmy.drivers.InputDriverInstaller; import org.netbeans.jemmy.explorer.GUIBrowser; /** * * Keeps default Jemmy properties. * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class JemmyProperties { /** * The event queue model mask. * @see #getCurrentDispatchingModel() * @see #setCurrentDispatchingModel(int) */ public static int QUEUE_MODEL_MASK = 1; /** * The robot using model mask. * @see #getCurrentDispatchingModel() * @see #setCurrentDispatchingModel(int) */ public static int ROBOT_MODEL_MASK = 2; /** * Event shorcutting model mask. Should not be used * together with robot mask. * @see #getCurrentDispatchingModel() * @see #setCurrentDispatchingModel(int) */ public static int SHORTCUT_MODEL_MASK = 4; /** * The robot using model mask. * @see #getCurrentDispatchingModel() * @see #setCurrentDispatchingModel(int) */ public static int SMOOTH_ROBOT_MODEL_MASK = 8; private static final int DEFAULT_DRAG_AND_DROP_STEP_LENGTH = 100; private static Stack propStack = null; Hashtable properties; /***/ protected JemmyProperties() { super(); properties = new Hashtable(); setProperty("timeouts", new Timeouts()); setProperty("output", new TestOut()); setProperty("resources", new BundleManager()); setProperty("binding.map", new DefaultCharBindingMap()); setProperty("dispatching.model", new Integer(getDefaultDispatchingModel())); setProperty("drag_and_drop.step_length", new Integer(DEFAULT_DRAG_AND_DROP_STEP_LENGTH)); } /** * Returns major version (like 1.0). * @return a String representing the major version value. */ public static String getMajorVersion() { return(extractValue(getProperties().getClass(). getClassLoader().getResourceAsStream("org/netbeans/jemmy/version_info"), "Jemmy-MajorVersion")); } /** * Returns minor version (like 1). * @return a String representing the minor version value. */ public static String getMinorVersion() { return(extractValue(getProperties().getClass(). getClassLoader().getResourceAsStream("org/netbeans/jemmy/version_info"), "Jemmy-MinorVersion")); } /** * Returns build (like 20011231 (yyyymmdd)). * @return a String representing the build value. */ public static String getBuild() { return(extractValue(getProperties().getClass(). getClassLoader().getResourceAsStream("org/netbeans/jemmy/version_info"), "Jemmy-Build")); } /** * Returns full version string (like 1.0.1-20011231). * @return a String representing the full version value. */ public static String getFullVersion() { return(getMajorVersion() + "." + getMinorVersion() + "-" + getBuild()); } /** * Returns version string (like 1.0.1). * @return a String representing the short version value. */ public static String getVersion() { return(getMajorVersion() + "." + getMinorVersion()); } /** * Creates a copy of the current JemmyProperties object * and pushes it into the properties stack. * @return New current properties. */ public static JemmyProperties push() { return(push(getProperties().cloneThis())); } /** * Pops last pushed properties from the properties stack. * If stack has just one element, does nothing. * @return Poped properties. */ public static JemmyProperties pop() { JemmyProperties result = (JemmyProperties)propStack.pop(); if(propStack.isEmpty()) { propStack.push(result); } return(result); } /** * Just like getProperties().getProperty(propertyName). * @param propertyName a property key * @return a property value * @see #setCurrentProperty * @see #setCurrentTimeout */ public static Object getCurrentProperty(String propertyName) { return(getProperties().getProperty(propertyName)); } /** * Just like getProperties().setProperty(propertyName, propertyValue). * @param propertyName a property key * @param propertyValue a property value * @return previous property value * @see #getCurrentProperty * @see #getCurrentTimeout */ public static Object setCurrentProperty(String propertyName, Object propertyValue) { return(getProperties().setProperty(propertyName, propertyValue)); } /** * Removes a property from current properties list. * @param propertyName a property key. * @return previous property value */ public static Object removeCurrentProperty(String propertyName) { return(getProperties().removeProperty(propertyName)); } /** * Returns the current key values. * @return an array of Strings representing the current key values */ public static String[] getCurrentKeys() { return(getProperties().getKeys()); } /** * Just like getProperties().getTimeouts(). * @return a Timeouts object representing the current timeouts. * @see #setCurrentTimeouts */ public static Timeouts getCurrentTimeouts() { return(getProperties().getTimeouts()); } /** * Just like getProperties().setTimeouts(to). * @param to New timeouts * @return old timeouts. * @see #getCurrentTimeouts */ public static Timeouts setCurrentTimeouts(Timeouts to) { return(getProperties().setTimeouts(to)); } /** * Just like getProperties().getTimeouts().setTimeout(name, newValue). * @param name a timeout name * @param newValue a timeout value * @return previous timeout value * @see #getCurrentTimeout */ public static long setCurrentTimeout(String name, long newValue) { return(getProperties().getTimeouts().setTimeout(name, newValue)); } /** * Just like getProperties().getTimeouts().getTimeout(name). * @param name a timeout name * @return a timeout value * @see #setCurrentTimeout */ public static long getCurrentTimeout(String name) { return(getProperties().getTimeouts().getTimeout(name)); } /** * Just like getProperties().getTimeouts().initTimeout(name, newValue). * @param name a timeout name * @param newValue a timeout value * @return a timeout value * @see #setCurrentTimeout */ public static long initCurrentTimeout(String name, long newValue) { return(getProperties().getTimeouts().initTimeout(name, newValue)); } /** * Just like getProperties().getOutput(). * @return a TestOut object representing the current output. * @see #setCurrentOutput */ public static TestOut getCurrentOutput() { return(getProperties().getOutput()); } /** * Just like getProperties().setOutput(out). * @param out new output * @return a TestOut object representing the current output. * @see #getCurrentOutput */ public static TestOut setCurrentOutput(TestOut out) { return(getProperties().setOutput(out)); } /** * Just like getProperties().getBundleManager(). * @return a BundleManager object representing the current bundle manager. * @see #setCurrentBundleManager */ public static BundleManager getCurrentBundleManager() { return(getProperties().getBundleManager()); } /** * Just like getProperties().setBundleManager(resources). * @param resources new BundleManager * @return a BundleManager object representing the current bundle manager. * @see #getCurrentBundleManager */ public static BundleManager setCurrentBundleManager(BundleManager resources) { return(getProperties().setBundleManager(resources)); } /** * Just like getProperties().getBundleManager().getResource(key). * @param key a resource key. * @return a resource value */ public static String getCurrentResource(String key) { return(getProperties().getBundleManager().getResource(key)); } /** * Just like getProperties().getBundleManager().getResource(bundleID, key). * @param key a resource key. * @param bundleID a bundle ID * @return a resource value */ public static String getCurrentResource(String bundleID, String key) { return(getProperties().getBundleManager().getResource(bundleID, key)); } /** * Just like getProperties().getCharBindingMap(). * @return a CharBindingMap object representing the current char binding map. * @see #setCurrentCharBindingMap */ public static CharBindingMap getCurrentCharBindingMap() { return(getProperties().getCharBindingMap()); } /** * Just like getProperties().setCharBindingMap(map). * @param map new CharBindingMap. * @return old CharBindingMap object. * @see #getCurrentCharBindingMap */ public static CharBindingMap setCurrentCharBindingMap(CharBindingMap map) { return(getProperties().setCharBindingMap(map)); } /** * Returns the current dispatching model. * @return Event dispatching model. * @see #getDispatchingModel() * @see #setCurrentDispatchingModel(int) * @see #QUEUE_MODEL_MASK * @see #ROBOT_MODEL_MASK */ public static int getCurrentDispatchingModel() { return(getProperties().getDispatchingModel()); } /** * Defines event dispatching model. * If (model & ROBOT_MODEL_MASK) != 0 java.awt.Robot class * is used to reproduce user actions, otherwise actions * are reproduced by event posting. * If (model & QUEUE_MODEL_MASK) != 0 actions are reproduced through * event queue. * @param model New dispatching model value. * @return Previous dispatching model value. * @see #setDispatchingModel(int) * @see #getCurrentDispatchingModel() * @see #QUEUE_MODEL_MASK * @see #ROBOT_MODEL_MASK * @see #initDispatchingModel(boolean, boolean) * @see #initDispatchingModel() */ public static int setCurrentDispatchingModel(int model) { return(getProperties().setDispatchingModel(model)); } /** * Returns default event dispatching model. * @return QUEUE_MODEL_MASK * @see #setCurrentDispatchingModel(int) * @see #QUEUE_MODEL_MASK * @see #ROBOT_MODEL_MASK */ public static int getDefaultDispatchingModel() { return(SHORTCUT_MODEL_MASK | QUEUE_MODEL_MASK); } /** * Returns the current drag and drop step length value. * @return Pixel count to move mouse during one drag'n'drop step. * @see #getDragAndDropStepLength() * @see #setCurrentDragAndDropStepLength(int) */ public static int getCurrentDragAndDropStepLength() { return(getProperties().getDragAndDropStepLength()); } /** * Specifies the current drag and drop step length value. * @param model Pixel count to move mouse during one drag'n'drop step. * @return Previous value. * @see #setDragAndDropStepLength(int) * @see #getCurrentDragAndDropStepLength() */ public static int setCurrentDragAndDropStepLength(int model) { return(getProperties().setDragAndDropStepLength(model)); } /** * Peeks upper JemmyProperties instance from stack. * @return a JemmyProperties object representing the properties value. */ public static JemmyProperties getProperties() { if(propStack == null) { propStack = new Stack(); } if(propStack.empty()) { propStack.add(new JemmyProperties()); } return((JemmyProperties)propStack.peek()); } /** * Prints full version into satndart output. * @param argv Application args. */ public static void main(String[] argv) { if(argv.length == 0) { System.out.println("Jemmy version : " + getVersion()); } else if(argv.length == 1 && argv[0].equals("-f")) { System.out.println("Jemmy full version : " + getFullVersion()); } else if(argv.length > 0 && argv[0].equals("-e")) { String[] newArgv = new String[argv.length -1]; for(int i = 1; i < argv.length; i++) { newArgv[i-1] = argv[i]; } GUIBrowser.main(newArgv); } else { System.out.println("Parameters: "); System.out.println(" - report Jemmy version."); System.out.println("\"-f\" - report full jemmy version."); } } /** * Pushes properties stack. * @param props a JemmyProperties instance to put into the stack head. * @return a JemmyProperties object. */ protected static JemmyProperties push(JemmyProperties props) { return((JemmyProperties)propStack.push(props)); } static { setCurrentDispatchingModel(getDefaultDispatchingModel()); } /** * Method to initialize timeouts and resources. * @param prop_file File to get filenames from.
* Can contain definition of variables TIMEOUTS_FILE - full path to timeouts file,
* RESOURCE_FILE - full path to resource file. * @see org.netbeans.jemmy.JemmyProperties#initProperties() */ public void initProperties(String prop_file) { try { getOutput().printLine("Loading properties from " + prop_file + " file"); Properties props = new Properties(); props.load(new FileInputStream(prop_file)); if(props.getProperty("TIMEOUTS_FILE") != null && !props.getProperty("TIMEOUTS_FILE").equals("")) { getOutput().printLine("Loading timeouts from " + props.getProperty("TIMEOUTS_FILE") + " file"); getTimeouts().loadDefaults(props.getProperty("TIMEOUTS_FILE")); } if(props.getProperty("RESOURCE_FILE") != null && !props.getProperty("RESOURCE_FILE").equals("")) { getOutput().printLine("Loading resources from " + props.getProperty("RESOURCE_FILE") + " file"); getBundleManager().loadBundleFromFile(props.getProperty("RESOURCE_FILE"), ""); } } catch(IOException e) { getOutput().printStackTrace(e); } } /** * Method to initialize timeouts and resources.
* Uses jemmy.properties system property to find file. * @see org.netbeans.jemmy.JemmyProperties#initProperties(String) */ public void initProperties() { if(System.getProperty("jemmy.properties") != null && !System.getProperty("jemmy.properties").equals("")) { initProperties(System.getProperty("jemmy.properties")); } else { try { getTimeouts().load(); getBundleManager().load(); } catch(IOException e) { getOutput().printStackTrace(e); } } } /** * Initializes dispatching model. * @param queue Notifies that event queue dispatching should be used. * @param robot Notifies that robot dispatching should be used. * @param shortcut Notifies that event shorcutting should be used. */ public void initDispatchingModel(boolean queue, boolean robot, boolean shortcut) { initDispatchingModel(queue, robot, shortcut, false); } /** * Initializes dispatching model. * @param queue Notifies that event queue dispatching should be used. * @param robot Notifies that robot dispatching should be used. * @param shortcut Notifies that event shorcutting should be used. */ public void initDispatchingModel(boolean queue, boolean robot, boolean shortcut, boolean smooth) { int model = getDefaultDispatchingModel(); getOutput().print("Reproduce user actions "); if(queue) { model = QUEUE_MODEL_MASK; getOutput().printLine("through event queue."); } else { model = model - (model & QUEUE_MODEL_MASK); getOutput().printLine("directly."); } getOutput().print("Use "); if(robot) { model = model | ROBOT_MODEL_MASK; getOutput().print("java.awt.Robot class"); } else { model = model - (model & ROBOT_MODEL_MASK); getOutput().print("event dispatching"); } if(smooth) { model = model | SMOOTH_ROBOT_MODEL_MASK; } else { model = model - (model & SMOOTH_ROBOT_MODEL_MASK); } getOutput().printLine(" to reproduce user actions"); if(shortcut) { model = model | SHORTCUT_MODEL_MASK; getOutput().print("Shortcut"); } else { model = model - (model & SHORTCUT_MODEL_MASK); getOutput().print("Dispatch"); } getOutput().printLine(" test events"); setDispatchingModel(model); } /** * Initializes dispatching model. * @param queue Notifies that event queue dispatching should be used. * @param robot Notifies that robot dispatching should be used. */ public void initDispatchingModel(boolean queue, boolean robot) { this.initDispatchingModel(queue, robot, false); } /** * Initializes dispatching model. * Uses "jemmy.queue_dispatching" and "jemmy.robot_dispatching" system properties * to determine what model should be used. * Possible values for the both properties:
* "off" - switch mode off.
* "on" - switch mode on.
* "" - use default value. * @see #getDefaultDispatchingModel() */ public void initDispatchingModel() { boolean qmask = ((getDefaultDispatchingModel() & QUEUE_MODEL_MASK) != 0); boolean rmask = ((getDefaultDispatchingModel() & ROBOT_MODEL_MASK) != 0); boolean srmask = ((getDefaultDispatchingModel() & SMOOTH_ROBOT_MODEL_MASK) != 0); boolean smask = ((getDefaultDispatchingModel() & SHORTCUT_MODEL_MASK) != 0); if( System.getProperty("jemmy.queue_dispatching") != null && !System.getProperty("jemmy.queue_dispatching").equals("")) { qmask = System.getProperty("jemmy.queue_dispatching").equals("on"); } if( System.getProperty("jemmy.robot_dispatching") != null && !System.getProperty("jemmy.robot_dispatching").equals("")) { rmask = System.getProperty("jemmy.robot_dispatching").equals("on"); } if( System.getProperty("jemmy.smooth_robot_dispatching") != null && !System.getProperty("jemmy.smooth_robot_dispatching").equals("")) { srmask = System.getProperty("jemmy.smooth_robot_dispatching").equals("on"); } if( System.getProperty("jemmy.shortcut_events") != null && !System.getProperty("jemmy.shortcut_events").equals("")) { smask = System.getProperty("jemmy.shortcut_events").equals("on"); } initDispatchingModel(qmask, rmask, smask, srmask); } /** * Inits properties and dispatching model from system environment variables. * @see #initProperties() * @see #initDispatchingModel() */ public void init() { initProperties(); initDispatchingModel(); } /** * Returns timeouts. * @return the Timeouts value. * @see #setTimeouts */ public Timeouts getTimeouts() { return((Timeouts)getProperty("timeouts")); } /** * Changes timeouts. * @param to new timeouts. * @return old timeouts. * @see #getTimeouts */ public Timeouts setTimeouts(Timeouts to) { return((Timeouts)setProperty("timeouts", to)); } /** * Changes a timeouts value. * @param name Timeout name * @param newValue New timeout value * @return previous timeout value * @see #getTimeout */ public long setTimeout(String name, long newValue) { return(getTimeouts().setTimeout(name, newValue)); } /** * Returns a timeouts value. * @param name Timeout name * @return a timeout value * @see #setTimeout */ public long getTimeout(String name) { return(getTimeouts().getTimeout(name)); } /** * Inits a timeouts value. * @param name Timeout name * @param newValue New timeout value * @return a timeout value */ public long initTimeout(String name, long newValue) { return(getTimeouts().initTimeout(name, newValue)); } /** * Returns output. * @return a TestOut object representing the output value * @see #setOutput */ public TestOut getOutput() { return((TestOut)getProperty("output")); } /** * Changes output. * @param out new output. * @return old output. * @see #getOutput */ public TestOut setOutput(TestOut out) { return((TestOut)setProperty("output", out)); } /** * Returns bundle manager. * @return a BundleManager object representing the bundle manager value. * @see #setBundleManager */ public BundleManager getBundleManager() { return((BundleManager)getProperty("resources")); } /** * Changes bundle manager. * @param resources new bundle manager. * @return old bundle manager * @see #getBundleManager */ public BundleManager setBundleManager(BundleManager resources) { return((BundleManager)setProperty("resources", resources)); } /** * Returns resource value. * @param key Resource key. * @return resource value */ public String getResource(String key) { return(getBundleManager().getResource(key)); } /** * Returns resource value from the specified bundle. * @param bundleID Id of a bundle to get resource from. * @param key Resource key. * @return resource value */ public String getResource(String bundleID, String key) { return(getBundleManager().getResource(bundleID, key)); } /** * Returns char binding map. * @return the char binding map. * @see #setCharBindingMap */ public CharBindingMap getCharBindingMap() { return((CharBindingMap)getProperty("binding.map")); } /** * Changes char binding map. * @param map new char binding map. * @return old char binding map. * @see #getCharBindingMap */ public CharBindingMap setCharBindingMap(CharBindingMap map) { return((CharBindingMap)setProperty("binding.map", map)); } /** * Returns the dispatching model. * @return Event dispatching model. * @see #getCurrentDispatchingModel() * @see #setDispatchingModel(int) * @see #QUEUE_MODEL_MASK * @see #ROBOT_MODEL_MASK */ public int getDispatchingModel() { return(((Integer)getProperty("dispatching.model")).intValue()); } private static DriverInstaller getDriverInstaller(int model) { String name = System.getProperty("jemmy.drivers.installer"); DriverInstaller installer = null; try { if(name != null && !(name.length() == 0)) { installer = (DriverInstaller)new ClassReference(name).newInstance(null, null); } } catch(ClassNotFoundException e) { getCurrentOutput().printLine("Cannot init driver installer:"); getCurrentOutput().printStackTrace(e); } catch(IllegalAccessException e) { getCurrentOutput().printLine("Cannot init driver installer:"); getCurrentOutput().printStackTrace(e); } catch(NoSuchMethodException e) { getCurrentOutput().printLine("Cannot init driver installer:"); getCurrentOutput().printStackTrace(e); } catch(InstantiationException e) { getCurrentOutput().printLine("Cannot init driver installer:"); getCurrentOutput().printStackTrace(e); } catch(InvocationTargetException e) { getCurrentOutput().printLine("Cannot init driver installer:"); getCurrentOutput().printStackTrace(e); } if(installer == null) { if(System.getProperty("os.name").startsWith("Mac OS X")) { installer = new APIDriverInstaller((model & SHORTCUT_MODEL_MASK) != 0); } else { installer = new DefaultDriverInstaller((model & SHORTCUT_MODEL_MASK) != 0); } }; getCurrentOutput().printLine("Using " + installer.getClass().getName() + " driver installer"); return(installer); } /** * Specifies the dispatching model value. * @param model New dispatching model value. * @return Previous dispatching model value. * @see #setCurrentDispatchingModel(int) * @see #getDispatchingModel() * @see #QUEUE_MODEL_MASK * @see #ROBOT_MODEL_MASK */ public int setDispatchingModel(int model) { new InputDriverInstaller((model & ROBOT_MODEL_MASK) == 0, (model & SMOOTH_ROBOT_MODEL_MASK) != 0).install(); getDriverInstaller(model).install(); return(((Integer)setProperty("dispatching.model", new Integer(model))).intValue()); } /** * Returns the drag and drop step length value. * @return Pixel count to move mouse during one drag'n'drop step. * @see #getCurrentDragAndDropStepLength() * @see #setDragAndDropStepLength(int) */ public int getDragAndDropStepLength() { return(((Integer)getProperty("drag_and_drop.step_length")).intValue()); } /** * Specifies the drag and drop step length value. * @param length Pixel count to move mouse during one drag'n'drop step. * @return Previous value. * @see #setCurrentDragAndDropStepLength(int) * @see #getDragAndDropStepLength() */ public int setDragAndDropStepLength(int length) { return(((Integer)setProperty("drag_and_drop.step_length", new Integer(length))).intValue()); } /** * Checks if "name" propery currently has a value. * @param name Property name. Should by unique. * @return true if property was defined. * @see #setProperty(String, Object) * @see #getProperty(String) */ public boolean contains(String name) { return(properties.containsKey(name)); } /** * Saves object as a static link to be used by other objects. * @param name Property name. Should by unique. * @param newValue Property value. * @return Previous value of "name" property. * @see #setCurrentProperty(String, Object) * @see #getProperty(String) * @see #contains(String) */ public Object setProperty(String name, Object newValue) { Object oldValue = null; if(contains(name)) { oldValue = properties.get(name); properties.remove(name); } properties.put(name, newValue); return(oldValue); } /** * Returns the property value. * @param name Property name. Should by unique. * @return Property value stored by setProperty(String, Object) method. * @see #getCurrentProperty(String) * @see #setProperty(String, Object) * @see #contains(String) */ public Object getProperty(String name) { if(contains(name)) { return(properties.get(name)); } else { return(null); } } /** * Removes the property. * @param name A name of the property to be removed. * @return previous property value */ public Object removeProperty(String name) { if(contains(name)) { return(properties.remove(name)); } else { return(null); } } /** * Returns the key values. @return an array of Strings representing the key values. */ public String[] getKeys() { Enumeration keys = properties.keys(); String[] result = new String[properties.size()]; int i = 0; while(keys.hasMoreElements()) { result[i] = (String)keys.nextElement(); i++; } return(result); } /** * Copy all properties from this instance into another. * @param properties a JemmyProperties instance to copy properties into. */ public void copyTo(JemmyProperties properties) { String[] keys = getKeys(); for(int i = 0; i < keys.length; i++) { properties.setProperty(keys[i], getProperty(keys[i])); } //some should be cloned properties.setTimeouts(getTimeouts().cloneThis()); properties.setBundleManager(getBundleManager().cloneThis()); } /** * Creates an exact copy on this instance. * @return new JemmyProperties object. */ protected JemmyProperties cloneThis() { JemmyProperties result = new JemmyProperties(); copyTo(result); return(result); } private static String extractValue(InputStream stream, String varName) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringTokenizer token; String nextLine; while((nextLine = reader.readLine()) != null) { token = new StringTokenizer(nextLine, ":"); String nextToken = token.nextToken(); if(nextToken != null && nextToken.trim().equals(varName)) { return(token.nextToken().trim()); } } return(""); } catch(IOException e) { getCurrentOutput().printStackTrace(e); return(""); } } } Jemmy2/src/org/netbeans/jemmy/Timeoutable.java0000644000175000017500000000536411064436407020415 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; /** * * Any class which contains methods requiring waiting or * sleeping should implement this interface. Waiting and * sleeping operations have time limits that can be set or * returned using the methods of this interface. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface Timeoutable { /** * Defines current timeouts. * @param t A collection of timeout assignments. * @see #getTimeouts */ public void setTimeouts(Timeouts t); /** * Return current timeouts. * @return the collection of current timeout assignments. * @see #setTimeouts */ public Timeouts getTimeouts(); } Jemmy2/src/org/netbeans/jemmy/QueueTool.java0000644000175000017500000005351711245712447020072 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.awt.AWTEvent; import java.awt.EventQueue; import java.awt.Toolkit; import java.awt.event.InvocationEvent; import java.lang.reflect.InvocationTargetException; /** * * Provides functionality to work with java.awt.EventQueue empty. * *

Timeouts used:
* QueueTool.WaitQueueEmptyTimeout - timeout to wait queue emptied
* QueueTool.QueueCheckingDelta - time delta to check result
* QueueTool.LockTimeout - time to wait queue locked after lock action has been put there
* QueueTool.InvocationTimeout - time for action was put into queue to be started
* QueueTool.MaximumLockingTime - maximum time to lock queue.
* * @see Timeouts * * @author Alexandre Iline (alexandre.iline@sun.com) * */ public class QueueTool implements Outputable, Timeoutable { private final static long WAIT_QUEUE_EMPTY_TIMEOUT = 180000; private final static long QUEUE_CHECKING_DELTA = 10; private final static long LOCK_TIMEOUT = 180000; private final static long MAXIMUM_LOCKING_TIME = 180000; private final static long INVOCATION_TIMEOUT = 180000; private static JemmyQueue jemmyQueue = null; private TestOut output; private Timeouts timeouts; private Locker locker; private Waiter lockWaiter; /** * Constructor. */ public QueueTool() { locker = new Locker(); lockWaiter = new Waiter(new Waitable() { public Object actionProduced(Object obj) { return(locker.isLocked() ? "" : null); } public String getDescription() { return("Event queue to be locked"); } }); setOutput(JemmyProperties.getProperties().getOutput()); setTimeouts(JemmyProperties.getProperties().getTimeouts()); } /** * Returns system EventQueue. * @return system EventQueue. */ public static EventQueue getQueue() { return(Toolkit.getDefaultToolkit().getSystemEventQueue()); } /** * Map to EventQueue.isDispatchThread(). * @return true if this thread is the AWT dispatching thread. */ public static boolean isDispatchThread() { return(getQueue().isDispatchThread()); } /** * Checks if system event queue is empty. * @return true if EventQueue is empty. */ public static boolean checkEmpty() { return(getQueue().peekEvent() == null); } /** * Shortcuts event if * ((JemmyProperties.getCurrentDispatchingModel() & JemmyProperties.SHORTCUT_MODEL_MASK) != 0) * and if executed in the dispatch thread. * Otherwise posts event. * @param event Event to dispatch. */ public static void processEvent(AWTEvent event) { if((JemmyProperties.getCurrentDispatchingModel() & JemmyProperties.SHORTCUT_MODEL_MASK) != 0) { installQueue(); } if((JemmyProperties.getCurrentDispatchingModel() & JemmyProperties.SHORTCUT_MODEL_MASK) != 0 && isDispatchThread()) { shortcutEvent(event); } else { postEvent(event); } } /** * Simply posts events into the system event queue. * @param event Event to dispatch. */ public static void postEvent(AWTEvent event) { getQueue().postEvent(event); } /** * Dispatches event ahead of all events staying in the event queue. * @param event an event to be shortcut. */ public static void shortcutEvent(AWTEvent event) { installQueue(); jemmyQueue.shortcutEvent(event); } /** * Installs own Jemmy EventQueue implementation. * The method is executed in dispatchmode only. * @see #uninstallQueue */ public static void installQueue() { if(jemmyQueue == null) { jemmyQueue = new JemmyQueue(); } jemmyQueue.install(); } /** * Uninstalls own Jemmy EventQueue implementation. * @see #installQueue */ public static void uninstallQueue() { if(jemmyQueue != null) { jemmyQueue.uninstall(); } } static { Timeouts.initDefault("QueueTool.WaitQueueEmptyTimeout", WAIT_QUEUE_EMPTY_TIMEOUT); Timeouts.initDefault("QueueTool.QueueCheckingDelta", QUEUE_CHECKING_DELTA); Timeouts.initDefault("QueueTool.LockTimeout", LOCK_TIMEOUT); Timeouts.initDefault("QueueTool.InvocationTimeout", INVOCATION_TIMEOUT); Timeouts.initDefault("QueueTool.MaximumLockingTime", MAXIMUM_LOCKING_TIME); } /** * Defines current timeouts. * * @param ts ?t? A collection of timeout assignments. * @see org.netbeans.jemmy.Timeouts * @see org.netbeans.jemmy.Timeoutable * @see #getTimeouts */ public void setTimeouts(Timeouts ts) { timeouts = ts; lockWaiter.setTimeouts(getTimeouts().cloneThis()); } /** * Return current timeouts. * @return the collection of current timeout assignments. * @see org.netbeans.jemmy.Timeouts * @see org.netbeans.jemmy.Timeoutable * @see #setTimeouts */ public Timeouts getTimeouts() { return(timeouts); } /** * Defines print output streams or writers. * @param out Identify the streams or writers used for print output. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #getOutput */ public void setOutput(TestOut out) { output = out; lockWaiter.setOutput(output.createErrorOutput()); } /** * Returns print output streams or writers. * @return an object that contains references to objects for * printing to output and err streams. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #setOutput */ public TestOut getOutput() { return(output); } /** * Waits for system event queue empty. * Uses "QueueTool.WaitQueueEmptyTimeout" milliseconds to wait. * @throws TimeoutExpiredException */ public void waitEmpty() { Waiter waiter = new Waiter(new Waitable() { public Object actionProduced(Object obj) { if(checkEmpty()) { return("Empty"); } return(null); } public String getDescription() { return("Wait event queue empty"); } }); waiter.setTimeoutsToCloneOf(timeouts, "QueueTool.WaitQueueEmptyTimeout"); waiter.setOutput(output); try { waiter.waitAction(null); } catch(TimeoutExpiredException e) { final AWTEvent event = getQueue().peekEvent(); // if event != null run toString in dispatch thread String eventToString = (event == null) ? "null" : (String)invokeSmoothly( new QueueTool.QueueAction("event.toString()") { public Object launch() { return event.toString(); } } ); getOutput().printErrLine("Event at the top of stack: " + eventToString); throw(e); } catch(InterruptedException e) { output.printStackTrace(e); } } /** * Waits for system event queue be empty for emptyTime milliseconds. * Uses "QueueTool.WaitQueueEmptyTimeout" milliseconds to wait. * * @param emptyTime time for the queue to stay empty. * @throws TimeoutExpiredException */ public void waitEmpty(long emptyTime) { StayingEmptyWaiter waiter = new StayingEmptyWaiter(emptyTime); waiter.setTimeoutsToCloneOf(timeouts, "QueueTool.WaitQueueEmptyTimeout"); waiter.setOutput(output); try { waiter.waitAction(null); } catch(TimeoutExpiredException e) { final AWTEvent event = getQueue().peekEvent(); String eventToString = (event == null) ? "null" : (String)invokeSmoothly( new QueueTool.QueueAction("event.toString()") { public Object launch() { return event.toString(); } } ); getOutput().printErrLine("Event at the top of stack: " + eventToString); throw(e); } catch(InterruptedException e) { output.printStackTrace(e); } } /** * Invokes action through EventQueue. * Does not wait for it execution. * @param action an action to be invoked. */ public void invoke(QueueAction action) { output.printTrace("Invoking \"" + action.getDescription() + "\" action through event queue"); EventQueue.invokeLater(action); } /** * Invokes runnable through EventQueue. * Does not wait for it execution. * @param runnable a runnable to be invoked. * @return QueueAction instance which can be use for execution monitoring. * @see QueueTool.QueueAction */ public QueueAction invoke(Runnable runnable) { QueueAction result = new RunnableRunnable(runnable); invoke(result); return(result); } /** * Invokes action through EventQueue. * Does not wait for it execution. * @param action an action to be invoked. * @param param action.launch(Object) method parameter. * @return QueueAction instance which can be use for execution monitoring. * @see QueueTool.QueueAction */ public QueueAction invoke(Action action, Object param) { QueueAction result = new ActionRunnable(action, param); invoke(result); return(result); } /** * Being executed outside of AWT dispatching thread, * invokes an action through the event queue. * Otherwise executes action.launch() method * directly. * @param action anaction to be executed. * @return Action result. */ public Object invokeSmoothly(QueueAction action) { if(!getQueue().isDispatchThread()) { return(invokeAndWait(action)); } else { try { return(action.launch()); } catch(Exception e) { throw(new JemmyException("Exception in " + action.getDescription(), e)); } } } /** * Being executed outside of AWT dispatching thread, * invokes a runnable through the event queue. * Otherwise executes runnable.run() method * directly. * @param runnable a runnable to be executed. */ public void invokeSmoothly(Runnable runnable) { if(!getQueue().isDispatchThread()) { invokeAndWait(runnable); } else { runnable.run(); } } /** * Being executed outside of AWT dispatching thread, * invokes an action through the event queue. * Otherwise executes action.launch(Object) method * directly. * @param action anaction to be executed. * @param param an action parameter * @return Action result. */ public Object invokeSmoothly(Action action, Object param) { if(!getQueue().isDispatchThread()) { return(invokeAndWait(action, param)); } else { return(action.launch(param)); } } /** * Invokes action through EventQueue. * Waits for it execution. * @param action an action to be invoked. * @return a result of action * @throws TimeoutExpiredException if action * was not executed in "QueueTool.InvocationTimeout" milliseconds. */ public Object invokeAndWait(QueueAction action) { class JemmyInvocationLock {} Object lock = new JemmyInvocationLock(); InvocationEvent event = new InvocationEvent(Toolkit.getDefaultToolkit(), action, lock, true); try { synchronized (lock) { getQueue().postEvent(event); lock.wait(); } } catch(InterruptedException e) { throw(new JemmyException("InterruptedException during " + action.getDescription() + " execution", e)); } if(action.getException() != null) { throw(new JemmyException("Exception in " + action.getDescription(), action.getException())); } if(event.getException() != null) { throw(new JemmyException("Exception in " + action.getDescription(), event.getException())); } return(action.getResult()); } /** * Invokes runnable through EventQueue. * Waits for it execution. * @param runnable a runnable to be invoked. * @throws TimeoutExpiredException if runnable * was not executed in "QueueTool.InvocationTimeout" milliseconds. */ public void invokeAndWait(Runnable runnable) { invokeAndWait(new RunnableRunnable(runnable)); } /** * Invokes action through EventQueue. * Waits for it execution. * May throw TimeoutExpiredException if action * was not executed in "QueueTool.InvocationTimeout" milliseconds. * @param action an action to be invoked. * @param param action.launch(Object method parameter. * @return a result of action * @throws TimeoutExpiredException if action * was not executed in "QueueTool.InvocationTimeout" milliseconds. */ public Object invokeAndWait(Action action, Object param) { return(invokeAndWait(new ActionRunnable(action, param))); } /** * Locks EventQueue. * Locking will be automatically aborted after * "QueueTool.MaximumLockingTime" milliseconds. * @see #unlock() * @throws TimeoutExpiredException */ public void lock() { output.printTrace("Locking queue."); invoke(locker); try { lockWaiter. getTimeouts(). setTimeout("Waiter.WaitingTime", timeouts. getTimeout("QueueTool.LockTimeout")); lockWaiter. getTimeouts(). setTimeout("Waiter.TimeDelta", timeouts. getTimeout("QueueTool.QueueCheckingDelta")); lockWaiter.waitAction(null); } catch(InterruptedException e) { output.printStackTrace(e); } } /** * Unlocks EventQueue. * @see #lock() */ public void unlock() { output.printTrace("Unlocking queue."); locker.setLocked(false); } /** * Locks event queue for "time" milliseconds. * Returns immediately after locking. * @param time a time to lock the queue for. */ public void lock(long time) { output.printTrace("Locking queue for " + Long.toString(time) + " milliseconds"); lock(); invoke(new UnlockPostponer(time)); } /** * Sais if last locking was expired. * @return true if last locking had beed expired. */ public boolean wasLockingExpired() { return(locker.expired); } /** * Action to be excuted through event queue. * Even if it was executed without waiting by invoke(QueueAction) * execution process can be monitored by getResult(), * getException(), getFinished() methods. */ public static abstract class QueueAction implements Runnable { private boolean finished; private Exception exception; private Object result; private String description; /** * Constructor. * @param description a description. */ public QueueAction(String description) { this.description = description; finished = false; exception = null; result = null; } /** * Method to implement action functionality. * @return an Object - action result * @throws Exception */ public abstract Object launch() throws Exception; /** */ public final void run() { finished = false; exception = null; result = null; try { result = launch(); } catch(Exception e) { exception = e; } finished = true; } /** * Action description. * @return the description. */ public String getDescription() { return(description); } /** * Returns action result if action has already been finished, * null otherwise. * @return an action result. */ public Object getResult() { return(result); } /** * Returns exception occured during action execution (if any). * @return the Exception happened inside launch() method. */ public Exception getException() { return(exception); } /** * Informs whether action has been finished or not. * @return true if this action have been finished */ public boolean getFinished() { return(finished); } } private static class JemmyQueue extends EventQueue { private boolean installed = false; public void shortcutEvent(AWTEvent event) { super.dispatchEvent(event); } protected void dispatchEvent(AWTEvent event) { //it's necessary to catch exception here. //because test might already fail by timeout //but generated events are still in stack try { super.dispatchEvent(event); } catch(Exception e) { //the exceptions should be printed into //Jemmy output - not System.out JemmyProperties.getCurrentOutput().printStackTrace(e); } } public synchronized void install() { if(!installed) { getQueue().push(this); installed = true; } } public synchronized void uninstall() { if(installed) { pop(); installed = false; } } } private class EventWaiter implements Runnable { boolean empty = true; long emptyTime; public EventWaiter(long emptyTime) { this.emptyTime = emptyTime; } public void run() { long startTime = System.currentTimeMillis(); while((empty = checkEmpty()) && (System.currentTimeMillis() - startTime) < emptyTime) { timeouts.sleep("QueueTool.QueueCheckingDelta"); } } } private class StayingEmptyWaiter extends Waiter { long emptyTime; public StayingEmptyWaiter(long emptyTime) { this.emptyTime = emptyTime; } public Object actionProduced(Object obj) { try { EventWaiter eventWaiter = new EventWaiter(emptyTime); EventQueue.invokeAndWait(eventWaiter); if(eventWaiter.empty && timeFromStart() <= super.getTimeouts().getTimeout("Waiter.WaitingTime")) { return("Reached"); } } catch(InterruptedException e) { output.printStackTrace(e); } catch(InvocationTargetException e) { output.printStackTrace(e); } return(null); } public String getDescription() { return("Wait event queue staying empty for " + Long.toString(emptyTime)); } } private class ActionRunnable extends QueueAction { Action action; Object param; public ActionRunnable(Action action, Object param) { super(action.getDescription()); this.action = action; this.param = param; } public Object launch() throws Exception { return(action.launch(param)); } } private class RunnableRunnable extends QueueAction { Runnable action; public RunnableRunnable(Runnable action) { super("Runnable"); this.action = action; } public Object launch() throws Exception { action.run(); return(null); } } private class Locker extends QueueAction { boolean locked = false; long wholeTime, deltaTime; boolean expired; public Locker() { super("Event queue locking"); } public Object launch() { wholeTime = timeouts.getTimeout("QueueTool.MaximumLockingTime"); deltaTime = timeouts.getTimeout("QueueTool.QueueCheckingDelta"); setLocked(true); expired = false; long startTime = System.currentTimeMillis(); while(isLocked()) { try { Thread.sleep(deltaTime); } catch(InterruptedException e) { getOutput().printStackTrace(e); } if(System.currentTimeMillis() - startTime > wholeTime) { getOutput().printLine("Locking has been expired!"); expired = true; break; } } return(null); } public void setLocked(boolean locked) { this.locked = locked; } public boolean isLocked() { return(locked); } } private class UnlockPostponer implements Runnable { long time; public UnlockPostponer(long time) { this.time = time; } public void run() { new Timeout("", time).sleep(); unlock(); } } } Jemmy2/src/org/netbeans/jemmy/image/0000755000175000017500000000000011572745222016354 5ustar tonytonyJemmy2/src/org/netbeans/jemmy/image/RoughImageFinder.java0000644000175000017500000001127211064436407022377 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.image; import java.awt.Point; import java.awt.image.BufferedImage; /** * Performs "rough" image search. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class RoughImageFinder implements ImageFinder { double roughness = .0; int bigWidth, bigHeight; int[][] bigPixels; /** * Creates an instance allowing to find an image inside the one * passed as parameter with some "roughness". * @param area - Image to search in. * @param roughness - Allowed */ public RoughImageFinder(BufferedImage area, double roughness) { this.roughness = roughness; bigWidth = area.getWidth(); bigHeight = area.getHeight(); bigPixels = new int[bigWidth][bigHeight]; for(int x = 0; x < bigWidth; x++) { for(int y = 0; y < bigHeight; y++) { bigPixels[x][y] = area.getRGB(x, y); } } } /** * Performs "rough" search. * @param image an image to search. * @param index an ordinal image location index. * @return Point where number of unmatching pixels less or equal to * image1.getWidth() * image1.getHeight() * roughness */ public Point findImage(BufferedImage image, int index) { int smallWidth = image.getWidth(); int smallHeight = image.getHeight(); int[][] smallPixels = new int[smallWidth][smallHeight]; for(int x = 0; x < smallWidth; x++) { for(int y = 0; y < smallHeight; y++) { smallPixels[x][y] = image.getRGB(x, y); } } double maxRoughPixels = (double)(smallWidth * smallHeight) * roughness; int count = 0; for(int X = 0; X <= bigWidth - smallWidth; X++) { for(int Y = 0; Y <= bigHeight - smallHeight; Y++) { int roughPixels = 0; for(int x = 0; x < smallWidth; x++) { for(int y = 0; y < smallHeight; y++) { if(smallPixels[x][y] != bigPixels[X + x][Y + y]) { roughPixels++; if(roughPixels > maxRoughPixels) { break; } } } if(roughPixels > maxRoughPixels) { break; } } if(roughPixels <= maxRoughPixels) { if(count == index) { return(new Point(X, Y)); } count++; } } } return(null); } } Jemmy2/src/org/netbeans/jemmy/image/ImageTool.java0000644000175000017500000001753611245712237021110 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.image; import java.awt.AWTException; import java.awt.Color; import java.awt.Component; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import org.netbeans.jemmy.JemmyException; /** * Contains util methods to work with images. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class ImageTool { /** * Gets an image from a rectange on screen. * @param rect a rectangle on screen in absolute screen coordinates. * @return a captured image. */ public static BufferedImage getImage(Rectangle rect) { try { return(new Robot().createScreenCapture(rect)); } catch(AWTException e) { throw(new JemmyException("Exception during screen capturing", e)); } } /** * Gets an image from a component. * @param comp a visible component. * @return a captured image. */ public static BufferedImage getImage(Component comp) { return(getImage(new Rectangle(comp.getLocationOnScreen(), comp.getSize()))); } /** * Gets the whole screen image. * @return a captured image. */ public static BufferedImage getImage() { return(getImage(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()))); } /** * Increases image. * @param image an image to enlarge. * @param zoom A scale. * @return a result image. */ public static BufferedImage enlargeImage(BufferedImage image, int zoom) { int wight = image.getWidth(); int height = image.getHeight(); BufferedImage result = new BufferedImage(wight * zoom, height * zoom, image.getType()); int rgb; for(int x = 0; x < wight; x++) { for(int y = 0; y < height; y++) { rgb = image.getRGB(x, y); for(int i = 0; i < zoom; i++) { for(int j = 0; j < zoom; j++) { result.setRGB(x * zoom + i, y * zoom + j, rgb); } } } } return(result); } /** * @deprecated Use subtractImage(BufferedImage, BufferedImage) instead. * @param minuend an image to subtract from. * @param deduction an image to subtract. * @return a result image. */ public static BufferedImage substractImage(BufferedImage minuend, BufferedImage deduction) { return(subtractImage(minuend, deduction)); } /** * Subtracts second image from first one. * Could be used to save file difference for future analysis. * @param minuend an image to subtract from. * @param deduction an image to subtract. * @return a result image. */ public static BufferedImage subtractImage(BufferedImage minuend, BufferedImage deduction) { return(subtractImage(minuend, deduction, 0, 0)); } /** * @deprecated Use subtractImage(BufferedImage, BufferedImage, int, int) instead. * @param minuend an image to subtract from. * @param deduction an image to subtract. * @return a result image. */ public static BufferedImage substractImage(BufferedImage minuend, BufferedImage deduction, int relativeX, int relativeY) { return(subtractImage(minuend, deduction, relativeX, relativeY)); } /** * Subtracts subimage from image. * Could be used to save file difference for future analysis. * @param minuend an image to subtract from. * @param deduction an image to subtract. * @param relativeX - deduction-in-minuend X coordinate * @param relativeY - deduction-in-minuend Y coordinate * @return a result image. */ public static BufferedImage subtractImage(BufferedImage minuend, BufferedImage deduction, int relativeX, int relativeY) { int mWidth = minuend.getWidth(); int mHeight = minuend.getHeight(); int dWidth = deduction.getWidth(); int dHeight = deduction.getHeight(); int maxWidth = (mWidth > relativeX + dWidth ) ? mWidth : (relativeX + dWidth); int maxHeight = (mHeight > relativeY + dHeight) ? mHeight : (relativeY + dHeight); BufferedImage result = new BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_RGB); int mColor, dColor; for(int x = 0; x < maxWidth; x++) { for(int y = 0; y < maxHeight; y++) { if(x >= mWidth || y >= mHeight) { mColor = 0; } else { mColor = minuend.getRGB(x, y); } if(x >= dWidth + relativeX || y >= dHeight + relativeY || x < relativeX || y < relativeY) { dColor = 0; } else { dColor = deduction.getRGB(x - relativeX, y - relativeY); } result.setRGB(x, y, subtractColors(mColor, dColor)); } } return(result); } private static int subtractColors(int mRGB, int dRGB) { Color mColor = new Color(mRGB); Color dColor = new Color(dRGB); int red = subtractColor(mColor.getRed() , dColor.getRed()); int green = subtractColor(mColor.getGreen(), dColor.getGreen()); int blue = subtractColor(mColor.getBlue() , dColor.getBlue()); return(new Color(red, green, blue).getRGB()); } private static int subtractColor(int mColor, int dColor) { if(mColor >= dColor) { return(mColor - dColor); } else { return(mColor - dColor + 0Xff); } } } Jemmy2/src/org/netbeans/jemmy/image/ColorImageComparator.java0000644000175000017500000001546011064436407023274 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.image; import java.awt.image.BufferedImage; /** * Compares two images with color mapping defined by ColorModel implementation. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class ColorImageComparator extends StrictImageComparator { ColorMap leftMap, rightMap; ImageComparator comparator = null; /** * Creates a comparator with a color maps. * Object created by this constructor behaves like StrictImageComparator. * Object created works faster because it does not create intermediate images * for another comparator. * @param map Map applied to both left and right images during comparision. */ public ColorImageComparator(ColorMap map) { leftMap = map; rightMap = map; } /** * Creates a comparator with map color mapping. * Actual comparision perfomed by comparator parameter. * @param map Map applied to both left and right images during comparision. * @param subComparator comporator to perform a comparision of to images with mapped colors. */ public ColorImageComparator(ColorMap map, ImageComparator subComparator) { this(map); this.comparator = subComparator; } /** * Creates a comparator with two color maps. * Object created by this constructor behaves like StrictImageComparator. * Object created works faster because it does not create intermediate images * for another comparator. * @param leftMap Map applied to the left image during comparision. * @param rightMap Map applied to the right image during comparision. */ public ColorImageComparator(ColorMap leftMap, ColorMap rightMap) { this.leftMap = leftMap; this.rightMap = rightMap; } /** * Creates a comparator with two color maps. * Actual comparision perfomed by comparator parameter. * @param leftMap Map applied to the left image during comparision. * @param rightMap Map applied to the right image during comparision. * @param subComparator comporator to perform a comparision of to images with mapped colors. */ public ColorImageComparator(ColorMap leftMap, ColorMap rightMap, ImageComparator subComparator) { this(leftMap, rightMap); this.comparator = subComparator; } /** * Compares images by ImageComparator passed into constructor, * or itself if no ImageComparator was passed, processing both images * by ColorMap instance before comparision. */ public boolean compare(BufferedImage image1, BufferedImage image2) { if(comparator != null) { return(comparator.compare(recolor(image1, leftMap), recolor(image2, rightMap))); } else { return(super.compare(image1, image2)); } } private BufferedImage recolor(BufferedImage src, ColorMap map) { BufferedImage result = new BufferedImage(src.getWidth(), src.getHeight(), src.getType()); for(int x = 0; x < src.getWidth(); x++) { for(int y = 0; y < src.getWidth(); y++) { result.setRGB(x, y, map.mapColor(src.getRGB(x, y))); } } return(result); } protected final boolean compareColors(int rgb1, int rgb2) { return(leftMap.mapColor(rgb1) == rightMap.mapColor(rgb2)); } /** * Interface to map colors during the comparision. */ public static interface ColorMap { /** * Maps one color into another. * @param rgb an original color. * @return a converted color. */ public int mapColor(int rgb); } /** * Turns foreground color to white, other - to black. */ public static class ForegroundColorMap implements ColorMap { int foreground; /** * Constructs a ColorImageComparator$ForegroundColorMap object. * @param foreground Foreground color. */ public ForegroundColorMap(int foreground) { this.foreground = foreground; } public int mapColor(int rgb) { return((rgb == foreground) ? 0xffffff : 0); } } /** * Turns background color to black, left others unchanged. */ public static class BackgroundColorMap implements ColorMap { int background; /** * Constructs a ColorImageComparator$BackgroundColorMap object. * @param background Background color. */ public BackgroundColorMap(int background) { this.background = background; } public int mapColor(int rgb) { return((rgb == background) ? 0 : rgb); } } } Jemmy2/src/org/netbeans/jemmy/image/ImageLoader.java0000644000175000017500000000503511245712237021370 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.image; import java.awt.image.BufferedImage; import java.io.IOException; /** * Interface for all classes performing image loading. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface ImageLoader { /** * Loads an image from file. * @param fileName a file to load image from. * @return a loaded image. * @throws IOException */ public BufferedImage load(String fileName) throws IOException; } Jemmy2/src/org/netbeans/jemmy/image/StrictImageFinder.java0000644000175000017500000001061311064436407022561 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.image; import java.awt.Point; import java.awt.image.BufferedImage; /** * Performs "strict" (i.e. based on all pixels matching) image search. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class StrictImageFinder implements ImageFinder { int bigWidth, bigHeight; int[][] bigPixels; /** * Creates an instance searching subimages insige a parameter image. * @param area - Image to search in. */ public StrictImageFinder(BufferedImage area) { bigWidth = area.getWidth(); bigHeight = area.getHeight(); bigPixels = new int[bigWidth][bigHeight]; for(int x = 0; x < bigWidth; x++) { for(int y = 0; y < bigHeight; y++) { bigPixels[x][y] = area.getRGB(x, y); } } } /** * Searchs for an image inside image passed into constructor. * @param image an image to search. * @param index an ordinal image location index. If equal to 1, for example, * second appropriate location will be found. * @return Left-up corner coordinates of image location. */ public Point findImage(BufferedImage image, int index) { int smallWidth = image.getWidth(); int smallHeight = image.getHeight(); int[][] smallPixels = new int[smallWidth][smallHeight]; for(int x = 0; x < smallWidth; x++) { for(int y = 0; y < smallHeight; y++) { smallPixels[x][y] = image.getRGB(x, y); } } boolean good; int count = 0; for(int X = 0; X <= bigWidth - smallWidth; X++) { for(int Y = 0; Y <= bigHeight - smallHeight; Y++) { good = true; for(int x = 0; x < smallWidth; x++) { for(int y = 0; y < smallHeight; y++) { if(smallPixels[x][y] != bigPixels[X + x][Y + y]) { good = false; break; } } if(!good) { break; } } if(good) { if(count == index) { return(new Point(X, Y)); } count++; } } } return(null); } } Jemmy2/src/org/netbeans/jemmy/image/ImageComparator.java0000644000175000017500000000510311064436407022266 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.image; import java.awt.image.BufferedImage; /** * Interface for all classes performing image comparision. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface ImageComparator { /** * Should return true if images matches, false otherwise. * @param image1 an image to compare. * @param image2 an image to compare. * @return true if images match each other. */ public boolean compare(BufferedImage image1, BufferedImage image2); } Jemmy2/src/org/netbeans/jemmy/image/package.html0000644000175000017500000000045111064436407020633 0ustar tonytony Image library

Image library

Contains classes allowing to compare two images and to find one image inside another.

@since 9 Nov 2002
Jemmy2/src/org/netbeans/jemmy/image/FileImageComparator.java0000644000175000017500000001020111245712237023060 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.image; import java.awt.image.BufferedImage; import java.io.IOException; import org.netbeans.jemmy.JemmyException; /** * Allowes compares images in memory to ones stored in files * and compare such images one with another. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class FileImageComparator { ImageLoader loader; ImageComparator comparator; /** * Constructs a FileImageComparator object. * @param comparator - ImageComparator to be used for image comparision. * @param loader - ImageLoader to be used for image loading. */ public FileImageComparator(ImageComparator comparator, ImageLoader loader) { this.loader = loader; this.comparator = comparator; } /** * Compares an image with one stored in file. * Comparision is performed by ImageComparator passed into constructor. * Image is loaded by ImageLoader passed into constructor. * @param image an image to compare. * @param fileName a file containing an image to compare. * @return true if images match each other. */ public boolean compare(BufferedImage image, String fileName) { try { return(comparator.compare(image, loader.load(fileName))); } catch(IOException e) { throw(new JemmyException("IOException during image loading", e)); } } /** * Compares two image stored in files.. * Comparision is performed by ImageComparator passed into constructor. * Images are loaded by ImageLoader passed into constructor. * @param fileName1 a file containing an image to compare. * @param fileName2 a file containing an image to compare. * @return true if images match each other. */ public boolean compare(String fileName1, String fileName2) { try { return(comparator.compare(loader.load(fileName1), loader.load(fileName2))); } catch(IOException e) { throw(new JemmyException("IOException during image loading", e)); } } } Jemmy2/src/org/netbeans/jemmy/image/PNGImageSaver.java0000644000175000017500000000534111245712237021607 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.image; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import org.netbeans.jemmy.util.PNGEncoder; /** * Allowes to process PNF image format. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class PNGImageSaver implements ImageSaver { /** * Saves an image into a PNG image file. */ public void save(BufferedImage image, String fileName) throws IOException{ new PNGEncoder(new BufferedOutputStream(new FileOutputStream(fileName)), PNGEncoder.COLOR_MODE). encode(image); } } Jemmy2/src/org/netbeans/jemmy/image/StrictImageComparator.java0000644000175000017500000000661011245712237023462 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.image; import java.awt.image.BufferedImage; /** * Compares two images strictly (i.e. all the pixel colors should match). * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class StrictImageComparator implements ImageComparator { /** * Checks images sizes and pixels. * Compares one pixel after another untill one will be different. * @param image1 an image to compare. * @param image2 an image to compare. * @return True if all the pixels match, false otherwise. */ public boolean compare(BufferedImage image1, BufferedImage image2) { if(image1.getWidth() != image2.getWidth() || image1.getHeight() != image2.getHeight()) { return(false); } for(int x = 0; x < image1.getWidth(); x++) { for(int y = 0; y < image1.getHeight(); y++) { if(!compareColors(image1.getRGB(x, y), image2.getRGB(x, y))) { return(false); } } } return(true); } /** * Could be used to override the way of comparing colors. * @param rgb1 a color to compare. * @param rgb2 a color to compare. * @return true if colors are equal. */ protected boolean compareColors(int rgb1, int rgb2) { return(rgb1 == rgb2); } } Jemmy2/src/org/netbeans/jemmy/image/RoughImageComparator.java0000644000175000017500000000721611064436407023302 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.image; import java.awt.image.BufferedImage; /** * Compares two images roughly (i.e. not all of the pixel colors should match). * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class RoughImageComparator implements ImageComparator { double roughness = .0; /** * Creates a comparator with roughness allowed roughness. * @param roughness Allowed comparision roughness. */ public RoughImageComparator(double roughness) { this.roughness = roughness; } /** * Compares two images with allowed roughness. * @param image1 an image to compare. * @param image2 an image to compare. * @return true if images have the same sizes and * number of unmatching pixels less or equal to * image1.getWidth() * image1.getHeight() * roughness */ public boolean compare(BufferedImage image1, BufferedImage image2) { if(image1.getWidth() != image2.getWidth() || image1.getHeight() != image2.getHeight()) { return(false); } double maxRoughPixels = (double)(image1.getWidth() * image1.getHeight()) * roughness; int errorCount = 0; for(int x = 0; x < image1.getWidth(); x++) { for(int y = 0; y < image1.getHeight(); y++) { if(image1.getRGB(x, y) != image2.getRGB(x, y)) { errorCount++; if(errorCount > maxRoughPixels) { return(false); } } } } return(true); } } Jemmy2/src/org/netbeans/jemmy/image/ImageSaver.java0000644000175000017500000000506111245712237021241 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.image; import java.awt.image.BufferedImage; import java.io.IOException; /** * Interface for classes performing image saving. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface ImageSaver { /** * Should save image into file. * @param image an image to be saved. * @param fileName a file to load image from. * @throws IOException */ public void save(BufferedImage image, String fileName) throws IOException; } Jemmy2/src/org/netbeans/jemmy/image/ImageFinder.java0000644000175000017500000000532411245712237021372 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.image; import java.awt.Point; import java.awt.image.BufferedImage; /** * Interface for all classes performing image lookup. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface ImageFinder { /** * Should return location if image lays inside an image represented by this object. * @param image an image to search. * @param index an ordinal image location index. If equal to 1, for example, * second appropriate location will be found. * @return Image location coordinates if image was found, null otherwise. */ public Point findImage(BufferedImage image, int index); } Jemmy2/src/org/netbeans/jemmy/image/PNGImageLoader.java0000644000175000017500000000513711245712237021740 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy.image; import java.awt.image.BufferedImage; import java.io.FileInputStream; import java.io.IOException; import org.netbeans.jemmy.util.PNGDecoder; /** * Allowes to process PNF image format. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class PNGImageLoader implements ImageLoader { /** * Loads an image from a PNG image file. */ public BufferedImage load(String fileName) throws IOException { return(new PNGDecoder(new FileInputStream(fileName)).decode()); } } Jemmy2/src/org/netbeans/jemmy/ObjectBrowser.java0000644000175000017500000001217211245712237020707 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * * Class to display information about object: fields, methods, ancestors and so on. * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class ObjectBrowser implements Outputable { private Object object; private TestOut output; /** * Constructor. */ public ObjectBrowser() { } /** * Defines print output streams or writers. * @param out Identify the streams or writers used for print output. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #getOutput */ public void setOutput(TestOut out) { output = out; } /** * Returns print output streams or writers. * @return an object that contains references to objects for * printing to output and err streams. * @see org.netbeans.jemmy.Outputable * @see org.netbeans.jemmy.TestOut * @see #setOutput */ public TestOut getOutput() { return(output); } /** * Specifies the object value. * @param obj Object to work with. * @see #getObject */ public void setObject(Object obj) { object = obj; } /** * Returns the object value. * @return Current object. * @see #setObject */ public Object getObject() { return(object); } /** * Prints toString() information. */ public void printToString() { output.printLine(object.toString()); } /** * Prints object fields names and values. */ public void printFields() { Class cl = object.getClass(); output.printLine("Class: " + cl.getName()); output.printLine("Fields: "); Field[] fields = cl.getFields(); for(int i = 0; i < fields.length; i++) { output.printLine(Modifier.toString(fields[i].getModifiers()) + " " + fields[i].getType().getName() + " " + fields[i].getName()); Object value = "Inaccessible"; try { value = fields[i].get(object); } catch(IllegalAccessException e) { } output.printLine(" Value: " + value.toString()); } } /** * Prints object methods names and parameters. */ public void printMethods() { Class cl = object.getClass(); output.printLine("Class: " + cl.getName()); output.printLine("Methods: "); Method[] methods = cl.getMethods(); for(int i = 0; i < methods.length; i++) { output.printLine(Modifier.toString(methods[i].getModifiers()) + " " + methods[i].getReturnType().getName() + " " + methods[i].getName()); Class[] params = methods[i].getParameterTypes(); for(int j = 0; j < params.length; j++) { output.printLine(" " + params[j].getName()); } } } /** * Prints allsuperclasses names. */ public void printClasses() { Class cl = object.getClass(); do { output.printLine(cl.getName()); } while((cl = cl.getSuperclass()) != null); } /** * Prints everything. */ public void printFull() { printFields(); printMethods(); } } Jemmy2/src/org/netbeans/jemmy/Timeouts.java0000644000175000017500000003043011245712347017745 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.util.Enumeration; import java.util.Hashtable; import java.util.Properties; /** * * Class to store and process a set of timeout values. * * @see #setDefault(String, long) * @see #getDefault(String) * @see #setTimeout(String, long) * @see #getTimeout(String) * * @author Alexandre Iline (alexandre.iline@sun.com) */ public class Timeouts extends Object{ private static final long DELTA_TIME = 100; private static Timeouts defaults; private Hashtable timeouts; private static double timeoutsScale = -1; /** * Creates empty Timeouts object. */ public Timeouts() { super(); timeouts = new Hashtable(); setTimeout("Timeouts.DeltaTimeout", DELTA_TIME); try { load(); } catch(IOException e) { } } /** * Stores default timeout value. * @param name Timeout name. * @param newValue Timeout value. * @see #getDefault(String) * @see #initDefault(String, long) * @see #containsDefault(String) */ public static void setDefault(String name, long newValue) { defaults.setTimeout(name, newValue); } /** * Sets default timeout value if it was not set before. * @param name Timeout name. * @param newValue Timeout value. * @see #setDefault(String, long) * @see #getDefault(String) * @see #containsDefault(String) */ public static void initDefault(String name, long newValue) { defaults.initTimeout(name, newValue); } /** * Gets default timeout value. * @param name Timeout name. * @return Timeout value or -1 if timeout is not defined. * @see #setDefault(String, long) * @see #initDefault(String, long) * @see #containsDefault(String) */ public static long getDefault(String name) { return(defaults.getTimeout(name)); } /** * Check that default timeout value was defined. * @param name Timeout name. * @return True if timeout has been defined, false otherwise. * @see #setDefault(String, long) * @see #getDefault(String) * @see #initDefault(String, long) */ public static boolean containsDefault(String name) { return(defaults.contains(name)); } static { defaults = new Timeouts(); } /** * Loads default timeouts values. * * @param stream Stream to load timeouts from. * @see org.netbeans.jemmy.Timeouts#loadDefaults(String) * @see org.netbeans.jemmy.Timeouts#loadDefaults() * @exception IOException */ public void loadDefaults(InputStream stream) throws IOException{ defaults.load(stream); } /** * Loads default timeouts values from file. * * @param fileName File to load timeouts from. * @see org.netbeans.jemmy.Timeouts#loadDefaults(InputStream) * @see org.netbeans.jemmy.Timeouts#loadDefaults(String) * @exception IOException * @exception FileNotFoundException */ public void loadDefaults(String fileName) throws FileNotFoundException, IOException { defaults.load(fileName); } /** * Loads default timeouts values. * Uses jemmy.timeouts system property to get timeouts file. * * @see org.netbeans.jemmy.Timeouts#loadDefaults(InputStream) * @see org.netbeans.jemmy.Timeouts#loadDefaults(String) * @exception IOException * @exception FileNotFoundException */ public void loadDefaults() throws FileNotFoundException, IOException { defaults.load(); } /** * Creates Timeout new object by name and getTimeout(name) value. * @param name Timeout name. * @return a Timeout instance. */ public Timeout create(String name) { return(new Timeout(name, getTimeout(name))); } /** * Create timeout for "Timeouts.DeltaTimeout" name. * @return a Timeout instance. */ public Timeout createDelta() { return(create("Timeouts.DeltaTimeout")); } /** * Checks if timeout has already been defined in this timeout instance. * @param name Timeout name. * @return True if timeout has been defined, false otherwise. * @see #containsDefault(String) */ public boolean contains(String name) { return(timeouts.containsKey(name)); } /** * Sets new timeout value. * @param name Timeout name. * @param newValue Timeout value. * @return old timeout value * @see #getTimeout */ public long setTimeout(String name, long newValue) { long oldValue = -1; if(contains(name)) { oldValue = getTimeout(name); timeouts.remove(name); } timeouts.put(name, new Long(newValue)); return(oldValue); } /** * Gets timeout value. * It timeout was not defined in this instance, * returns default timeout value. * @param name Timeout name. * @return Timeout value. * @see #getDefault(String) * @see #setTimeout */ public long getTimeout(String name) { long timeout; if(contains(name) && timeouts.get(name) != null) { timeout = ((Long) timeouts.get(name)).longValue(); timeout = (long) ((double) timeout * getTimeoutsScale()); } else if(this != defaults) { timeout = getDefault(name); } else { timeout = -1; } return timeout; } /** * Gets "Timeouts.DeltaTimeout" timeout value. * @return Timeout value. * @see #getDefault(String) */ public long getDeltaTimeout() { return(getTimeout("Timeouts.DeltaTimeout")); } /** * Sets timeout value if it was not set before. * @param name Timeout name. * @param newValue Timeout value. * @return old timeout value */ public long initTimeout(String name, long newValue) { long result = getTimeout(name); if(!contains(name)) { setTimeout(name, newValue); } return(result); } /** * Creates a copy of the current timeouts set. * @return A copy. */ public Timeouts cloneThis() { Timeouts t = new Timeouts(); Enumeration e = timeouts.keys(); String name = ""; while(e.hasMoreElements()) { name = (String)e.nextElement(); t.setTimeout(name, getTimeout(name)); } return(t); } /** * Sleeps for the "name" timeout value. * Can throw InterruptedException if current thread was interrupted. * * @param name Timeout name. * @exception InterruptedException */ public void eSleep(String name) throws InterruptedException{ if(contains(name) || defaults.contains(name)) { Thread.currentThread().sleep(getTimeout(name)); } } /** * Sleeps for the "name" timeout value. * Does not throw InterruptedException anyway. * @param name Timeout name. */ public void sleep(String name) { create(name).sleep(); } /** * Prins all defined timeouts. * @param pw PrintWriter to print into. */ public void print(PrintWriter pw) { Enumeration e = timeouts.keys(); String name = ""; while(e.hasMoreElements()) { name = (String)e.nextElement(); pw.println(name + " = " + Long.toString(getTimeout(name))); } pw.println("Default values:"); e = defaults.timeouts.keys(); name = ""; while(e.hasMoreElements()) { name = (String)e.nextElement(); if(!contains(name)) { pw.println(name + " = " + Long.toString(getDefault(name))); } } } /** * Prins all defined timeouts. * @param ps PrintStream to print into. */ public void print(PrintStream ps) { print(new PrintWriter(ps)); } /** * Loads timeouts values. * * @param stream Stream to load timeouts from. * @see org.netbeans.jemmy.Timeouts#load(String) * @see org.netbeans.jemmy.Timeouts#load() * @exception IOException */ public void load(InputStream stream) throws IOException{ Properties props = new Properties(); props.load(stream); Enumeration propNames = props.propertyNames(); long propValue = -1; String propName = null; while(propNames.hasMoreElements()) { propName = (String)propNames.nextElement(); propValue = -1; propValue = (new Long(props.getProperty(propName))).longValue(); setTimeout(propName, propValue); } } /** * Loads timeouts values from file. * * @param fileName File to load timeouts from. * @see org.netbeans.jemmy.Timeouts#load(InputStream) * @see org.netbeans.jemmy.Timeouts#load(String) * @exception IOException * @exception FileNotFoundException */ public void load(String fileName) throws FileNotFoundException, IOException { load(new FileInputStream(fileName)); } /** * Loads timeouts values. * Uses jemmy.timeouts system property to get timeouts file. * * @see org.netbeans.jemmy.Timeouts#load(InputStream) * @see org.netbeans.jemmy.Timeouts#load(String) * @exception IOException * @exception FileNotFoundException */ public void load() throws FileNotFoundException, IOException { if(System.getProperty("jemmy.timeouts") != null && !System.getProperty("jemmy.timeouts").equals("")) { load(System.getProperty("jemmy.timeouts")); } } /** * Loads debug timeouts values. * * @exception IOException */ public void loadDebugTimeouts() throws IOException { load(getClass().getClassLoader().getResourceAsStream("org/netbeans/jemmy/debug.timeouts")); } /** * Get timeouts scale. * Uses jemmy.timeouts.scale system property to get the value. * @return timeouts scale or 1 if the property is not set. */ public static double getTimeoutsScale() { if (timeoutsScale == -1) { String s = System.getProperty("jemmy.timeouts.scale", "1"); try { timeoutsScale = Double.parseDouble(s); } catch (NumberFormatException e){ timeoutsScale = 1; } } if (timeoutsScale < 0) { timeoutsScale = 1; } return timeoutsScale; } /** * This method is designed to be used by unit test for testing purpose. */ static void resetTimeoutScale() { timeoutsScale = -1; } } Jemmy2/src/org/netbeans/jemmy/Scenario.java0000644000175000017500000000562511064436407017706 0ustar tonytony/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): Alexandre Iline. * * The Original Software is the Jemmy library. * The Initial Developer of the Original Software is Alexandre Iline. * All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * * * $Id$ $Revision$ $Date$ * */ package org.netbeans.jemmy; /** * * A test scenario. This interface provides a mechanism for * putting something into execution. The execution is conditioned * in a very general way by passing a java.lang.Object * to it's runIt method. * * @see Test * * @author Alexandre Iline (alexandre.iline@sun.com) */ public interface Scenario { /** * Defines a way to execute this test scenario. * @param param An object passed to configure the test scenario * execution. For example, this parameter might be a * java.lang.String[] object that lists the * command line arguments to the Java application corresponding * to a test. * @return an int that tells something about the execution. * For, example, a status code. */ public int runIt(Object param); }